From a757d76182b48b5fd12b74feb82c564568567140 Mon Sep 17 00:00:00 2001 From: Szymon Jastrzebski Date: Thu, 14 Sep 2017 12:10:53 +0200 Subject: [PATCH] [PROJECT][C++] Reformatting the whole project The refactoring was requested by yj99.shin. With this change, the cpplint does not find any more errors. The change has been applied to C++ files only. [Verification] Code compiles. Conflicts: src/callhistory/callhistory.cc src/callhistory/callhistory.h src/download/download_instance.cc src/mediacontroller/mediacontroller_types.cc src/sensor/sensor_service.cc Change-Id: I83e99c735d6dcc473d064c140c0e12b01ea9789a Signed-off-by: Szymon Jastrzebski --- src/account/account_extension.cc | 10 +- src/account/account_extension.h | 2 +- src/account/account_instance.cc | 95 +- src/account/account_instance.h | 45 +- src/account/account_manager.cc | 127 +- src/account/account_manager.h | 35 +- src/alarm/alarm_extension.cc | 9 +- src/alarm/alarm_extension.h | 2 +- src/alarm/alarm_instance.cc | 22 +- src/alarm/alarm_instance.h | 8 +- src/alarm/alarm_manager.cc | 163 +- src/alarm/alarm_manager.h | 11 +- src/alarm/alarm_utils.cc | 44 +- src/alarm/alarm_utils.h | 17 +- src/application/application.cc | 2 +- src/application/application.h | 4 +- src/application/application_extension.cc | 6 +- src/application/application_extension.h | 4 +- src/application/application_instance.cc | 59 +- src/application/application_instance.h | 7 +- src/application/application_manager.cc | 619 ++--- src/application/application_manager.h | 49 +- src/application/application_utils.cc | 68 +- src/application/application_utils.h | 30 +- src/application/requested_application_control.cc | 44 +- src/application/requested_application_control.h | 5 +- src/archive/archive_callback_data.cc | 1011 ++++---- src/archive/archive_callback_data.h | 320 ++- src/archive/archive_extension.cc | 29 +- src/archive/archive_extension.h | 15 +- src/archive/archive_file.cc | 1119 ++++---- src/archive/archive_file.h | 226 +- src/archive/archive_file_entry.cc | 166 +- src/archive/archive_file_entry.h | 70 +- src/archive/archive_instance.cc | 925 ++++--- src/archive/archive_instance.h | 62 +- src/archive/archive_manager.cc | 145 +- src/archive/archive_manager.h | 46 +- src/archive/archive_utils.cc | 342 ++- src/archive/archive_utils.h | 17 +- src/archive/defs.h | 82 +- src/archive/filesystem_file.cc | 51 +- src/archive/filesystem_file.h | 51 +- src/archive/filesystem_node.cc | 962 ++++--- src/archive/filesystem_node.h | 363 ++- src/archive/filesystem_path.cc | 203 +- src/archive/filesystem_path.h | 62 +- src/archive/un_zip.cc | 709 +++-- src/archive/un_zip.h | 130 +- src/archive/un_zip_extract_request.cc | 734 +++--- src/archive/un_zip_extract_request.h | 107 +- src/archive/zip.cc | 187 +- src/archive/zip.h | 55 +- src/archive/zip_add_request.cc | 866 +++---- src/archive/zip_add_request.h | 84 +- src/badge/badge_extension.cc | 7 +- src/badge/badge_instance.cc | 41 +- src/badge/badge_instance.h | 2 +- src/badge/badge_manager.cc | 51 +- src/badge/badge_manager.h | 8 +- src/bluetooth/bluetooth_adapter.cc | 642 +++-- src/bluetooth/bluetooth_adapter.h | 63 +- src/bluetooth/bluetooth_class.cc | 158 +- src/bluetooth/bluetooth_class.h | 6 +- src/bluetooth/bluetooth_device.cc | 60 +- src/bluetooth/bluetooth_device.h | 15 +- src/bluetooth/bluetooth_extension.cc | 11 +- src/bluetooth/bluetooth_extension.h | 3 +- src/bluetooth/bluetooth_gatt_service.cc | 242 +- src/bluetooth/bluetooth_gatt_service.h | 35 +- src/bluetooth/bluetooth_health_application.cc | 17 +- src/bluetooth/bluetooth_health_application.h | 13 +- src/bluetooth/bluetooth_health_channel.cc | 39 +- src/bluetooth/bluetooth_health_channel.h | 17 +- src/bluetooth/bluetooth_health_profile_handler.cc | 104 +- src/bluetooth/bluetooth_health_profile_handler.h | 25 +- src/bluetooth/bluetooth_instance.cc | 187 +- src/bluetooth/bluetooth_instance.h | 10 +- src/bluetooth/bluetooth_le_adapter.cc | 272 +- src/bluetooth/bluetooth_le_adapter.h | 15 +- src/bluetooth/bluetooth_le_device.cc | 216 +- src/bluetooth/bluetooth_le_device.h | 17 +- src/bluetooth/bluetooth_privilege.cc | 6 +- src/bluetooth/bluetooth_privilege.h | 8 +- src/bluetooth/bluetooth_service_handler.cc | 14 +- src/bluetooth/bluetooth_service_handler.h | 6 +- src/bluetooth/bluetooth_socket.cc | 47 +- src/bluetooth/bluetooth_socket.h | 6 +- src/bluetooth/bluetooth_util.cc | 20 +- src/bluetooth/bluetooth_util.h | 8 +- src/bookmark/bookmark_extension.cc | 14 +- src/bookmark/bookmark_instance.cc | 141 +- src/bookmark/bookmark_instance.h | 3 +- src/calendar/calendar.cc | 431 ++-- src/calendar/calendar.h | 8 +- src/calendar/calendar_extension.cc | 21 +- src/calendar/calendar_extension.h | 2 +- src/calendar/calendar_instance.cc | 184 +- src/calendar/calendar_instance.h | 6 +- src/calendar/calendar_item.cc | 626 ++--- src/calendar/calendar_item.h | 126 +- src/calendar/calendar_manager.cc | 71 +- src/calendar/calendar_manager.h | 3 +- src/calendar/calendar_plugin.cc | 56 +- src/calendar/calendar_record.cc | 137 +- src/calendar/calendar_record.h | 75 +- src/callhistory/callhistory.cc | 221 +- src/callhistory/callhistory.h | 39 +- src/callhistory/callhistory_extension.cc | 3 +- src/callhistory/callhistory_extension.h | 2 +- src/callhistory/callhistory_instance.cc | 16 +- src/callhistory/callhistory_instance.h | 11 +- src/callhistory/callhistory_types.h | 6 +- src/callhistory/callhistory_utils.cc | 290 +-- src/callhistory/callhistory_utils.h | 14 +- src/common/GDBus/auto_gen_interface.h | 409 ++- src/common/GDBus/connection.cpp | 38 +- src/common/GDBus/connection.h | 24 +- src/common/GDBus/gdbus_powerwrapper.cc | 83 +- src/common/GDBus/gdbus_powerwrapper.h | 13 +- src/common/GDBus/proxy.cpp | 169 +- src/common/GDBus/proxy.h | 136 +- src/common/XW_Extension.cc | 16 +- src/common/XW_Extension.h | 29 +- src/common/XW_Extension_EntryPoints.h | 13 +- src/common/XW_Extension_Permissions.h | 9 +- src/common/XW_Extension_Runtime.h | 14 +- src/common/XW_Extension_SyncMessage.h | 15 +- src/common/assert.h | 16 +- src/common/converter.cc | 15 +- src/common/converter.h | 8 +- src/common/current_application.cc | 25 +- src/common/current_application.h | 2 +- src/common/deleter.h | 46 +- src/common/extension.cc | 109 +- src/common/extension.h | 30 +- src/common/filesystem/filesystem_provider.cc | 15 +- src/common/filesystem/filesystem_provider.h | 5 +- .../filesystem/filesystem_provider_deviced.cc | 169 +- .../filesystem/filesystem_provider_deviced.h | 13 +- .../filesystem/filesystem_provider_storage.cc | 67 +- .../filesystem/filesystem_provider_storage.h | 4 +- src/common/filesystem/filesystem_provider_types.h | 11 +- src/common/filesystem/filesystem_storage.cc | 21 +- src/common/filesystem/filesystem_storage.h | 30 +- src/common/filter-utils.cc | 48 +- src/common/filter-utils.h | 135 +- src/common/logger.cc | 13 +- src/common/logger.h | 204 +- src/common/optional.h | 86 +- src/common/picojson.h | 1467 ++++++----- src/common/platform_exception.cc | 11 +- src/common/platform_exception.h | 17 +- src/common/platform_result.cc | 11 +- src/common/platform_result.h | 25 +- src/common/scope_exit.h | 26 +- src/common/task-queue.cpp | 56 +- src/common/task-queue.h | 193 +- src/common/tizen_instance.cc | 25 +- src/common/tizen_instance.h | 9 +- src/common/tizen_result.cc | 16 +- src/common/tizen_result.h | 17 +- src/common/tools.cc | 83 +- src/common/tools.h | 60 +- src/common/typeutil.h | 105 +- src/common/utils.h | 6 +- src/contact/addressbook.cc | 336 +-- src/contact/addressbook.h | 35 +- src/contact/contact_extension.cc | 31 +- src/contact/contact_instance.cc | 240 +- src/contact/contact_instance.h | 12 +- src/contact/contact_manager.cc | 667 ++--- src/contact/contact_manager.h | 38 +- src/contact/contact_search_engine.cc | 718 +++--- src/contact/contact_search_engine.h | 100 +- src/contact/contact_util.cc | 1280 ++++----- src/contact/contact_util.h | 147 +- src/contact/person.cc | 103 +- src/contact/person.h | 2 +- src/content/content_extension.cc | 3 +- src/content/content_extension.h | 2 +- src/content/content_filter.cc | 36 +- src/content/content_filter.h | 8 +- src/content/content_instance.cc | 311 ++- src/content/content_instance.h | 11 +- src/content/content_manager.cc | 551 ++-- src/content/content_manager.h | 30 +- .../convergence_app_communication_service.cc | 155 +- .../convergence_app_communication_service.h | 67 +- src/convergence/convergence_channel_info.cc | 24 +- src/convergence/convergence_channel_info.h | 11 +- src/convergence/convergence_client_info.cc | 18 +- src/convergence/convergence_client_info.h | 8 +- src/convergence/convergence_device.cc | 48 +- src/convergence/convergence_device.h | 32 +- src/convergence/convergence_extension.cc | 11 +- src/convergence/convergence_extension.h | 2 +- src/convergence/convergence_instance.cc | 380 +-- src/convergence/convergence_instance.h | 59 +- src/convergence/convergence_manager.cc | 150 +- src/convergence/convergence_manager.h | 36 +- src/convergence/convergence_payload.cc | 27 +- src/convergence/convergence_payload.h | 17 +- .../convergence_remote_app_control_service.cc | 124 +- .../convergence_remote_app_control_service.h | 35 +- src/convergence/convergence_service.cc | 59 +- src/convergence/convergence_service.h | 42 +- src/convergence/convergence_utils.cc | 66 +- src/convergence/convergence_utils.h | 42 +- src/datacontrol/datacontrol_extension.cc | 4 +- src/datacontrol/datacontrol_instance.cc | 733 +++--- src/datacontrol/datacontrol_instance.h | 84 +- src/download/download_extension.cc | 8 +- src/download/download_instance.cc | 248 +- src/download/download_instance.h | 46 +- src/exif/exif_extension.cc | 11 +- src/exif/exif_gps_location.cc | 41 +- src/exif/exif_gps_location.h | 12 +- src/exif/exif_information.cc | 217 +- src/exif/exif_information.h | 52 +- src/exif/exif_instance.cc | 196 +- src/exif/exif_tag_saver.cc | 62 +- src/exif/exif_tag_saver.h | 17 +- src/exif/exif_util.cc | 32 +- src/exif/exif_util.h | 17 +- src/exif/get_exif_info.cc | 151 +- src/exif/get_exif_info.h | 9 +- src/exif/jpeg_file.cc | 250 +- src/exif/jpeg_file.h | 43 +- src/exif/rational.cc | 44 +- src/exif/rational.h | 9 +- src/feedback/feedback_extension.cc | 5 +- src/feedback/feedback_instance.cc | 39 +- src/feedback/feedback_instance.h | 11 +- src/feedback/feedback_manager.cc | 126 +- src/feedback/feedback_manager.h | 24 +- src/filesystem/filesystem_extension.cc | 3 +- src/filesystem/filesystem_extension.h | 2 +- src/filesystem/filesystem_file.cc | 24 +- src/filesystem/filesystem_file.h | 2 +- src/filesystem/filesystem_instance.cc | 156 +- src/filesystem/filesystem_instance.h | 21 +- src/filesystem/filesystem_manager.cc | 176 +- src/filesystem/filesystem_manager.h | 66 +- src/filesystem/filesystem_stat.cc | 20 +- src/filesystem/filesystem_utils.h | 2 +- src/humanactivitymonitor/gesture_manager.cc | 51 +- src/humanactivitymonitor/gesture_manager.h | 10 +- .../humanactivitymonitor_extension.cc | 3 +- .../humanactivitymonitor_instance.cc | 55 +- .../humanactivitymonitor_instance.h | 45 +- .../humanactivitymonitor_manager.cc | 581 +++-- .../humanactivitymonitor_manager.h | 24 +- src/inputdevice/inputdevice_extension.cc | 11 +- src/inputdevice/inputdevice_extension.h | 7 +- src/inputdevice/inputdevice_instance.cc | 6 +- src/inputdevice/inputdevice_instance.h | 7 +- src/iotcon/iotcon_client_manager.cc | 19 +- src/iotcon/iotcon_client_manager.h | 16 +- src/iotcon/iotcon_extension.cc | 16 +- src/iotcon/iotcon_extension.h | 1 - src/iotcon/iotcon_instance.cc | 269 +- src/iotcon/iotcon_instance.h | 8 +- src/iotcon/iotcon_manager.cc | 32 +- src/iotcon/iotcon_manager.h | 13 +- src/iotcon/iotcon_server_manager.cc | 45 +- src/iotcon/iotcon_server_manager.h | 19 +- src/iotcon/iotcon_utils.cc | 937 +++---- src/iotcon/iotcon_utils.h | 103 +- src/keymanager/keymanager_extension.cc | 10 +- src/keymanager/keymanager_extension.h | 2 +- src/keymanager/keymanager_instance.cc | 88 +- src/keymanager/keymanager_instance.h | 9 +- src/mediacontroller/mediacontroller_client.cc | 282 +- src/mediacontroller/mediacontroller_client.h | 49 +- src/mediacontroller/mediacontroller_extension.cc | 5 +- src/mediacontroller/mediacontroller_extension.h | 2 +- src/mediacontroller/mediacontroller_instance.cc | 340 +-- src/mediacontroller/mediacontroller_instance.h | 36 +- src/mediacontroller/mediacontroller_server.cc | 213 +- src/mediacontroller/mediacontroller_server.h | 29 +- src/mediacontroller/mediacontroller_types.cc | 126 +- src/mediacontroller/mediacontroller_types.h | 24 +- src/mediakey/mediakey_extension.cc | 1 - src/mediakey/mediakey_extension.h | 2 +- src/mediakey/mediakey_instance.cc | 39 +- src/mediakey/mediakey_instance.h | 6 +- src/mediakey/mediakey_manager.cc | 17 +- src/mediakey/mediakey_manager.h | 14 +- src/messageport/messageport_extension.cc | 5 +- src/messageport/messageport_instance.cc | 274 +- src/messageport/messageport_instance.h | 19 +- src/messaging/DBus/DBusTypes.cpp | 6 +- src/messaging/DBus/DBusTypes.h | 6 +- src/messaging/DBus/EmailSignalProxy.cpp | 61 +- src/messaging/DBus/EmailSignalProxy.h | 41 +- src/messaging/DBus/LoadAttachmentProxy.cpp | 309 ++- src/messaging/DBus/LoadAttachmentProxy.h | 50 +- src/messaging/DBus/LoadBodyProxy.cpp | 232 +- src/messaging/DBus/LoadBodyProxy.h | 68 +- src/messaging/DBus/MessageProxy.cpp | 474 ++-- src/messaging/DBus/MessageProxy.h | 59 +- src/messaging/DBus/SendProxy.cpp | 67 +- src/messaging/DBus/SendProxy.h | 29 +- src/messaging/DBus/SyncProxy.cpp | 170 +- src/messaging/DBus/SyncProxy.h | 59 +- src/messaging/MsgCommon/AbstractFilter.cpp | 250 +- src/messaging/MsgCommon/AbstractFilter.h | 113 +- src/messaging/MsgCommon/Any.cpp | 219 +- src/messaging/MsgCommon/Any.h | 70 +- src/messaging/MsgCommon/AttributeFilter.cpp | 60 +- src/messaging/MsgCommon/AttributeFilter.h | 43 +- src/messaging/MsgCommon/AttributeRangeFilter.cpp | 64 +- src/messaging/MsgCommon/AttributeRangeFilter.h | 39 +- src/messaging/MsgCommon/CompositeFilter.cpp | 91 +- src/messaging/MsgCommon/CompositeFilter.h | 36 +- src/messaging/MsgCommon/FilterIterator.cpp | 220 +- src/messaging/MsgCommon/FilterIterator.h | 121 +- src/messaging/MsgCommon/SortMode.cpp | 38 +- src/messaging/MsgCommon/SortMode.h | 37 +- src/messaging/change_listener_container.cc | 10 +- src/messaging/change_listener_container.h | 6 +- src/messaging/conversation_callback_data.cc | 92 +- src/messaging/conversation_callback_data.h | 58 +- src/messaging/conversations_change_callback.cc | 244 +- src/messaging/conversations_change_callback.h | 73 +- src/messaging/email_manager.cc | 1224 +++++---- src/messaging/email_manager.h | 189 +- src/messaging/find_msg_callback_user_data.cc | 90 +- src/messaging/find_msg_callback_user_data.h | 58 +- src/messaging/folders_callback_data.cc | 28 +- src/messaging/folders_callback_data.h | 28 +- src/messaging/folders_change_callback.cc | 235 +- src/messaging/folders_change_callback.h | 79 +- src/messaging/message.cc | 2710 ++++++++++---------- src/messaging/message.h | 387 ++- src/messaging/message_attachment.cc | 1012 ++++---- src/messaging/message_attachment.h | 109 +- src/messaging/message_body.cc | 134 +- src/messaging/message_body.h | 68 +- src/messaging/message_callback_user_data.cc | 26 +- src/messaging/message_callback_user_data.h | 27 +- src/messaging/message_conversation.cc | 736 +++--- src/messaging/message_conversation.h | 158 +- src/messaging/message_email.cc | 235 +- src/messaging/message_email.h | 50 +- src/messaging/message_folder.cc | 206 +- src/messaging/message_folder.h | 108 +- src/messaging/message_mms.cc | 84 +- src/messaging/message_mms.h | 32 +- src/messaging/message_service.cc | 408 ++- src/messaging/message_service.h | 270 +- src/messaging/message_service_email.cc | 128 +- src/messaging/message_service_email.h | 34 +- src/messaging/message_service_short_msg.cc | 197 +- src/messaging/message_service_short_msg.h | 22 +- src/messaging/message_sms.cc | 19 +- src/messaging/message_sms.h | 19 +- src/messaging/message_storage.cc | 72 +- src/messaging/message_storage.h | 61 +- src/messaging/message_storage_email.cc | 282 +- src/messaging/message_storage_email.h | 29 +- src/messaging/message_storage_short_msg.cc | 332 ++- src/messaging/message_storage_short_msg.h | 32 +- src/messaging/messages_callback_user_data.cc | 36 +- src/messaging/messages_callback_user_data.h | 26 +- src/messaging/messages_change_callback.cc | 309 ++- src/messaging/messages_change_callback.h | 79 +- src/messaging/messaging_database_manager.cc | 1709 ++++++------ src/messaging/messaging_database_manager.h | 145 +- src/messaging/messaging_extension.cc | 22 +- src/messaging/messaging_extension.h | 3 +- src/messaging/messaging_instance.cc | 1022 ++++---- src/messaging/messaging_instance.h | 75 +- src/messaging/messaging_manager.cc | 171 +- src/messaging/messaging_manager.h | 45 +- src/messaging/messaging_util.cc | 1556 ++++++----- src/messaging/messaging_util.h | 262 +- src/messaging/short_message_manager.cc | 1698 ++++++------ src/messaging/short_message_manager.h | 191 +- .../networkbearerselection_extension.cc | 3 +- .../networkbearerselection_instance.cc | 25 +- .../networkbearerselection_instance.h | 3 +- .../networkbearerselection_manager.cc | 72 +- .../networkbearerselection_manager.h | 10 +- src/nfc/aid_data.cc | 5 +- src/nfc/defs.h | 26 +- src/nfc/nfc_adapter.cc | 524 ++-- src/nfc/nfc_adapter.h | 47 +- src/nfc/nfc_extension.cc | 16 +- src/nfc/nfc_extension.h | 1 + src/nfc/nfc_instance.cc | 341 +-- src/nfc/nfc_instance.h | 9 +- src/nfc/nfc_message_utils.cc | 263 +- src/nfc/nfc_message_utils.h | 42 +- src/nfc/nfc_util.cc | 118 +- src/nfc/nfc_util.h | 33 +- src/notification/common_notification.cc | 429 ++-- src/notification/common_notification.h | 121 +- src/notification/notification_extension.cc | 7 +- src/notification/notification_instance.cc | 59 +- src/notification/notification_instance.h | 32 +- src/notification/notification_manager.cc | 98 +- src/notification/notification_manager.h | 13 +- src/notification/status_notification.cc | 28 +- src/notification/status_notification.h | 11 +- src/notification/user_notification.cc | 88 +- src/notification/user_notification.h | 12 +- src/package/package_extension.cc | 2 +- src/package/package_info_provider.cc | 111 +- src/package/package_info_provider.h | 6 +- src/package/package_instance.cc | 337 ++- src/package/package_instance.h | 31 +- src/playerutil/playerutil_extension.cc | 4 +- src/playerutil/playerutil_extension.h | 1 - src/playerutil/playerutil_instance.cc | 13 +- src/playerutil/playerutil_instance.h | 2 +- src/playerutil/playerutil_utils.cc | 27 +- src/playerutil/playerutil_utils.h | 10 +- src/power/power_extension.cc | 3 +- src/power/power_extension.h | 3 +- src/power/power_instance.cc | 62 +- src/power/power_instance.h | 10 +- src/power/power_manager.cc | 188 +- src/power/power_manager.h | 14 +- src/power/power_platform_proxy.cc | 25 +- src/preference/preference_extension.cc | 3 +- src/preference/preference_extension.h | 3 +- src/preference/preference_instance.cc | 28 +- src/preference/preference_instance.h | 10 +- src/preference/preference_manager.cc | 17 +- src/preference/preference_manager.h | 13 +- src/push/push_extension.cc | 11 +- src/push/push_extension.h | 7 +- src/push/push_instance.cc | 349 ++- src/push/push_instance.h | 42 +- src/push/push_manager.cc | 285 +- src/push/push_manager.h | 27 +- src/push/push_manager_common.cc | 17 +- src/push/push_manager_common.h | 31 +- src/radio/radio_extension.h | 3 +- src/radio/radio_instance.cc | 50 +- src/radio/radio_instance.h | 4 +- src/radio/radio_manager.cc | 96 +- src/radio/radio_manager.h | 18 +- src/secureelement/secureelement_extension.cc | 3 +- src/secureelement/secureelement_extension.h | 13 +- src/secureelement/secureelement_instance.cc | 43 +- src/secureelement/secureelement_instance.h | 70 +- src/sensor/sensor_extension.cc | 3 +- src/sensor/sensor_extension.h | 2 +- src/sensor/sensor_instance.cc | 15 +- src/sensor/sensor_instance.h | 6 +- src/sensor/sensor_service.cc | 180 +- src/sensor/sensor_service.h | 6 +- src/sound/sound_extension.cc | 3 +- src/sound/sound_extension.h | 2 +- src/sound/sound_instance.cc | 81 +- src/sound/sound_instance.h | 10 +- src/sound/sound_manager.cc | 236 +- src/sound/sound_manager.h | 21 +- src/systeminfo/systeminfo-utils.cpp | 83 +- src/systeminfo/systeminfo-utils.h | 22 +- src/systeminfo/systeminfo_device_capability.cc | 134 +- src/systeminfo/systeminfo_device_capability.h | 12 +- src/systeminfo/systeminfo_extension.cc | 3 +- src/systeminfo/systeminfo_extension.h | 3 +- src/systeminfo/systeminfo_instance.cc | 34 +- src/systeminfo/systeminfo_instance.h | 11 +- src/systeminfo/systeminfo_manager.cc | 547 ++-- src/systeminfo/systeminfo_manager.h | 27 +- src/systeminfo/systeminfo_properties_manager.cc | 585 ++--- src/systeminfo/systeminfo_properties_manager.h | 12 +- src/systeminfo/systeminfo_sim_details_manager.cc | 89 +- src/systeminfo/systeminfo_sim_details_manager.h | 24 +- src/systemsetting/systemsetting_extension.cc | 3 +- src/systemsetting/systemsetting_extension.h | 3 +- src/systemsetting/systemsetting_instance.cc | 116 +- src/systemsetting/systemsetting_instance.h | 19 +- src/time/time_extension.cc | 8 +- src/time/time_instance.cc | 90 +- src/time/time_instance.h | 2 +- src/time/time_manager.cc | 66 +- src/time/time_manager.h | 17 +- src/time/time_utils.cc | 89 +- src/time/time_utils.h | 37 +- src/tizen/tizen.h | 20 +- src/tizen/tizen_extension.cc | 3 +- src/tool/desc_gentool.cc | 108 +- src/tvinputdevice/tvinputdevice_extension.cc | 11 +- src/tvinputdevice/tvinputdevice_extension.h | 7 +- src/tvinputdevice/tvinputdevice_instance.cc | 6 +- src/tvinputdevice/tvinputdevice_instance.h | 7 +- src/utils/utils_extension.cc | 2 +- src/utils/utils_instance.cc | 22 +- src/utils/utils_instance.h | 3 +- src/websetting/websetting_extension.cc | 2 +- src/widgetservice/widgetservice_extension.cc | 3 +- src/widgetservice/widgetservice_instance.cc | 102 +- src/widgetservice/widgetservice_instance.h | 15 +- src/widgetservice/widgetservice_utils.cc | 113 +- src/widgetservice/widgetservice_utils.h | 17 +- 502 files changed, 28141 insertions(+), 32708 deletions(-) mode change 100755 => 100644 src/account/account_extension.cc mode change 100755 => 100644 src/account/account_extension.h mode change 100755 => 100644 src/account/account_instance.h mode change 100755 => 100644 src/account/account_manager.h mode change 100755 => 100644 src/alarm/alarm_extension.cc mode change 100755 => 100644 src/alarm/alarm_extension.h mode change 100755 => 100644 src/alarm/alarm_instance.cc mode change 100755 => 100644 src/alarm/alarm_instance.h mode change 100755 => 100644 src/alarm/alarm_manager.cc mode change 100755 => 100644 src/alarm/alarm_manager.h mode change 100755 => 100644 src/alarm/alarm_utils.cc mode change 100755 => 100644 src/alarm/alarm_utils.h mode change 100755 => 100644 src/application/application.cc mode change 100755 => 100644 src/application/application.h mode change 100755 => 100644 src/application/application_extension.cc mode change 100755 => 100644 src/application/application_extension.h mode change 100755 => 100644 src/application/application_instance.cc mode change 100755 => 100644 src/application/application_instance.h mode change 100755 => 100644 src/application/application_manager.cc mode change 100755 => 100644 src/application/application_manager.h mode change 100755 => 100644 src/application/application_utils.h mode change 100755 => 100644 src/application/requested_application_control.cc mode change 100755 => 100644 src/application/requested_application_control.h mode change 100755 => 100644 src/archive/archive_callback_data.cc mode change 100755 => 100644 src/archive/archive_extension.cc mode change 100755 => 100644 src/archive/archive_extension.h mode change 100755 => 100644 src/archive/archive_file.cc mode change 100755 => 100644 src/archive/archive_file_entry.cc mode change 100755 => 100644 src/archive/archive_instance.cc mode change 100755 => 100644 src/archive/archive_instance.h mode change 100755 => 100644 src/archive/archive_manager.cc mode change 100755 => 100644 src/archive/archive_utils.cc mode change 100755 => 100644 src/archive/archive_utils.h mode change 100755 => 100644 src/archive/defs.h mode change 100755 => 100644 src/archive/filesystem_path.cc mode change 100755 => 100644 src/archive/un_zip_extract_request.h mode change 100755 => 100644 src/archive/zip.cc mode change 100755 => 100644 src/archive/zip.h mode change 100755 => 100644 src/archive/zip_add_request.cc mode change 100755 => 100644 src/archive/zip_add_request.h mode change 100755 => 100644 src/badge/badge_extension.cc mode change 100755 => 100644 src/badge/badge_instance.cc mode change 100755 => 100644 src/badge/badge_instance.h mode change 100755 => 100644 src/badge/badge_manager.cc mode change 100755 => 100644 src/badge/badge_manager.h mode change 100755 => 100644 src/bluetooth/bluetooth_adapter.cc mode change 100755 => 100644 src/bluetooth/bluetooth_adapter.h mode change 100755 => 100644 src/bluetooth/bluetooth_class.cc mode change 100755 => 100644 src/bluetooth/bluetooth_class.h mode change 100755 => 100644 src/bluetooth/bluetooth_device.cc mode change 100755 => 100644 src/bluetooth/bluetooth_device.h mode change 100755 => 100644 src/bluetooth/bluetooth_extension.cc mode change 100755 => 100644 src/bluetooth/bluetooth_extension.h mode change 100755 => 100644 src/bluetooth/bluetooth_gatt_service.cc mode change 100755 => 100644 src/bluetooth/bluetooth_gatt_service.h mode change 100755 => 100644 src/bluetooth/bluetooth_health_application.cc mode change 100755 => 100644 src/bluetooth/bluetooth_health_application.h mode change 100755 => 100644 src/bluetooth/bluetooth_health_channel.cc mode change 100755 => 100644 src/bluetooth/bluetooth_health_channel.h mode change 100755 => 100644 src/bluetooth/bluetooth_health_profile_handler.cc mode change 100755 => 100644 src/bluetooth/bluetooth_health_profile_handler.h mode change 100755 => 100644 src/bluetooth/bluetooth_instance.cc mode change 100755 => 100644 src/bluetooth/bluetooth_instance.h mode change 100755 => 100644 src/bluetooth/bluetooth_le_adapter.cc mode change 100755 => 100644 src/bluetooth/bluetooth_le_adapter.h mode change 100755 => 100644 src/bluetooth/bluetooth_le_device.cc mode change 100755 => 100644 src/bluetooth/bluetooth_le_device.h mode change 100755 => 100644 src/bluetooth/bluetooth_service_handler.cc mode change 100755 => 100644 src/bluetooth/bluetooth_service_handler.h mode change 100755 => 100644 src/bluetooth/bluetooth_socket.cc mode change 100755 => 100644 src/bluetooth/bluetooth_socket.h mode change 100755 => 100644 src/bluetooth/bluetooth_util.cc mode change 100755 => 100644 src/bookmark/bookmark_extension.cc mode change 100755 => 100644 src/bookmark/bookmark_instance.cc mode change 100755 => 100644 src/bookmark/bookmark_instance.h mode change 100755 => 100644 src/calendar/calendar.cc mode change 100755 => 100644 src/calendar/calendar_extension.cc mode change 100755 => 100644 src/calendar/calendar_extension.h mode change 100755 => 100644 src/calendar/calendar_instance.cc mode change 100755 => 100644 src/calendar/calendar_instance.h mode change 100755 => 100644 src/calendar/calendar_item.cc mode change 100755 => 100644 src/calendar/calendar_manager.cc mode change 100755 => 100644 src/calendar/calendar_plugin.cc mode change 100755 => 100644 src/calendar/calendar_record.cc mode change 100755 => 100644 src/callhistory/callhistory.cc mode change 100755 => 100644 src/callhistory/callhistory.h mode change 100755 => 100644 src/callhistory/callhistory_extension.cc mode change 100755 => 100644 src/callhistory/callhistory_extension.h mode change 100755 => 100644 src/callhistory/callhistory_instance.cc mode change 100755 => 100644 src/callhistory/callhistory_types.h mode change 100755 => 100644 src/callhistory/callhistory_utils.cc mode change 100755 => 100644 src/callhistory/callhistory_utils.h mode change 100755 => 100644 src/common/XW_Extension.cc mode change 100755 => 100644 src/common/XW_Extension.h mode change 100755 => 100644 src/common/XW_Extension_EntryPoints.h mode change 100755 => 100644 src/common/XW_Extension_Permissions.h mode change 100755 => 100644 src/common/XW_Extension_Runtime.h mode change 100755 => 100644 src/common/XW_Extension_SyncMessage.h mode change 100755 => 100644 src/common/assert.h mode change 100755 => 100644 src/common/converter.cc mode change 100755 => 100644 src/common/current_application.cc mode change 100755 => 100644 src/common/current_application.h mode change 100755 => 100644 src/common/deleter.h mode change 100755 => 100644 src/common/filter-utils.cc mode change 100755 => 100644 src/common/filter-utils.h mode change 100755 => 100644 src/common/optional.h mode change 100755 => 100644 src/common/platform_exception.cc mode change 100755 => 100644 src/common/platform_exception.h mode change 100755 => 100644 src/common/platform_result.cc mode change 100755 => 100644 src/common/platform_result.h mode change 100755 => 100644 src/common/task-queue.cpp mode change 100755 => 100644 src/common/task-queue.h mode change 100755 => 100644 src/common/typeutil.h mode change 100755 => 100644 src/common/utils.h mode change 100755 => 100644 src/contact/addressbook.cc mode change 100755 => 100644 src/contact/contact_extension.cc mode change 100755 => 100644 src/contact/contact_instance.cc mode change 100755 => 100644 src/contact/contact_instance.h mode change 100755 => 100644 src/contact/contact_manager.cc mode change 100755 => 100644 src/contact/contact_manager.h mode change 100755 => 100644 src/contact/contact_util.cc mode change 100755 => 100644 src/contact/person.cc mode change 100755 => 100644 src/content/content_extension.cc mode change 100755 => 100644 src/content/content_extension.h mode change 100755 => 100644 src/content/content_filter.cc mode change 100755 => 100644 src/content/content_instance.cc mode change 100755 => 100644 src/content/content_instance.h mode change 100755 => 100644 src/datacontrol/datacontrol_extension.cc mode change 100755 => 100644 src/datacontrol/datacontrol_instance.cc mode change 100755 => 100644 src/datacontrol/datacontrol_instance.h mode change 100755 => 100644 src/download/download_extension.cc mode change 100755 => 100644 src/download/download_instance.cc mode change 100755 => 100644 src/download/download_instance.h mode change 100755 => 100644 src/exif/exif_extension.cc mode change 100755 => 100644 src/exif/exif_gps_location.cc mode change 100755 => 100644 src/exif/exif_gps_location.h mode change 100755 => 100644 src/exif/exif_information.cc mode change 100755 => 100644 src/exif/exif_information.h mode change 100755 => 100644 src/exif/exif_instance.cc mode change 100755 => 100644 src/exif/exif_tag_saver.cc mode change 100755 => 100644 src/exif/exif_tag_saver.h mode change 100755 => 100644 src/exif/exif_util.cc mode change 100755 => 100644 src/exif/exif_util.h mode change 100755 => 100644 src/exif/get_exif_info.cc mode change 100755 => 100644 src/exif/get_exif_info.h mode change 100755 => 100644 src/exif/jpeg_file.cc mode change 100755 => 100644 src/exif/jpeg_file.h mode change 100755 => 100644 src/exif/rational.cc mode change 100755 => 100644 src/exif/rational.h mode change 100755 => 100644 src/feedback/feedback_extension.cc mode change 100755 => 100644 src/feedback/feedback_instance.cc mode change 100755 => 100644 src/feedback/feedback_instance.h mode change 100755 => 100644 src/filesystem/filesystem_extension.cc mode change 100755 => 100644 src/filesystem/filesystem_extension.h mode change 100755 => 100644 src/filesystem/filesystem_stat.cc mode change 100755 => 100644 src/humanactivitymonitor/humanactivitymonitor_extension.cc mode change 100755 => 100644 src/humanactivitymonitor/humanactivitymonitor_instance.cc mode change 100755 => 100644 src/humanactivitymonitor/humanactivitymonitor_instance.h mode change 100755 => 100644 src/humanactivitymonitor/humanactivitymonitor_manager.cc mode change 100755 => 100644 src/humanactivitymonitor/humanactivitymonitor_manager.h mode change 100755 => 100644 src/keymanager/keymanager_extension.cc mode change 100755 => 100644 src/keymanager/keymanager_extension.h mode change 100755 => 100644 src/keymanager/keymanager_instance.h mode change 100755 => 100644 src/mediacontroller/mediacontroller_client.h mode change 100755 => 100644 src/mediacontroller/mediacontroller_extension.cc mode change 100755 => 100644 src/mediacontroller/mediacontroller_extension.h mode change 100755 => 100644 src/mediacontroller/mediacontroller_instance.cc mode change 100755 => 100644 src/mediacontroller/mediacontroller_instance.h mode change 100755 => 100644 src/mediacontroller/mediacontroller_server.h mode change 100755 => 100644 src/mediacontroller/mediacontroller_types.h mode change 100755 => 100644 src/mediakey/mediakey_extension.cc mode change 100755 => 100644 src/mediakey/mediakey_extension.h mode change 100755 => 100644 src/mediakey/mediakey_instance.cc mode change 100755 => 100644 src/mediakey/mediakey_instance.h mode change 100755 => 100644 src/mediakey/mediakey_manager.cc mode change 100755 => 100644 src/mediakey/mediakey_manager.h mode change 100755 => 100644 src/messageport/messageport_extension.cc mode change 100755 => 100644 src/messageport/messageport_instance.cc mode change 100755 => 100644 src/messageport/messageport_instance.h mode change 100755 => 100644 src/messaging/MsgCommon/AbstractFilter.cpp mode change 100755 => 100644 src/messaging/MsgCommon/Any.cpp mode change 100755 => 100644 src/messaging/MsgCommon/AttributeFilter.cpp mode change 100755 => 100644 src/messaging/MsgCommon/AttributeRangeFilter.cpp mode change 100755 => 100644 src/messaging/MsgCommon/CompositeFilter.cpp mode change 100755 => 100644 src/messaging/MsgCommon/FilterIterator.cpp mode change 100755 => 100644 src/messaging/MsgCommon/SortMode.cpp mode change 100755 => 100644 src/messaging/change_listener_container.cc mode change 100755 => 100644 src/messaging/change_listener_container.h mode change 100755 => 100644 src/messaging/conversation_callback_data.cc mode change 100755 => 100644 src/messaging/conversations_change_callback.cc mode change 100755 => 100644 src/messaging/email_manager.cc mode change 100755 => 100644 src/messaging/find_msg_callback_user_data.cc mode change 100755 => 100644 src/messaging/folders_callback_data.cc mode change 100755 => 100644 src/messaging/folders_change_callback.cc mode change 100755 => 100644 src/messaging/message.cc mode change 100755 => 100644 src/messaging/message_attachment.cc mode change 100755 => 100644 src/messaging/message_body.cc mode change 100755 => 100644 src/messaging/message_callback_user_data.cc mode change 100755 => 100644 src/messaging/message_conversation.cc mode change 100755 => 100644 src/messaging/message_email.cc mode change 100755 => 100644 src/messaging/message_folder.cc mode change 100755 => 100644 src/messaging/message_folder.h mode change 100755 => 100644 src/messaging/message_mms.cc mode change 100755 => 100644 src/messaging/message_service.cc mode change 100755 => 100644 src/messaging/message_service_email.cc mode change 100755 => 100644 src/messaging/message_service_email.h mode change 100755 => 100644 src/messaging/message_service_short_msg.cc mode change 100755 => 100644 src/messaging/message_service_short_msg.h mode change 100755 => 100644 src/messaging/message_sms.cc mode change 100755 => 100644 src/messaging/message_storage.cc mode change 100755 => 100644 src/messaging/message_storage_email.cc mode change 100755 => 100644 src/messaging/message_storage_short_msg.cc mode change 100755 => 100644 src/messaging/message_storage_short_msg.h mode change 100755 => 100644 src/messaging/messages_callback_user_data.cc mode change 100755 => 100644 src/messaging/messages_callback_user_data.h mode change 100755 => 100644 src/messaging/messages_change_callback.cc mode change 100755 => 100644 src/messaging/messages_change_callback.h mode change 100755 => 100644 src/messaging/messaging_database_manager.cc mode change 100755 => 100644 src/messaging/messaging_database_manager.h mode change 100755 => 100644 src/messaging/messaging_extension.cc mode change 100755 => 100644 src/messaging/messaging_extension.h mode change 100755 => 100644 src/messaging/messaging_instance.cc mode change 100755 => 100644 src/messaging/messaging_instance.h mode change 100755 => 100644 src/messaging/messaging_manager.cc mode change 100755 => 100644 src/messaging/messaging_manager.h mode change 100755 => 100644 src/messaging/messaging_util.cc mode change 100755 => 100644 src/messaging/short_message_manager.cc mode change 100755 => 100644 src/messaging/short_message_manager.h mode change 100755 => 100644 src/power/power_extension.cc mode change 100755 => 100644 src/power/power_extension.h mode change 100755 => 100644 src/power/power_instance.cc mode change 100755 => 100644 src/power/power_instance.h mode change 100755 => 100644 src/power/power_manager.h mode change 100755 => 100644 src/radio/radio_manager.cc mode change 100755 => 100644 src/radio/radio_manager.h mode change 100755 => 100644 src/sensor/sensor_service.cc mode change 100755 => 100644 src/widgetservice/widgetservice_extension.cc mode change 100755 => 100644 src/widgetservice/widgetservice_instance.h diff --git a/src/account/account_extension.cc b/src/account/account_extension.cc old mode 100755 new mode 100644 index 358032c..d743aee --- a/src/account/account_extension.cc +++ b/src/account/account_extension.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "account/account_extension.h" #include "account/account_instance.h" @@ -29,14 +29,12 @@ AccountExtension::AccountExtension() { SetExtensionName("tizen.account"); SetJavaScriptAPI(kSource_account_api); - const char* entry_points[] = { - "tizen.Account", - NULL - }; + const char* entry_points[] = {"tizen.Account", NULL}; SetExtraJSEntryPoints(entry_points); } -AccountExtension::~AccountExtension() {} +AccountExtension::~AccountExtension() { +} common::Instance* AccountExtension::CreateInstance() { return new extension::account::AccountInstance; diff --git a/src/account/account_extension.h b/src/account/account_extension.h old mode 100755 new mode 100644 index eb87c0b..17c2e6e --- a/src/account/account_extension.h +++ b/src/account/account_extension.h @@ -28,4 +28,4 @@ class AccountExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // ACCOUNT_ACCOUNT_EXTENSION_H_ +#endif // ACCOUNT_ACCOUNT_EXTENSION_H_ diff --git a/src/account/account_instance.cc b/src/account/account_instance.cc index a16d846..903b262 100644 --- a/src/account/account_instance.cc +++ b/src/account/account_instance.cc @@ -20,10 +20,10 @@ #include -#include "common/picojson.h" #include "common/logger.h" -#include "common/task-queue.h" +#include "common/picojson.h" #include "common/platform_exception.h" +#include "common/task-queue.h" #include "common/tools.h" namespace extension { @@ -36,17 +36,15 @@ using common::SecurityException; namespace { // The privileges that required in Account API -const std::string kPrivilegeAccountRead = - "http://tizen.org/privilege/account.read"; -const std::string kPrivilegeAccountWrite = - "http://tizen.org/privilege/account.write"; -} // namespace - -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +const std::string kPrivilegeAccountRead = "http://tizen.org/privilege/account.read"; +const std::string kPrivilegeAccountWrite = "http://tizen.org/privilege/account.write"; +} // namespace + +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } AccountInstance::AccountInstance() { LoggerD("Enter"); @@ -57,14 +55,12 @@ AccountInstance::AccountInstance() { using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&AccountInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&AccountInstance::x, this, _1, _2)); REGISTER_ASYNC("AccountManager_getAccounts", AccountManagerGetAccounts); REGISTER_ASYNC("AccountManager_getProviders", AccountManagerGetProviders); REGISTER_ASYNC("Account_getExtendedData", AccountGetExtendedData); - #undef REGISTER_ASYNC - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&AccountInstance::x, this, _1, _2)); +#undef REGISTER_ASYNC +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&AccountInstance::x, this, _1, _2)); REGISTER_SYNC("AccountManager_removeAccountListener", AccountManagerRemoveAccountListener); REGISTER_SYNC("AccountManager_update", AccountManagerUpdate); REGISTER_SYNC("AccountManager_remove", AccountManagerRemove); @@ -74,7 +70,7 @@ AccountInstance::AccountInstance() { REGISTER_SYNC("AccountManager_add", AccountManagerAdd); REGISTER_SYNC("Account_setExtendedData", AccountSetExtendedData); REGISTER_SYNC("Account_getExtendedDataSync", AccountGetExtendedDataSync); - #undef REGISTER_SYNC +#undef REGISTER_SYNC } AccountInstance::~AccountInstance() { @@ -90,8 +86,7 @@ AccountManager* AccountInstance::GetAccountManager() { return manager_; } -void AccountInstance::AccountSetExtendedData(const picojson::value& args, - picojson::object& out) { +void AccountInstance::AccountSetExtendedData(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); @@ -107,8 +102,7 @@ void AccountInstance::AccountSetExtendedData(const picojson::value& args, this->manager_->SetExtendedData(account_id, key, value, out); } -void AccountInstance::AccountGetExtendedData(const picojson::value& args, - picojson::object& out) { +void AccountInstance::AccountGetExtendedData(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -123,17 +117,17 @@ void AccountInstance::AccountGetExtendedData(const picojson::value& args, this->manager_->GetExtendedData(account_id, result->get()); }; - auto get_extended_data_result = [this, callback_id](const std::shared_ptr& result) { - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + auto get_extended_data_result = [this, + callback_id](const std::shared_ptr& result) { + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); }; auto data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - get_extended_data, - get_extended_data_result, - data); + TaskQueue::GetInstance().Queue(get_extended_data, get_extended_data_result, + data); ReportSuccess(out); } @@ -159,22 +153,19 @@ void AccountInstance::AccountManagerAdd(const picojson::value& args, picojson::o manager_->AddAccount(args, out); } -void AccountInstance::AccountManagerRemove(const picojson::value& args, - picojson::object& out) { +void AccountInstance::AccountManagerRemove(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); manager_->RemoveAccount(args, out); } -void AccountInstance::AccountManagerUpdate(const picojson::value& args, - picojson::object& out) { +void AccountInstance::AccountManagerUpdate(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); manager_->UpdateAccount(args, out); } -void AccountInstance::AccountManagerGetAccount(const picojson::value& args, - picojson::object& out) { +void AccountInstance::AccountManagerGetAccount(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -195,7 +186,8 @@ void AccountInstance::AccountManagerGetAccounts(const picojson::value& args, CHECK_EXIST(args, "callbackId", out) int callback_id = static_cast(args.get("callbackId").get()); - const std::string application_id = args.contains("applicationId") ? args.get("applicationId").get() : ""; + const std::string application_id = + args.contains("applicationId") ? args.get("applicationId").get() : ""; LoggerD("application ID: [%s]", application_id.c_str()); auto get_accounts = [this, application_id](const std::shared_ptr& result) { @@ -203,16 +195,14 @@ void AccountInstance::AccountManagerGetAccounts(const picojson::value& args, }; auto get_accounts_result = [this, callback_id](const std::shared_ptr& result) { - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); }; auto data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - get_accounts, - get_accounts_result, - data); + TaskQueue::GetInstance().Queue(get_accounts, get_accounts_result, data); ReportSuccess(out); } @@ -248,16 +238,14 @@ void AccountInstance::AccountManagerGetProviders(const picojson::value& args, }; auto get_providers_result = [this, callback_id](const std::shared_ptr& result) { - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); }; auto data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - get_providers, - get_providers_result, - data); + TaskQueue::GetInstance().Queue(get_providers, get_providers_result, data); ReportSuccess(out); } @@ -268,8 +256,7 @@ void AccountInstance::InvokeListener(picojson::object& param) { Instance::PostMessage(this, result.serialize().c_str()); } -static bool AccountEventCb(const char *event_type, int account_id, - void *user_data) { +static bool AccountEventCb(const char* event_type, int account_id, void* user_data) { LoggerD("Enter"); AccountInstance* instance = static_cast(user_data); @@ -304,8 +291,8 @@ static bool AccountEventCb(const char *event_type, int account_id, return true; } -void AccountInstance::AccountManagerAddAccountListener( - const picojson::value& args, picojson::object& out) { +void AccountInstance::AccountManagerAddAccountListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -332,8 +319,8 @@ void AccountInstance::AccountManagerAddAccountListener( ReportSuccess(out); } -void AccountInstance::AccountManagerRemoveAccountListener( - const picojson::value& args, picojson::object& out) { +void AccountInstance::AccountManagerRemoveAccountListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -353,5 +340,5 @@ void AccountInstance::AccountManagerRemoveAccountListener( #undef CHECK_EXIST -} // namespace account -} // namespace extension +} // namespace account +} // namespace extension diff --git a/src/account/account_instance.h b/src/account/account_instance.h old mode 100755 new mode 100644 index 9651cfb..31fe2d0 --- a/src/account/account_instance.h +++ b/src/account/account_instance.h @@ -42,35 +42,22 @@ class AccountInstance : public common::ParsedInstance { AccountManager* manager_; account_subscribe_h subscribe_; - void AccountManagerRemoveAccountListener( - const picojson::value& args, picojson::object& out); - void AccountManagerUpdate( - const picojson::value& args, picojson::object& out); - void AccountManagerRemove( - const picojson::value& args, picojson::object& out); - void AccountConstructor( - const picojson::value& args, picojson::object& out); - void AccountManagerGetAccount( - const picojson::value& args, picojson::object& out); - void AccountManagerGetProvider( - const picojson::value& args, picojson::object& out); - void AccountSetExtendedData( - const picojson::value& args, picojson::object& out); - void AccountManagerAddAccountListener( - const picojson::value& args, picojson::object& out); - void AccountManagerAdd( - const picojson::value& args, picojson::object& out); - void AccountManagerGetAccounts( - const picojson::value& args, picojson::object& out); - void AccountGetExtendedData( - const picojson::value& args, picojson::object& out); - void AccountGetExtendedDataSync( - const picojson::value& args, picojson::object& out); - void AccountManagerGetProviders( - const picojson::value& args, picojson::object& out); + void AccountManagerRemoveAccountListener(const picojson::value& args, picojson::object& out); + void AccountManagerUpdate(const picojson::value& args, picojson::object& out); + void AccountManagerRemove(const picojson::value& args, picojson::object& out); + void AccountConstructor(const picojson::value& args, picojson::object& out); + void AccountManagerGetAccount(const picojson::value& args, picojson::object& out); + void AccountManagerGetProvider(const picojson::value& args, picojson::object& out); + void AccountSetExtendedData(const picojson::value& args, picojson::object& out); + void AccountManagerAddAccountListener(const picojson::value& args, picojson::object& out); + void AccountManagerAdd(const picojson::value& args, picojson::object& out); + void AccountManagerGetAccounts(const picojson::value& args, picojson::object& out); + void AccountGetExtendedData(const picojson::value& args, picojson::object& out); + void AccountGetExtendedDataSync(const picojson::value& args, picojson::object& out); + void AccountManagerGetProviders(const picojson::value& args, picojson::object& out); }; -} // namespace account -} // namespace extension +} // namespace account +} // namespace extension -#endif // ACCOUNT_ACCOUNT_INSTANCE_H_ +#endif // ACCOUNT_ACCOUNT_INSTANCE_H_ diff --git a/src/account/account_manager.cc b/src/account/account_manager.cc index 153be1b..b409b89 100644 --- a/src/account/account_manager.cc +++ b/src/account/account_manager.cc @@ -31,7 +31,7 @@ using common::NotFoundException; using common::tools::ReportError; namespace { -static bool ProviderCapabilitiesCb(char *app_id, char *key, void *user_data) { +static bool ProviderCapabilitiesCb(char* app_id, char* key, void* user_data) { LoggerD("Enter"); picojson::array* array_data = static_cast(user_data); @@ -44,7 +44,7 @@ static bool ProviderCapabilitiesCb(char *app_id, char *key, void *user_data) { return true; } -static bool AccountProvidersGetCb(account_type_h provider, void *user_data) { +static bool AccountProvidersGetCb(account_type_h provider, void* user_data) { LoggerD("Enter"); picojson::array* array_data = static_cast(user_data); @@ -61,7 +61,7 @@ static bool AccountProvidersGetCb(account_type_h provider, void *user_data) { return true; } -static bool GetAccountsCallback(account_h handle, void *user_data) { +static bool GetAccountsCallback(account_h handle, void* user_data) { LoggerD("Enter"); picojson::array* array_data = static_cast(user_data); @@ -100,7 +100,7 @@ static bool GetCustomAllCallback(char* key, char* value, void* user_data) { return true; }; -} // namespace +} // namespace AccountManager::AccountManager() { LoggerD("Enter"); @@ -151,8 +151,7 @@ std::string AccountManager::GetErrorMsg(int error) { } } -void AccountManager::GetAccountsInfo(const std::string& application_id, - picojson::object& out) { +void AccountManager::GetAccountsInfo(const std::string& application_id, picojson::object& out) { LoggerD("Enter"); picojson::array array_data; @@ -161,8 +160,7 @@ void AccountManager::GetAccountsInfo(const std::string& application_id, if ("" == application_id) { ret = account_foreach_account_from_db(GetAccountsCallback, &array_data); } else { - ret = account_query_account_by_package_name(GetAccountsCallback, - application_id.c_str(), + ret = account_query_account_by_package_name(GetAccountsCallback, application_id.c_str(), &array_data); } @@ -185,8 +183,7 @@ void AccountManager::GetAccountInfo(int account_id, picojson::object& out) { int ret = account_create(&account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account info")); return; } @@ -196,8 +193,7 @@ void AccountManager::GetAccountInfo(int account_id, picojson::object& out) { out["result"] = picojson::value(); return; } else if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get account info")); return; } @@ -214,8 +210,7 @@ void AccountManager::GetAccountInfo(int account_id, picojson::object& out) { return; } -bool AccountManager::GetProviderInfo(const std::string& provider_id, - picojson::object& out) { +bool AccountManager::GetProviderInfo(const std::string& provider_id, picojson::object& out) { LoggerD("Enter"); account_type_h provider = NULL; @@ -225,8 +220,7 @@ bool AccountManager::GetProviderInfo(const std::string& provider_id, int ret = account_type_create(&provider); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create provider info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create provider info")); return false; } @@ -242,8 +236,7 @@ bool AccountManager::GetProviderInfo(const std::string& provider_id, out["result"] = picojson::value(); return true; } else if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get provider info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get provider info")); return false; } @@ -260,8 +253,7 @@ bool AccountManager::GetProviderInfo(const std::string& provider_id, return true; } -bool AccountManager::ConvertAccountToObject(account_h account, - picojson::object& out) { +bool AccountManager::ConvertAccountToObject(account_h account, picojson::object& out) { LoggerD("Enter"); char* provider_id = NULL; @@ -277,16 +269,14 @@ bool AccountManager::ConvertAccountToObject(account_h account, int account_id = -1; int ret = account_get_account_id(account, &account_id); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get account ID")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get account ID")); return false; } out["id"] = picojson::value(static_cast(account_id)); ret = account_get_package_name(account, &provider_id); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get provider name")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get provider name")); return false; } @@ -300,16 +290,14 @@ bool AccountManager::ConvertAccountToObject(account_h account, picojson::object account_init; ret = account_get_icon_path(account, &icon_path); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get icon path")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get icon path")); return false; } account_init["iconUri"] = icon_path ? picojson::value(icon_path) : picojson::value(); ret = account_get_user_name(account, &user_name); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get user name")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get user name")); return false; } account_init["userName"] = user_name ? picojson::value(user_name) : picojson::value(); @@ -318,8 +306,7 @@ bool AccountManager::ConvertAccountToObject(account_h account, return true; } -bool AccountManager::ConvertProviderToObject(account_type_h provider, - picojson::object& out) { +bool AccountManager::ConvertProviderToObject(account_type_h provider, picojson::object& out) { LoggerD("Enter"); char* provider_id = NULL; @@ -331,8 +318,7 @@ bool AccountManager::ConvertProviderToObject(account_type_h provider, int ret = account_type_get_app_id(provider, &provider_id); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get application id")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get application id")); return false; } out["applicationId"] = picojson::value(provider_id); @@ -347,15 +333,13 @@ bool AccountManager::ConvertProviderToObject(account_type_h provider, LoggerD("There is no label"); out["displayName"] = picojson::value(""); } else { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get label")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get label")); return false; } ret = account_type_get_icon_path(provider, &icon_uri); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get icon")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get icon")); return false; } out["iconUri"] = picojson::value(icon_uri); @@ -363,18 +347,15 @@ bool AccountManager::ConvertProviderToObject(account_type_h provider, ret = account_type_get_small_icon_path(provider, &small_icon_uri); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get small icon")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get small icon")); return false; } out["smallIconUri"] = picojson::value(small_icon_uri); free(small_icon_uri); - ret = account_type_get_provider_feature_all(provider, ProviderCapabilitiesCb, - &capabilities); + ret = account_type_get_provider_feature_all(provider, ProviderCapabilitiesCb, &capabilities); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get capabilities")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get capabilities")); return false; } out["capabilities"] = picojson::value(capabilities); @@ -382,30 +363,25 @@ bool AccountManager::ConvertProviderToObject(account_type_h provider, int supported = 0; ret = account_type_get_multiple_account_support(provider, &supported); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get small icon")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get small icon")); return false; } is_multiple_account_supported = (supported != 0); - out["isMultipleAccountSupported"] = picojson::value( - is_multiple_account_supported); + out["isMultipleAccountSupported"] = picojson::value(is_multiple_account_supported); return true; } -void AccountManager::GetProvidersInfo(const std::string& capability, - picojson::object& out) { +void AccountManager::GetProvidersInfo(const std::string& capability, picojson::object& out) { LoggerD("Enter"); picojson::array array_data; int ret = ACCOUNT_ERROR_NONE; if ("" == capability) { - ret = account_type_foreach_account_type_from_db(AccountProvidersGetCb, - &array_data); + ret = account_type_foreach_account_type_from_db(AccountProvidersGetCb, &array_data); } else { - ret = account_type_query_by_provider_feature(AccountProvidersGetCb, - capability.c_str(), + ret = account_type_query_by_provider_feature(AccountProvidersGetCb, capability.c_str(), &array_data); } @@ -418,7 +394,8 @@ void AccountManager::GetProvidersInfo(const std::string& capability, } } -void AccountManager::GetExtendedData(int account_id, const std::string& key, picojson::object& out) { +void AccountManager::GetExtendedData(int account_id, const std::string& key, + picojson::object& out) { LoggerD("Enter"); account_h account = nullptr; @@ -428,15 +405,13 @@ void AccountManager::GetExtendedData(int account_id, const std::string& key, pic int ret = account_create(&account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account info")); return; } ret = account_query_account_by_account_id(account_id, &account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get account info")); return; } @@ -448,8 +423,7 @@ void AccountManager::GetExtendedData(int account_id, const std::string& key, pic out["status"] = picojson::value("success"); out["result"] = picojson::value(); } else { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get custom field")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get custom field")); } } else { out["status"] = picojson::value("success"); @@ -468,30 +442,28 @@ void AccountManager::GetExtendedData(int account_id, picojson::object& out) { int ret = account_create(&account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account info")); return; } ret = account_query_account_by_account_id(account_id, &account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get account info")); return; } picojson::array array_data; ret = account_get_custom_all(account, GetCustomAllCallback, &array_data); if (ACCOUNT_ERROR_NONE != ret) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get custom fields")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get custom fields")); } else { out["status"] = picojson::value("success"); out["result"] = picojson::value(array_data); } } -void AccountManager::SetExtendedData(int account_id, const std::string& key, const std::string& value, picojson::object& out) { +void AccountManager::SetExtendedData(int account_id, const std::string& key, + const std::string& value, picojson::object& out) { LoggerD("Enter"); account_h account = nullptr; @@ -501,22 +473,19 @@ void AccountManager::SetExtendedData(int account_id, const std::string& key, con int ret = account_create(&account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account info") ); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account info")); return; } ret = account_query_account_by_account_id(account_id, &account); if (ret != ACCOUNT_ERROR_NONE) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to get account info")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to get account info")); return; } ret = account_set_custom(account, key.c_str(), value.c_str()); if (ACCOUNT_ERROR_NONE != ret) { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to set custom field")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to set custom field")); return; } @@ -561,8 +530,7 @@ void AccountManager::AddAccount(const picojson::value& data, picojson::object& o out["status"] = picojson::value("success"); out["result"] = picojson::value(static_cast(account_id)); } else { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account")); } } @@ -575,8 +543,7 @@ void AccountManager::RemoveAccount(const picojson::value& data, picojson::object if (!ret || ret == ACCOUNT_ERROR_INVALID_PARAMETER) { out["status"] = picojson::value("success"); } else { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account")); } } @@ -606,11 +573,9 @@ void AccountManager::UpdateAccount(const picojson::value& data, picojson::object if (!ret) { out["status"] = picojson::value("success"); } else { - LogAndReportError(UnknownException(GetErrorMsg(ret)), out, - ("Failed to create account")); + LogAndReportError(UnknownException(GetErrorMsg(ret)), out, ("Failed to create account")); } } - -} // namespace account -} // namespace extension +} // namespace account +} // namespace extension diff --git a/src/account/account_manager.h b/src/account/account_manager.h old mode 100755 new mode 100644 index 0e5d107..007a636 --- a/src/account/account_manager.h +++ b/src/account/account_manager.h @@ -37,22 +37,22 @@ class AccountManager { */ void GetAccountsInfo(const std::string& application_id, picojson::object& out); - /* out["status"] = "success" or "error" - * If status is "success", then the result(picojson::value) will be stored in out["result"]. - * If status is "error", then the error(picojson::value) will be stored in out["error"]. - */ + /* out["status"] = "success" or "error" + * If status is "success", then the result(picojson::value) will be stored in out["result"]. + * If status is "error", then the error(picojson::value) will be stored in out["error"]. + */ void GetAccountInfo(int account_id, picojson::object& out); - /* out["status"] = "success" or "error" - * If status is "success", then the result(picojson::value) will be stored in out["result"]. - * If status is "error", then the error(picojson::value) will be stored in out["error"]. - */ + /* out["status"] = "success" or "error" + * If status is "success", then the result(picojson::value) will be stored in out["result"]. + * If status is "error", then the error(picojson::value) will be stored in out["error"]. + */ void GetProvidersInfo(const std::string& capability, picojson::object& out); - /* out["status"] = "success" or "error" - * If status is "success", then the result(picojson::value) will be stored in out["result"]. - * If status is "error", then the error(picojson::value) will be stored in out["error"]. - */ + /* out["status"] = "success" or "error" + * If status is "success", then the result(picojson::value) will be stored in out["result"]. + * If status is "error", then the error(picojson::value) will be stored in out["error"]. + */ static bool GetProviderInfo(const std::string& provider_id, picojson::object& out); /* out["status"] = "success" or "error" @@ -71,7 +71,8 @@ class AccountManager { * If status is "success", then the result(picojson::value) will be stored in out["result"]. * If status is "error", then the error(picojson::value) will be stored in out["error"]. */ - void SetExtendedData(int account_id, const std::string& key, const std::string& value, picojson::object& out); + void SetExtendedData(int account_id, const std::string& key, const std::string& value, + picojson::object& out); static bool ConvertAccountToObject(account_h account, picojson::object& out); @@ -82,10 +83,10 @@ class AccountManager { void AddAccount(const picojson::value& data, picojson::object& obj); void RemoveAccount(const picojson::value& data, picojson::object& obj); void UpdateAccount(const picojson::value& data, picojson::object& obj); - //bool IsValidPackage(const std::string& packageName); + // bool IsValidPackage(const std::string& packageName); }; -} // namespace account -} // namespace extension +} // namespace account +} // namespace extension -#endif // ACCOUNT_ACCOUNT_MANAGER_H_ +#endif // ACCOUNT_ACCOUNT_MANAGER_H_ diff --git a/src/alarm/alarm_extension.cc b/src/alarm/alarm_extension.cc old mode 100755 new mode 100644 index 2182084..3027641 --- a/src/alarm/alarm_extension.cc +++ b/src/alarm/alarm_extension.cc @@ -33,15 +33,12 @@ common::Extension* CreateExtension() { AlarmExtension::AlarmExtension() { SetExtensionName(kAlarm); SetJavaScriptAPI(kSource_alarm_api); - const char* entry_points[] = { - kAlarmRelative, - kAlarmAbsolute, - NULL - }; + const char* entry_points[] = {kAlarmRelative, kAlarmAbsolute, NULL}; SetExtraJSEntryPoints(entry_points); } -AlarmExtension::~AlarmExtension() {} +AlarmExtension::~AlarmExtension() { +} common::Instance* AlarmExtension::CreateInstance() { return new extension::alarm::AlarmInstance(); diff --git a/src/alarm/alarm_extension.h b/src/alarm/alarm_extension.h old mode 100755 new mode 100644 index 59606e1..6cd7e88 --- a/src/alarm/alarm_extension.h +++ b/src/alarm/alarm_extension.h @@ -28,4 +28,4 @@ class AlarmExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // ALARM_ALARM_EXTENSION_H_ +#endif // ALARM_ALARM_EXTENSION_H_ diff --git a/src/alarm/alarm_instance.cc b/src/alarm/alarm_instance.cc old mode 100755 new mode 100644 index a9e6d00..e1b4008 --- a/src/alarm/alarm_instance.cc +++ b/src/alarm/alarm_instance.cc @@ -16,8 +16,8 @@ #include "alarm_instance.h" -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" namespace extension { namespace alarm { @@ -28,24 +28,20 @@ AlarmInstance::AlarmInstance() { LoggerD("Entered"); using namespace std::placeholders; - RegisterSyncHandler("AlarmManager_add", - std::bind(&AlarmManager::Add, &manager_, _1, _2)); + RegisterSyncHandler("AlarmManager_add", std::bind(&AlarmManager::Add, &manager_, _1, _2)); RegisterSyncHandler("AlarmManager_addAlarmNotification", std::bind(&AlarmManager::AddAlarmNotification, &manager_, _1, _2)); - RegisterSyncHandler("AlarmManager_remove", - std::bind(&AlarmManager::Remove, &manager_, _1, _2)); + RegisterSyncHandler("AlarmManager_remove", std::bind(&AlarmManager::Remove, &manager_, _1, _2)); RegisterSyncHandler("AlarmManager_removeAll", std::bind(&AlarmManager::RemoveAll, &manager_, _1, _2)); - RegisterSyncHandler("AlarmManager_get", - std::bind(&AlarmManager::Get, &manager_, _1, _2)); + RegisterSyncHandler("AlarmManager_get", std::bind(&AlarmManager::Get, &manager_, _1, _2)); RegisterSyncHandler("AlarmManager_getAlarmNotification", std::bind(&AlarmManager::GetAlarmNotification, &manager_, _1, _2)); - RegisterSyncHandler("AlarmManager_getAll", - std::bind(&AlarmManager::GetAll, &manager_, _1, _2)); - //AlarmRelative + RegisterSyncHandler("AlarmManager_getAll", std::bind(&AlarmManager::GetAll, &manager_, _1, _2)); + // AlarmRelative RegisterSyncHandler("AlarmRelative_getRemainingSeconds", std::bind(&AlarmManager::GetRemainingSeconds, &manager_, _1, _2)); - //AlarmAbsolute + // AlarmAbsolute RegisterSyncHandler("AlarmAbsolute_getNextScheduledDate", std::bind(&AlarmManager::GetNextScheduledDate, &manager_, _1, _2)); } @@ -54,5 +50,5 @@ AlarmInstance::~AlarmInstance() { LoggerD("Entered"); } -} // namespace Alarm -} // namespace extension +} // namespace Alarm +} // namespace extension diff --git a/src/alarm/alarm_instance.h b/src/alarm/alarm_instance.h old mode 100755 new mode 100644 index f6a7412..8965b2a --- a/src/alarm/alarm_instance.h +++ b/src/alarm/alarm_instance.h @@ -24,7 +24,7 @@ namespace extension { namespace alarm { -class AlarmInstance: public common::ParsedInstance { +class AlarmInstance : public common::ParsedInstance { public: AlarmInstance(); virtual ~AlarmInstance(); @@ -33,7 +33,7 @@ class AlarmInstance: public common::ParsedInstance { AlarmManager manager_; }; -} // namespace alarm -} // namespace extension +} // namespace alarm +} // namespace extension -#endif // ALARM_ALARM_INSTANCE_H_ +#endif // ALARM_ALARM_INSTANCE_H_ diff --git a/src/alarm/alarm_manager.cc b/src/alarm/alarm_manager.cc old mode 100755 new mode 100644 index 6bb33e4..e8d2087 --- a/src/alarm/alarm_manager.cc +++ b/src/alarm/alarm_manager.cc @@ -22,8 +22,8 @@ #include #include -#include "common/logger.h" #include "common/converter.h" +#include "common/logger.h" #include "common/scope_exit.h" #include "common/tools.h" @@ -41,7 +41,7 @@ namespace extension { namespace alarm { namespace { -const int kDateSize = 22; //"yyy mm dd hh mm ss dd" e.g 115 11 28 11 25 50 -1 +const int kDateSize = 22; //"yyy mm dd hh mm ss dd" e.g 115 11 28 11 25 50 -1 const std::string kPrivilegeAlarm = "http://tizen.org/privilege/alarm"; const std::string kPrivilegeNotification = "http://tizen.org/privilege/notification"; @@ -73,7 +73,8 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeAlarm, &out); if (!args.contains("alarm")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out); return; } const picojson::object& alarm = args.get("alarm").get(); @@ -94,8 +95,8 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { }; if (args.contains("appControl") && args.get("appControl").is()) { - PlatformResult result = util::AppControlToService( - args.get("appControl").get(), &app_control); + PlatformResult result = + util::AppControlToService(args.get("appControl").get(), &app_control); if (!result) { LogAndReportError(result, &out, ("Failed: util::AppControlToService")); return; @@ -121,7 +122,8 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { const auto it_period = alarm.find("period"); if (alarm.end() == it_delay || alarm.end() == it_period || !it_delay->second.is()) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out); return; } int delay = static_cast(it_delay->second.get()); @@ -138,32 +140,31 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { std::string delay_str = std::to_string(delay); int ret = app_control_add_extra_data(app_control, kAlarmRelativeDelayKey, delay_str.c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Fail to add data from app_control."), &out, + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Fail to add data from app_control."), &out, ("Fail to add data from app_control: %d (%s)", ret, get_error_message(ret))); return; } - if(!isPeriodSet){ + if (!isPeriodSet) { ret = alarm_schedule_once_after_delay(app_control, delay, &alarm_id); - }else{ + } else { ret = alarm_schedule_after_delay(app_control, delay, period, &alarm_id); } if (ALARM_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Error while add alarm to server."), &out, - ("Error while add alarm to server: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Error while add alarm to server."), + &out, + ("Error while add alarm to server: %d (%s)", ret, get_error_message(ret))); return; } ret = alarm_get_scheduled_period(alarm_id, &period); if (ALARM_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Unknown error occurred."), &out, - ("Unknown error occurred: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error occurred."), &out, + ("Unknown error occurred: %d (%s)", ret, get_error_message(ret))); return; } - if(period != 0){ + if (period != 0) { result_obj.insert(std::make_pair("period", picojson::value(std::to_string(period)))); } } else { @@ -198,8 +199,8 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { int ret = 0; if (alarm.end() != it_period && it_period->second.is()) { - app_control_add_extra_data( - app_control, kAlarmAbsoluteRecurrenceTypeKey, kAlarmAbsoluteReccurrenceTypeInterval); + app_control_add_extra_data(app_control, kAlarmAbsoluteRecurrenceTypeKey, + kAlarmAbsoluteReccurrenceTypeInterval); period = static_cast(it_period->second.get()); ret = alarm_schedule_at_date(app_control, &start_date, period, &alarm_id); if (ALARM_ERROR_NONE != ret) { @@ -212,28 +213,28 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { ret = alarm_get_scheduled_period(alarm_id, &period); result_obj.insert(std::make_pair("period", picojson::value(std::to_string(period)))); } else if (alarm.end() != it_daysOfTheWeek && it_daysOfTheWeek->second.is() && - !(it_daysOfTheWeek->second.get()).empty()) { - app_control_add_extra_data( - app_control, kAlarmAbsoluteRecurrenceTypeKey, kAlarmAbsoluteReccurrenceTypeByDayValue); - const picojson::array &days_of_the_week = it_daysOfTheWeek->second.get(); + !(it_daysOfTheWeek->second.get()).empty()) { + app_control_add_extra_data(app_control, kAlarmAbsoluteRecurrenceTypeKey, + kAlarmAbsoluteReccurrenceTypeByDayValue); + const picojson::array& days_of_the_week = it_daysOfTheWeek->second.get(); int repeat_value = 0; PlatformResult result = util::ArrayDaysToMask(days_of_the_week, &repeat_value); if (!result) { LogAndReportError(PlatformResult(result.error_code(), result.message()), &out); return; } - ret = alarm_schedule_with_recurrence_week_flag( - app_control, &start_date, repeat_value, &alarm_id); + ret = alarm_schedule_with_recurrence_week_flag(app_control, &start_date, repeat_value, + &alarm_id); } else { - app_control_add_extra_data( - app_control, kAlarmAbsoluteRecurrenceTypeKey, kAlarmAbsoluteRecurrenceTypeNone); + app_control_add_extra_data(app_control, kAlarmAbsoluteRecurrenceTypeKey, + kAlarmAbsoluteRecurrenceTypeNone); ret = alarm_schedule_at_date(app_control, &start_date, 0, &alarm_id); } if (ALARM_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Adding alarm to server failed."), &out, - ("Adding alarm to server failed: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Adding alarm to server failed."), + &out, + ("Adding alarm to server failed: %d (%s)", ret, get_error_message(ret))); return; } } @@ -270,9 +271,9 @@ void AlarmManager::AddAlarmNotification(const picojson::value& args, picojson::o }; using namespace std::placeholders; - GetHandleFromJsonFun impl {}; - if (args.contains("newImpl") && args.get("newImpl").is() - && args.get("newImpl").get()) { + GetHandleFromJsonFun impl{}; + if (args.contains("newImpl") && args.get("newImpl").is() && + args.get("newImpl").get()) { LoggerD("New implementation"); impl = std::bind(&UserNotification::GetNotiHandleFromJson, _1, _2, _3); } else { @@ -348,10 +349,9 @@ void AlarmManager::AddAlarmNotification(const picojson::value& args, picojson::o } } else { if (alarm.find("period")->second.is()) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "AlarmAbsolute constructed by deprecated constructor."), - &out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, + "AlarmAbsolute constructed by deprecated constructor."), + &out); return; } @@ -371,7 +371,7 @@ void AlarmManager::AddAlarmNotification(const picojson::value& args, picojson::o } time_t second = milliseconds / 1000; - struct tm start_date = { 0 }; + struct tm start_date = {0}; tzset(); if (nullptr == localtime_r(&second, &start_date)) { @@ -395,12 +395,12 @@ void AlarmManager::AddAlarmNotification(const picojson::value& args, picojson::o return; } - if (alarm.end() != it_daysOfTheWeek && it_daysOfTheWeek->second.is() - && !(it_daysOfTheWeek->second.get()).empty()) { + if (alarm.end() != it_daysOfTheWeek && it_daysOfTheWeek->second.is() && + !(it_daysOfTheWeek->second.get()).empty()) { app_control_add_extra_data(app_control, kAlarmAbsoluteRecurrenceTypeKey, kAlarmAbsoluteReccurrenceTypeByDayValue); - const picojson::array &days_of_the_week = it_daysOfTheWeek->second.get(); + const picojson::array& days_of_the_week = it_daysOfTheWeek->second.get(); int repeat_value = 0; util::ArrayDaysToMask(days_of_the_week, &repeat_value); @@ -433,8 +433,8 @@ void AlarmManager::AddAlarmNotification(const picojson::value& args, picojson::o } if (ALARM_ERROR_NONE != ret) { - if (ALARM_ERROR_INVALID_TIME == ret || ALARM_ERROR_INVALID_DATE == ret - || ALARM_ERROR_INVALID_PARAMETER == ret) { + if (ALARM_ERROR_INVALID_TIME == ret || ALARM_ERROR_INVALID_DATE == ret || + ALARM_ERROR_INVALID_PARAMETER == ret) { platform_result = PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid data."); } else { platform_result = PlatformResult(ErrorCode::ABORT_ERR, "Error while adding alarm to server."); @@ -476,10 +476,9 @@ void AlarmManager::Remove(const picojson::value& args, picojson::object& out) { } if (id <= 0) { - LogAndReportError(PlatformResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid id."), &out, - ("id is wrong: %d", id)); - return; + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid id."), &out, + ("id is wrong: %d", id)); + return; } int ret = alarm_cancel(id); @@ -488,9 +487,8 @@ void AlarmManager::Remove(const picojson::value& args, picojson::object& out) { } else if (ALARM_ERROR_INVALID_PARAMETER == ret) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Alarm not found."), &out); } else { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, - ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, + ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); } } @@ -500,9 +498,8 @@ void AlarmManager::RemoveAll(const picojson::value& args, picojson::object& out) int ret = alarm_cancel_all(); if (ALARM_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, - ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, + ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); return; } @@ -513,7 +510,8 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { LoggerD("Entered"); if (id <= 0) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid id.", ("id is wrong: %d", id)); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid id.", + ("id is wrong: %d", id)); } int ret = ALARM_ERROR_NONE; @@ -540,10 +538,9 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { notification_handle, &app_control); if (!platform_result) { return LogAndCreateResult( - platform_result.error_code(), - platform_result.message().c_str(), + platform_result.error_code(), platform_result.message().c_str(), ("Failed to get AppControl: %d (%s)", platform_result.error_code(), - platform_result.message().c_str())); + platform_result.message().c_str())); } } } @@ -567,8 +564,8 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { ("Failed to get data: %d (%s)", ret, get_error_message(ret))); } - sscanf(date_string, "%5d %5d %5d %5d %5d %5d %5d", &date.tm_year, &date.tm_mon, - &date.tm_mday, &date.tm_hour, &date.tm_min, &date.tm_sec, &date.tm_isdst); + sscanf(date_string, "%5d %5d %5d %5d %5d %5d %5d", &date.tm_year, &date.tm_mon, &date.tm_mday, + &date.tm_hour, &date.tm_min, &date.tm_sec, &date.tm_isdst); mktime(&date); obj.insert(std::make_pair("year", picojson::value(std::to_string(date.tm_year + 1900)))); @@ -601,23 +598,16 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { picojson::array& array = obj.insert(std::make_pair("second", picojson::value(picojson::array()))) - .first->second.get(); + .first->second.get(); using namespace util; - if (byDayValue & ALARM_WEEK_FLAG_SUNDAY) - array.push_back(picojson::value(kSundayShort)); - if (byDayValue & ALARM_WEEK_FLAG_MONDAY) - array.push_back(picojson::value(kMondayShort)); - if (byDayValue & ALARM_WEEK_FLAG_TUESDAY) - array.push_back(picojson::value(kTuesdayShort)); - if (byDayValue & ALARM_WEEK_FLAG_WEDNESDAY) - array.push_back(picojson::value(kWednesdayShort)); - if (byDayValue & ALARM_WEEK_FLAG_THURSDAY) - array.push_back(picojson::value(kThuesdayShort)); - if (byDayValue & ALARM_WEEK_FLAG_FRIDAY) - array.push_back(picojson::value(kFridayShort)); - if (byDayValue & ALARM_WEEK_FLAG_SATURDAY) - array.push_back(picojson::value(kSaturdayShort)); + if (byDayValue & ALARM_WEEK_FLAG_SUNDAY) array.push_back(picojson::value(kSundayShort)); + if (byDayValue & ALARM_WEEK_FLAG_MONDAY) array.push_back(picojson::value(kMondayShort)); + if (byDayValue & ALARM_WEEK_FLAG_TUESDAY) array.push_back(picojson::value(kTuesdayShort)); + if (byDayValue & ALARM_WEEK_FLAG_WEDNESDAY) array.push_back(picojson::value(kWednesdayShort)); + if (byDayValue & ALARM_WEEK_FLAG_THURSDAY) array.push_back(picojson::value(kThuesdayShort)); + if (byDayValue & ALARM_WEEK_FLAG_FRIDAY) array.push_back(picojson::value(kFridayShort)); + if (byDayValue & ALARM_WEEK_FLAG_SATURDAY) array.push_back(picojson::value(kSaturdayShort)); } obj.insert(std::make_pair("type", picojson::value(kAlarmAbsolute))); @@ -640,8 +630,8 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { obj.insert(std::make_pair("type", picojson::value(kAlarmRelative))); obj.insert(std::make_pair("delay", picojson::value(delay_string))); if (interval != 0) { - //according to documentation interval will not be lower than 600, - //thus 0 from native means period wasn't set by user + // according to documentation interval will not be lower than 600, + // thus 0 from native means period wasn't set by user obj.insert(std::make_pair("period", picojson::value(std::to_string(interval)))); } } else { @@ -693,8 +683,8 @@ void AlarmManager::GetAlarmNotification(const picojson::value& args, picojson::o if (ALARM_ERROR_NONE != ret) { if (ALARM_ERROR_INVALID_PARAMETER == ret) { - platform_result = PlatformResult(ErrorCode::NOT_FOUND_ERR, - "Alarm with given ID was not found."); + platform_result = + PlatformResult(ErrorCode::NOT_FOUND_ERR, "Alarm with given ID was not found."); } else { platform_result = PlatformResult(ErrorCode::ABORT_ERR, "Failed to get notification."); } @@ -720,10 +710,10 @@ void AlarmManager::GetAlarmNotification(const picojson::value& args, picojson::o ReportSuccess(result, out); } -static bool AlarmIterateCB(int alarm_id, void *user_data) { +static bool AlarmIterateCB(int alarm_id, void* user_data) { LoggerD("Enter"); - std::vector *alarm_ids = reinterpret_cast*>(user_data); + std::vector* alarm_ids = reinterpret_cast*>(user_data); alarm_ids->push_back(alarm_id); return true; @@ -736,16 +726,15 @@ void AlarmManager::GetAll(const picojson::value& args, picojson::object& out) { int ret = alarm_foreach_registered_alarm(AlarmIterateCB, &alarm_ids); if (ALARM_ERROR_NONE != ret) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, - ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Platform unknown error."), &out, + ("Platform unknown error: %d (%s)", ret, get_error_message(ret))); return; } picojson::value result_array = picojson::value(picojson::array()); picojson::array& array_obj = result_array.get(); - for (size_t i = 0 ; i < alarm_ids.size(); i++) { + for (size_t i = 0; i < alarm_ids.size(); i++) { picojson::value result = picojson::value(picojson::object()); picojson::object& obj = result.get(); @@ -778,7 +767,7 @@ void AlarmManager::GetRemainingSeconds(const picojson::value& args, picojson::ob picojson::object& result_obj = result.get(); int ret = alarm_get_scheduled_date(id, &date); - if(ALARM_ERROR_NONE != ret) { + if (ALARM_ERROR_NONE != ret) { LoggerI("alarm_get_scheduled_date error: %d (%s)", ret, get_error_message(ret)); if (ALARM_ERROR_INVALID_PARAMETER == ret || ALARM_ERROR_CONNECTION_FAIL == ret) { result_obj.insert(std::make_pair("seconds", picojson::value())); @@ -841,5 +830,5 @@ void AlarmManager::GetNextScheduledDate(const picojson::value& args, picojson::o ReportSuccess(result, out); } -} // namespace alarm -} // namespace extension +} // namespace alarm +} // namespace extension diff --git a/src/alarm/alarm_manager.h b/src/alarm/alarm_manager.h old mode 100755 new mode 100644 index 2920787..f7c0f3f --- a/src/alarm/alarm_manager.h +++ b/src/alarm/alarm_manager.h @@ -36,19 +36,18 @@ class AlarmManager { void GetAlarmNotification(const picojson::value& args, picojson::object& out); void GetAll(const picojson::value& args, picojson::object& out); - //AlarmRelative + // AlarmRelative void GetRemainingSeconds(const picojson::value& args, picojson::object& out); - //AlarmAbsolute + // AlarmAbsolute void GetNextScheduledDate(const picojson::value& args, picojson::object& out); private: AlarmManager(const AlarmManager&) = delete; AlarmManager& operator=(const AlarmManager&) = delete; common::PlatformResult GetAlarm(int id, picojson::object& obj); - }; -} // namespace alarm -} // namespace extension +} // namespace alarm +} // namespace extension -#endif // ALARM_ALARM_MANAGER_H_ +#endif // ALARM_ALARM_MANAGER_H_ diff --git a/src/alarm/alarm_utils.cc b/src/alarm/alarm_utils.cc old mode 100755 new mode 100644 index 9c7c1e4..a80e657 --- a/src/alarm/alarm_utils.cc +++ b/src/alarm/alarm_utils.cc @@ -34,7 +34,7 @@ const char* kSaturdayShort = "SA"; using namespace common; -PlatformResult AppControlToService(const picojson::object& obj, app_control_h *app_control) { +PlatformResult AppControlToService(const picojson::object& obj, app_control_h* app_control) { LoggerD("Entered"); const auto it_end = obj.end(); @@ -49,25 +49,27 @@ PlatformResult AppControlToService(const picojson::object& obj, app_control_h *a if (APP_CONTROL_ERROR_NONE != result) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Creation AppControl failed.", - ("Problem with create handle.")); + ("Problem with create handle.")); } - std::unique_ptr::type, int(*)(app_control_h)> app_control_ptr( + std::unique_ptr::type, int (*)(app_control_h)> app_control_ptr( app_control_tmp, &app_control_destroy); - - int ret = app_control_set_operation(app_control_tmp, it_operation->second.get().c_str()); + int ret = + app_control_set_operation(app_control_tmp, it_operation->second.get().c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while setting operation.", - ("Failed app_control_set_operation(): %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while setting operation.", + ("Failed app_control_set_operation(): %d (%s)", ret, get_error_message(ret))); } const auto it_uri = obj.find("uri"); if (it_end != it_uri && it_uri->second.is()) { ret = app_control_set_uri(app_control_tmp, it_uri->second.get().c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while setting uri.", - ("Failed app_control_set_uri(): %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while setting uri.", + ("Failed app_control_set_uri(): %d (%s)", ret, get_error_message(ret))); } } @@ -75,8 +77,9 @@ PlatformResult AppControlToService(const picojson::object& obj, app_control_h *a if (it_end != it_mime && it_mime->second.is()) { ret = app_control_set_mime(app_control_tmp, it_mime->second.get().c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while setting mime.", - ("Failed app_control_set_mime(): %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while setting mime.", + ("Failed app_control_set_mime(): %d (%s)", ret, get_error_message(ret))); } } @@ -84,8 +87,9 @@ PlatformResult AppControlToService(const picojson::object& obj, app_control_h *a if (it_end != it_category && it_category->second.is()) { ret = app_control_set_category(app_control_tmp, it_category->second.get().c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while setting category.", - ("Failed app_control_set_category(): %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while setting category.", + ("Failed app_control_set_category(): %d (%s)", ret, get_error_message(ret))); } } @@ -109,16 +113,14 @@ PlatformResult AppControlToService(const picojson::object& obj, app_control_h *a } PlatformResult AppControlToServiceExtraData(const picojson::object& app_obj, - app_control_h *app_control) { + app_control_h* app_control) { LoggerD("Entered"); const auto it_key = app_obj.find("key"); const auto it_value = app_obj.find("value"); const auto it_end = app_obj.end(); - if (it_key == it_end || - it_value == it_end || - !it_key->second.is() || + if (it_key == it_end || it_value == it_end || !it_key->second.is() || !it_value->second.is()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Problem with key or value."); } @@ -150,7 +152,7 @@ PlatformResult AppControlToServiceExtraData(const picojson::object& app_obj, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ArrayDaysToMask(const picojson::array &days_of_the_week, int *repeat_value) { +PlatformResult ArrayDaysToMask(const picojson::array& days_of_the_week, int* repeat_value) { LoggerD("Entered"); for (auto iter = days_of_the_week.begin(); iter != days_of_the_week.end(); ++iter) { auto day = (*iter).get(); @@ -175,6 +177,6 @@ PlatformResult ArrayDaysToMask(const picojson::array &days_of_the_week, int *rep return PlatformResult(ErrorCode::NO_ERROR); } -} // util -} // alarm -} // extension +} // util +} // alarm +} // extension diff --git a/src/alarm/alarm_utils.h b/src/alarm/alarm_utils.h old mode 100755 new mode 100644 index 048fea3..c1a7fe2 --- a/src/alarm/alarm_utils.h +++ b/src/alarm/alarm_utils.h @@ -17,8 +17,8 @@ #ifndef ALARM_ALARM_UTILS_H_ #define ALARM_ALARM_UTILS_H_ -#include #include +#include #include "common/picojson.h" #include "common/platform_result.h" @@ -35,13 +35,12 @@ extern const char* kThuesdayShort; extern const char* kFridayShort; extern const char* kSaturdayShort; -common::PlatformResult AppControlToService(const picojson::object& obj, app_control_h *app_control); +common::PlatformResult AppControlToService(const picojson::object& obj, app_control_h* app_control); common::PlatformResult AppControlToServiceExtraData(const picojson::object& app_obj, - app_control_h *app_control); -common::PlatformResult ArrayDaysToMask(const picojson::array &days_of_the_week, - int *repeat_value); -} // util -} // alarm -} // extension + app_control_h* app_control); +common::PlatformResult ArrayDaysToMask(const picojson::array& days_of_the_week, int* repeat_value); +} // util +} // alarm +} // extension -#endif // ALARM_ALARM_UTILS_H_ +#endif // ALARM_ALARM_UTILS_H_ diff --git a/src/application/application.cc b/src/application/application.cc old mode 100755 new mode 100644 index 7842a4c..6879658 --- a/src/application/application.cc +++ b/src/application/application.cc @@ -28,7 +28,7 @@ namespace extension { namespace application { RequestedApplicationControl& Application::app_control() { - return app_control_; + return app_control_; } void Application::GetRequestedAppControl(const picojson::value& args, picojson::object* out) { diff --git a/src/application/application.h b/src/application/application.h old mode 100755 new mode 100644 index 2c6905c..bd7816a --- a/src/application/application.h +++ b/src/application/application.h @@ -17,11 +17,11 @@ #ifndef SRC_APPLICATION_APPLICATION_H_ #define SRC_APPLICATION_APPLICATION_H_ -#include #include +#include -#include "common/picojson.h" #include "application/requested_application_control.h" +#include "common/picojson.h" namespace extension { namespace application { diff --git a/src/application/application_extension.cc b/src/application/application_extension.cc old mode 100755 new mode 100644 index 1379e0c..17e25b4 --- a/src/application/application_extension.cc +++ b/src/application/application_extension.cc @@ -44,11 +44,7 @@ ApplicationExtension::ApplicationExtension() { SetExtensionName(kApplication); SetJavaScriptAPI(kSource_application_api); - const char* entry_points[] = { - kApplicationControl, - kApplicationControlData, - NULL - }; + const char* entry_points[] = {kApplicationControl, kApplicationControlData, NULL}; SetExtraJSEntryPoints(entry_points); } diff --git a/src/application/application_extension.h b/src/application/application_extension.h old mode 100755 new mode 100644 index c0aa74b..8aba615 --- a/src/application/application_extension.h +++ b/src/application/application_extension.h @@ -26,7 +26,9 @@ class ApplicationExtension : public common::Extension { ApplicationExtension(); virtual ~ApplicationExtension(); - std::string app_id() const { return app_id_; } + std::string app_id() const { + return app_id_; + } private: std::string app_id_; diff --git a/src/application/application_instance.cc b/src/application/application_instance.cc old mode 100755 new mode 100644 index 44a51f6..e289614 --- a/src/application/application_instance.cc +++ b/src/application/application_instance.cc @@ -16,11 +16,11 @@ #include "application/application_instance.h" +#include "common/current_application.h" #include "common/logger.h" #include "common/picojson.h" #include "common/platform_exception.h" #include "common/task-queue.h" -#include "common/current_application.h" #include "common/tools.h" namespace extension { @@ -28,7 +28,8 @@ namespace application { namespace { // The privileges that are required in Application API -const std::string kPrivilegeAppManagerCertificate = "http://tizen.org/privilege/appmanager.certificate"; +const std::string kPrivilegeAppManagerCertificate = + "http://tizen.org/privilege/appmanager.certificate"; const std::string kPrivilegeAppManagerKill = "http://tizen.org/privilege/appmanager.kill"; const std::string kPrivilegeApplicationInfo = "http://tizen.org/privilege/application.info"; const std::string kPrivilegeApplicationLaunch = "http://tizen.org/privilege/application.launch"; @@ -37,8 +38,7 @@ const std::string kPrivilegeAppHistoryRead = "http://tizen.org/privilege/apphist using namespace common; -ApplicationInstance::ApplicationInstance() : - manager_(*this) { +ApplicationInstance::ApplicationInstance() : manager_(*this) { LoggerD("Entered"); app_id_ = CurrentApplication::GetInstance().GetApplicationId(); @@ -52,8 +52,8 @@ ApplicationInstance::ApplicationInstance() : using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&ApplicationInstance::x, this, _1, _2)); - //ApplicationManager + RegisterSyncHandler(c, std::bind(&ApplicationInstance::x, this, _1, _2)); + // ApplicationManager REGISTER_SYNC("ApplicationManager_getCurrentApplication", GetCurrentApplication); REGISTER_SYNC("ApplicationManager_getAppContext", GetAppContext); REGISTER_SYNC("ApplicationManager_getAppInfo", GetAppInfo); @@ -65,24 +65,24 @@ ApplicationInstance::ApplicationInstance() : REGISTER_SYNC("ApplicationManager_addAppStatusChangeListener", AddStatusListener); REGISTER_SYNC("ApplicationManager_removeStatusChangeListener", RemoveStatusListener); - //Application + // Application REGISTER_SYNC("Application_getRequestedAppControl", GetRequestedAppControl); REGISTER_SYNC("Application_broadcastEvent", BroadcastEvent); REGISTER_SYNC("Application_broadcastTrustedEvent", BroadcastTrustedEvent); REGISTER_SYNC("Application_addEventListener", AddEventListener); REGISTER_SYNC("Application_removeEventListener", RemoveEventListener); - //RequestedApplicationControl + // RequestedApplicationControl REGISTER_SYNC("RequestedApplicationControl_replyResult", ReplyResult); REGISTER_SYNC("RequestedApplicationControl_replyFailure", ReplyFailure); - //ApplicationInformation + // ApplicationInformation REGISTER_SYNC("ApplicationInformation_getSize", GetSize); #undef REGISTER_SYNC #define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&ApplicationInstance::x, this, _1, _2)); - //ApplicationManager + RegisterSyncHandler(c, std::bind(&ApplicationInstance::x, this, _1, _2)); + // ApplicationManager REGISTER_ASYNC("ApplicationManager_kill", Kill); REGISTER_ASYNC("ApplicationManager_launch", Launch); REGISTER_ASYNC("ApplicationManager_launchAppControl", LaunchAppControl); @@ -98,7 +98,8 @@ ApplicationInstance::~ApplicationInstance() { LoggerD("Entered"); } -void ApplicationInstance::GetCurrentApplication(const picojson::value& args, picojson::object& out) { +void ApplicationInstance::GetCurrentApplication(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); manager_.GetCurrentApplication(app_id_, &out); @@ -176,24 +177,31 @@ void ApplicationInstance::GetAppsUsageInfo(const picojson::value& args, picojson manager_.GetAppsUsageInfo(args, &out); } -void ApplicationInstance::AddAppInfoEventListener(const picojson::value& args, picojson::object& out) { +void ApplicationInstance::AddAppInfoEventListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); - LoggerW("DEPRECATION WARNING: addAppInfoEventListener() is deprecated and will be removed from next release. " + LoggerW( + "DEPRECATION WARNING: addAppInfoEventListener() is deprecated and will be removed from next " + "release. " "Use tizen.package.setPackageInfoEventListener() instead."); manager_.StartAppInfoEventListener(&out); - } +} -void ApplicationInstance::RemoveAppInfoEventListener(const picojson::value& args, picojson::object& out) { +void ApplicationInstance::RemoveAppInfoEventListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); - LoggerW("DEPRECATION WARNING: removeAppInfoEventListener() is deprecated and will be removed from next release. " - "Use tizen.package.unsetPackageInfoEventListener() instead."); + LoggerW( + "DEPRECATION WARNING: removeAppInfoEventListener() is deprecated and will be removed from " + "next release. " + "Use tizen.package.unsetPackageInfoEventListener() instead."); manager_.StopAppInfoEventListener(); ReportSuccess(out); } -void ApplicationInstance::GetRequestedAppControl(const picojson::value& args, picojson::object& out) { +void ApplicationInstance::GetRequestedAppControl(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); current_application_.GetRequestedAppControl(args, &out); @@ -267,7 +275,8 @@ void ApplicationInstance::BroadcastEvent(const picojson::value& args, picojson:: manager_.BroadcastEventHelper(args, out, false); } -void ApplicationInstance::BroadcastTrustedEvent(const picojson::value& args, picojson::object& out) { +void ApplicationInstance::BroadcastTrustedEvent(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); manager_.BroadcastEventHelper(args, out, true); @@ -281,11 +290,11 @@ void ApplicationInstance::AddEventListener(const picojson::value& args, picojson LOGGER(DEBUG) << "event_name: " << event_name; JsonCallback cb = [this, args](picojson::value* event) -> void { - picojson::object& event_o = event->get(); - event_o["listenerId"] = args.get("listenerId"); - LOGGER(DEBUG) << event->serialize().c_str(); - Instance::PostMessage(this, event->serialize().c_str()); - LOGGER(DEBUG) << event->serialize().c_str(); + picojson::object& event_o = event->get(); + event_o["listenerId"] = args.get("listenerId"); + LOGGER(DEBUG) << event->serialize().c_str(); + Instance::PostMessage(this, event->serialize().c_str()); + LOGGER(DEBUG) << event->serialize().c_str(); }; PlatformResult result = manager_.StartEventListener(event_name, cb); diff --git a/src/application/application_instance.h b/src/application/application_instance.h old mode 100755 new mode 100644 index 69cf042..8cafed2 --- a/src/application/application_instance.h +++ b/src/application/application_instance.h @@ -19,18 +19,19 @@ #include -#include "common/extension.h" -#include "application/application_manager.h" #include "application/application.h" +#include "application/application_manager.h" #include "application/requested_application_control.h" +#include "common/extension.h" namespace extension { namespace application { -class ApplicationInstance: public common::ParsedInstance { +class ApplicationInstance : public common::ParsedInstance { public: ApplicationInstance(); virtual ~ApplicationInstance(); + private: void GetCurrentApplication(const picojson::value& args, picojson::object& out); void GetAppContext(const picojson::value& args, picojson::object& out); diff --git a/src/application/application_manager.cc b/src/application/application_manager.cc old mode 100755 new mode 100644 index 1f34769..a5e69f9 --- a/src/application/application_manager.cc +++ b/src/application/application_manager.cc @@ -16,19 +16,19 @@ #include "application_manager.h" -#include #include +#include +#include #include #include +#include #include -#include -#include -#include #include #include -#include -#include +#include +#include +#include #include "common/current_application.h" #include "common/logger.h" @@ -60,7 +60,6 @@ const char* kUninstallEvent = PKGMGR_INSTALLER_UNINSTALL_EVENT_STR; const char* kAppidKey = "appid"; - const std::string kAction = "action"; const std::string kCallbackId = "callbackId"; const std::string kOnInstalled = "oninstalled"; @@ -75,29 +74,28 @@ const std::string kAppUsageModeFrequently = "FREQUENTLY"; const std::string kAppUsageModeRecently = "RECENTLY"; const std::map event_map_ = { - {SYSTEM_EVENT_BATTERY_CHARGER_STATUS, EVENT_KEY_BATTERY_CHARGER_STATUS}, - {SYSTEM_EVENT_BATTERY_LEVEL_STATUS, EVENT_KEY_BATTERY_LEVEL_STATUS}, - {SYSTEM_EVENT_USB_STATUS, EVENT_KEY_USB_STATUS}, - {SYSTEM_EVENT_EARJACK_STATUS, EVENT_KEY_EARJACK_STATUS}, - {SYSTEM_EVENT_DISPLAY_STATE, EVENT_KEY_DISPLAY_STATE}, - {SYSTEM_EVENT_LOW_MEMORY, EVENT_KEY_LOW_MEMORY}, - {SYSTEM_EVENT_WIFI_STATE, EVENT_KEY_WIFI_STATE}, - {SYSTEM_EVENT_BT_STATE, EVENT_KEY_BT_STATE}, - {SYSTEM_EVENT_LOCATION_ENABLE_STATE, EVENT_KEY_LOCATION_ENABLE_STATE}, - {SYSTEM_EVENT_GPS_ENABLE_STATE, EVENT_KEY_GPS_ENABLE_STATE}, - {SYSTEM_EVENT_NPS_ENABLE_STATE, EVENT_KEY_NPS_ENABLE_STATE}, - {SYSTEM_EVENT_INCOMING_MSG, EVENT_KEY_MSG_TYPE}, - {SYSTEM_EVENT_TIME_ZONE, EVENT_KEY_TIME_ZONE}, - {SYSTEM_EVENT_HOUR_FORMAT, EVENT_KEY_HOUR_FORMAT}, - {SYSTEM_EVENT_LANGUAGE_SET, EVENT_KEY_LANGUAGE_SET}, - {SYSTEM_EVENT_REGION_FORMAT, EVENT_KEY_REGION_FORMAT}, - {SYSTEM_EVENT_SILENT_MODE, EVENT_KEY_SILENT_MODE}, - {SYSTEM_EVENT_VIBRATION_STATE, EVENT_KEY_VIBRATION_STATE}, - {SYSTEM_EVENT_SCREEN_AUTOROTATE_STATE, EVENT_KEY_SCREEN_AUTOROTATE_STATE}, - {SYSTEM_EVENT_MOBILE_DATA_STATE, EVENT_KEY_MOBILE_DATA_STATE}, - {SYSTEM_EVENT_DATA_ROAMING_STATE, EVENT_KEY_DATA_ROAMING_STATE}, - {SYSTEM_EVENT_FONT_SET, EVENT_KEY_FONT_SET} -}; + {SYSTEM_EVENT_BATTERY_CHARGER_STATUS, EVENT_KEY_BATTERY_CHARGER_STATUS}, + {SYSTEM_EVENT_BATTERY_LEVEL_STATUS, EVENT_KEY_BATTERY_LEVEL_STATUS}, + {SYSTEM_EVENT_USB_STATUS, EVENT_KEY_USB_STATUS}, + {SYSTEM_EVENT_EARJACK_STATUS, EVENT_KEY_EARJACK_STATUS}, + {SYSTEM_EVENT_DISPLAY_STATE, EVENT_KEY_DISPLAY_STATE}, + {SYSTEM_EVENT_LOW_MEMORY, EVENT_KEY_LOW_MEMORY}, + {SYSTEM_EVENT_WIFI_STATE, EVENT_KEY_WIFI_STATE}, + {SYSTEM_EVENT_BT_STATE, EVENT_KEY_BT_STATE}, + {SYSTEM_EVENT_LOCATION_ENABLE_STATE, EVENT_KEY_LOCATION_ENABLE_STATE}, + {SYSTEM_EVENT_GPS_ENABLE_STATE, EVENT_KEY_GPS_ENABLE_STATE}, + {SYSTEM_EVENT_NPS_ENABLE_STATE, EVENT_KEY_NPS_ENABLE_STATE}, + {SYSTEM_EVENT_INCOMING_MSG, EVENT_KEY_MSG_TYPE}, + {SYSTEM_EVENT_TIME_ZONE, EVENT_KEY_TIME_ZONE}, + {SYSTEM_EVENT_HOUR_FORMAT, EVENT_KEY_HOUR_FORMAT}, + {SYSTEM_EVENT_LANGUAGE_SET, EVENT_KEY_LANGUAGE_SET}, + {SYSTEM_EVENT_REGION_FORMAT, EVENT_KEY_REGION_FORMAT}, + {SYSTEM_EVENT_SILENT_MODE, EVENT_KEY_SILENT_MODE}, + {SYSTEM_EVENT_VIBRATION_STATE, EVENT_KEY_VIBRATION_STATE}, + {SYSTEM_EVENT_SCREEN_AUTOROTATE_STATE, EVENT_KEY_SCREEN_AUTOROTATE_STATE}, + {SYSTEM_EVENT_MOBILE_DATA_STATE, EVENT_KEY_MOBILE_DATA_STATE}, + {SYSTEM_EVENT_DATA_ROAMING_STATE, EVENT_KEY_DATA_ROAMING_STATE}, + {SYSTEM_EVENT_FONT_SET, EVENT_KEY_FONT_SET}}; #ifdef TIZEN_MOBILE const int kMaximumBatteryRetrievedObjects = 30; @@ -106,12 +104,12 @@ const int kDefaultPeriodOfTime = 30; #endif } -ApplicationManager::ApplicationManager(ApplicationInstance& instance) : - pkgmgr_client_handle_(nullptr), - pkgmgr_client_uninstall_handle_(nullptr), - instance_(instance), - app_status_handle_(nullptr) { - LoggerD("Enter"); +ApplicationManager::ApplicationManager(ApplicationInstance& instance) + : pkgmgr_client_handle_(nullptr), + pkgmgr_client_uninstall_handle_(nullptr), + instance_(instance), + app_status_handle_(nullptr) { + LoggerD("Enter"); } ApplicationManager::~ApplicationManager() { @@ -122,13 +120,12 @@ ApplicationManager::~ApplicationManager() { if (app_status_handle_) { int ret = app_manager_event_destroy(app_status_handle_); if (APP_MANAGER_ERROR_NONE != ret) { - LoggerE ("app_manager_event_destroy failed, error: %d", ret); + LoggerE("app_manager_event_destroy failed, error: %d", ret); } } } -void ApplicationManager::GetCurrentApplication(const std::string& app_id, - picojson::object* out) { +void ApplicationManager::GetCurrentApplication(const std::string& app_id, picojson::object* out) { LoggerD("Entered"); // obtain handle to application info @@ -150,7 +147,8 @@ void ApplicationManager::GetCurrentApplication(const std::string& app_id, picojson::object& result_obj = result.get(); result_obj.insert(std::make_pair( - "contextId", picojson::value(std::to_string(CurrentApplication::GetInstance().GetProcessId())))); + "contextId", + picojson::value(std::to_string(CurrentApplication::GetInstance().GetProcessId())))); result_obj.insert(std::make_pair("appInfo", app_info)); ReportSuccess(result, *out); @@ -158,11 +156,8 @@ void ApplicationManager::GetCurrentApplication(const std::string& app_id, class TerminateHandler { public: - TerminateHandler(int callback_id, ApplicationInstance* app_instance) : - callback_handle_(callback_id), - pid_(-1), - timeout_id_(0), - app_instance_(app_instance) { + TerminateHandler(int callback_id, ApplicationInstance* app_instance) + : callback_handle_(callback_id), pid_(-1), timeout_id_(0), app_instance_(app_instance) { } void set_pid(pid_t pid) { @@ -184,12 +179,14 @@ class TerminateHandler { ApplicationInstance* app_instance = this->app_instance_; int callback_id = this->callback_handle_; - TaskQueue::GetInstance().Async([callback_id, app_instance]( - const std::shared_ptr& response) { - picojson::object& obj = response->get(); - obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); - Instance::PostMessage(app_instance, response->serialize().c_str()); - }, response); + TaskQueue::GetInstance().Async( + [callback_id, app_instance](const std::shared_ptr& response) { + picojson::object& obj = response->get(); + obj.insert( + std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); + Instance::PostMessage(app_instance, response->serialize().c_str()); + }, + response); } void LaunchCheckTerminate() { @@ -213,14 +210,13 @@ class TerminateHandler { LoggerD("checking if application is still alive"); int ret = app_manager_get_app_id(that->pid_, &app_id); if (APP_MANAGER_ERROR_NONE == ret) { - free(app_id); - // context is still alive, report error - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to kill application."), - &response->get(), - ("application is alive - failure")); + free(app_id); + // context is still alive, report error + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to kill application."), + &response->get(), ("application is alive - failure")); } else { LoggerD("application is dead - success: %d (%s)", ret, get_error_message(ret)); - ReportSuccess(response->get()); + ReportSuccess(response->get()); } that->Invoke(response); @@ -235,24 +231,24 @@ class TerminateHandler { ApplicationInstance* app_instance_; }; -#define CHECK_RESULT(result, response, handler) \ - if (result.IsError()) { \ +#define CHECK_RESULT(result, response, handler) \ + if (result.IsError()) { \ LogAndReportError(result, &response->get()); \ - handler->Invoke(response); \ - delete handler; \ - return; \ + handler->Invoke(response); \ + delete handler; \ + return; \ } void ApplicationManager::AsyncResponse(PlatformResult& result, std::shared_ptr* response) { - LoggerD("Enter"); LogAndReportError(result, &(*response)->get()); - TaskQueue::GetInstance().Async([this]( - const std::shared_ptr& response) { + TaskQueue::GetInstance().Async( + [this](const std::shared_ptr& response) { Instance::PostMessage(&this->instance_, response->serialize().c_str()); - }, *response); + }, + *response); } void ApplicationManager::Kill(const picojson::value& args) { @@ -311,7 +307,8 @@ void ApplicationManager::Kill(const picojson::value& args) { // if kill request comes for current context, throw InvalidValuesException if (CurrentApplication::GetInstance().GetProcessId() == pid) { - result = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Cannot kill current application."); + result = + LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Cannot kill current application."); CHECK_RESULT(result, response, handler) } @@ -320,11 +317,12 @@ void ApplicationManager::Kill(const picojson::value& args) { char* app_id = nullptr; int ret = app_manager_get_app_id(pid, &app_id); // automatically release the memory - std::unique_ptr app_id_ptr(app_id, &std::free); + std::unique_ptr app_id_ptr(app_id, &std::free); if (APP_MANAGER_ERROR_NONE != ret) { - result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Failed to get application ID.", - ("Failed to get application ID, error: %d (%s)", ret, get_error_message(ret))); + result = LogAndCreateResult( + ErrorCode::NOT_FOUND_ERR, "Failed to get application ID.", + ("Failed to get application ID, error: %d (%s)", ret, get_error_message(ret))); CHECK_RESULT(result, response, handler) } @@ -334,18 +332,18 @@ void ApplicationManager::Kill(const picojson::value& args) { app_context_h app_context = nullptr; ret = app_manager_get_app_context(app_id, &app_context); - std::unique_ptr::type, int(*)(app_context_h)> - app_context_ptr(app_context, &app_context_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(app_context_h)> + app_context_ptr(app_context, &app_context_destroy); // automatically release the memory if (APP_MANAGER_ERROR_NONE != ret) { - result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Failed to get application ID.", - ("Failed to get application context handle: %d (%s)", ret, get_error_message(ret))); + result = LogAndCreateResult( + ErrorCode::NOT_FOUND_ERR, "Failed to get application ID.", + ("Failed to get application context handle: %d (%s)", ret, get_error_message(ret))); CHECK_RESULT(result, response, handler) } - auto terminate_callback = [](app_context_h app_context, - app_context_event_e event, - void* user_data) { + auto terminate_callback = [](app_context_h app_context, app_context_event_e event, + void* user_data) { LoggerD("terminate_callback: %d", event); if (APP_CONTEXT_EVENT_TERMINATED != event) { @@ -379,15 +377,16 @@ void ApplicationManager::Kill(const picojson::value& args) { ret = app_manager_set_app_context_event_cb(terminate_callback, handler); if (APP_MANAGER_ERROR_NONE != ret) { - result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register termination callback.", - ("Error while registering app context event: %d (%s)", ret, get_error_message(ret))); + result = LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to register termination callback.", + ("Error while registering app context event: %d (%s)", ret, get_error_message(ret))); CHECK_RESULT(result, response, handler) } // due to platform issue, sometimes termination event is not reported to callback // registered with app_manager_set_app_context_event_cb() // this is a workaround, it should be removed when issue is solved - //handler->LaunchCheckTerminate(); + // handler->LaunchCheckTerminate(); LoggerD("Kill async, KILL!!!!!!!!!"); @@ -395,8 +394,9 @@ void ApplicationManager::Kill(const picojson::value& args) { ret = app_manager_terminate_app(app_context); if (APP_MANAGER_ERROR_NONE != ret) { - result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to terminate application.", - ("Failed to terminate application: %d (%s)", ret, get_error_message(ret))); + result = LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to terminate application.", + ("Failed to terminate application: %d (%s)", ret, get_error_message(ret))); CHECK_RESULT(result, response, handler) } @@ -421,7 +421,8 @@ void ApplicationManager::Launch(const picojson::value& args) { const auto& app_id = args.get("id"); if (!app_id.is()) { - PlatformResult ret = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."); + PlatformResult ret = + LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."); AsyncResponse(ret, &response); return; } @@ -443,7 +444,7 @@ void ApplicationManager::Launch(const picojson::value& args) { } // delay 300ms for each retry - struct timespec sleep_time = { 0, 300L * 1000L * 1000L }; + struct timespec sleep_time = {0, 300L * 1000L * 1000L}; nanosleep(&sleep_time, nullptr); ++retry; @@ -458,13 +459,14 @@ void ApplicationManager::Launch(const picojson::value& args) { case AUL_R_EINVAL: case AUL_R_ERROR: case AUL_R_ENOAPP: - result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Launchpad returns not found error.", - ("aul_open_app returns Not Found error")); + result = + LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Launchpad returns not found error.", + ("aul_open_app returns Not Found error")); break; case AUL_R_ECOMM: result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Internal IPC error has occurred.", - ("aul_open_app returns internal IPC error")); + ("aul_open_app returns internal IPC error")); break; } @@ -513,8 +515,8 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { app_control_h app_control = nullptr; result = ApplicationUtils::ApplicationControlToService(app_control_obj, &app_control); - std::shared_ptr::type> - app_control_ptr(app_control, &app_control_destroy); // automatically release the memory + std::shared_ptr::type> app_control_ptr( + app_control, &app_control_destroy); // automatically release the memory if (result.IsError()) { LoggerE("Application control to service failed."); @@ -534,8 +536,8 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { reply_callback = reply.get(); } - auto launch = [this, app_control_ptr, app_id, launch_mode_str, reply_callback]( - const std::shared_ptr& response) -> void { + auto launch = [this, app_control_ptr, app_id, launch_mode_str, + reply_callback](const std::shared_ptr& response) -> void { LoggerD("Entered"); if (!app_id.empty()) { @@ -544,9 +546,10 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { int ret = app_control_set_app_id(app_control_ptr.get(), app_id.c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), - &response->get(), - ("Failed to set app id: %d (%s)", ret, get_error_message(ret))); + LogAndReportError( + PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &response->get(), + ("Failed to set app id: %d (%s)", ret, get_error_message(ret))); return; } } @@ -567,8 +570,8 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { int ret = app_control_set_launch_mode(app_control_ptr.get(), launch_mode); if (APP_CONTROL_ERROR_NONE != ret) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Setting launch mode failed."), - &response->get(), - ("Setting launch mode failed: %d (%s)", ret, get_error_message(ret))); + &response->get(), + ("Setting launch mode failed: %d (%s)", ret, get_error_message(ret))); return; } } @@ -586,8 +589,8 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { user_data->app_instance = &this->instance_; user_data->reply_callback = reply_callback; - callback = [](app_control_h request, - app_control_h reply, app_control_result_e result, void* user_data) { + callback = [](app_control_h request, app_control_h reply, app_control_result_e result, + void* user_data) { LoggerD("send_launch_request callback"); picojson::value return_value = picojson::value(picojson::object()); @@ -598,7 +601,7 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { const std::string data = "data"; return_value_obj.insert(std::make_pair(data, picojson::value(picojson::array()))); if (!ApplicationUtils::ServiceToApplicationControlDataArray( - reply, &return_value_obj.find(data)->second.get())) { + reply, &return_value_obj.find(data)->second.get())) { return_value_obj.erase(data); } ReportSuccess(return_value_obj); @@ -628,7 +631,7 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { } // delay 300ms for each retry - struct timespec sleep_time = { 0, 300L * 1000L * 1000L }; + struct timespec sleep_time = {0, 300L * 1000L * 1000L}; nanosleep(&sleep_time, nullptr); ++retry; } @@ -638,25 +641,29 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { switch (ret) { case APP_CONTROL_ERROR_INVALID_PARAMETER: - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter returned."), - &response->get(), - ("app_control_send_launch_request returns APP_CONTROL_ERROR_INVALID_PARAMETER")); + LogAndReportError( + PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter returned."), + &response->get(), + ("app_control_send_launch_request returns APP_CONTROL_ERROR_INVALID_PARAMETER")); return; case APP_CONTROL_ERROR_OUT_OF_MEMORY: - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Out of memory."), - &response->get(), - ("app_control_send_launch_request returns APP_CONTROL_ERROR_OUT_OF_MEMORY")); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Out of memory."), + &response->get(), + ("app_control_send_launch_request returns APP_CONTROL_ERROR_OUT_OF_MEMORY")); return; case APP_CONTROL_ERROR_LAUNCH_REJECTED: case APP_CONTROL_ERROR_APP_NOT_FOUND: - LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "No matched application found."), - &response->get(), - ("app_control_send_launch_request returns APP_CONTROL_ERROR_APP_NOT_FOUND")); + LogAndReportError( + PlatformResult(ErrorCode::NOT_FOUND_ERR, "No matched application found."), + &response->get(), + ("app_control_send_launch_request returns APP_CONTROL_ERROR_APP_NOT_FOUND")); return; default: - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), - &response->get(), - ("app_control_send_launch_request returns: %d (%s)", ret, get_error_message(ret))); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), + &response->get(), + ("app_control_send_launch_request returns: %d (%s)", ret, get_error_message(ret))); return; } } @@ -672,19 +679,21 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { TaskQueue::GetInstance().Queue(launch, launch_response, response); } -//internal impl of app_control_foreach_app_matched() for handling APP_CONTROL_ERROR_APP_NOT_FOUND -//public CAPI did not handling APP_CONTROL_ERROR_APP_NOT_FOUND -int app_control_foreach_app_matched_internal(app_control_h app_control, app_control_app_matched_cb callback, void* user_data){ +// internal impl of app_control_foreach_app_matched() for handling APP_CONTROL_ERROR_APP_NOT_FOUND +// public CAPI did not handling APP_CONTROL_ERROR_APP_NOT_FOUND +int app_control_foreach_app_matched_internal(app_control_h app_control, + app_control_app_matched_cb callback, void* user_data) { typedef struct { app_control_h app_control; app_control_app_matched_cb callback; - void *user_data; + void* user_data; bool foreach_break; - } foreach_context_launchable_app_t_internal; + } foreach_context_launchable_app_t_internal; - //internal impl of app_control_cb_broker_foreach_app_matched() - auto app_control_cb_broker_foreach_app_matched_internal = [](const char *package, void *data) -> int { - foreach_context_launchable_app_t_internal *foreach_context; + // internal impl of app_control_cb_broker_foreach_app_matched() + auto app_control_cb_broker_foreach_app_matched_internal = [](const char* package, + void* data) -> int { + foreach_context_launchable_app_t_internal* foreach_context; app_control_app_matched_cb app_matched_cb; if (package == NULL || data == NULL) { @@ -692,15 +701,15 @@ int app_control_foreach_app_matched_internal(app_control_h app_control, app_cont return -1; } - foreach_context = (foreach_context_launchable_app_t_internal *)data; - if (foreach_context->foreach_break == true) - return -1; + foreach_context = (foreach_context_launchable_app_t_internal*)data; + if (foreach_context->foreach_break == true) return -1; app_matched_cb = foreach_context->callback; if (app_matched_cb != NULL) { bool stop_foreach = false; - stop_foreach = !app_matched_cb(foreach_context->app_control, package, foreach_context->user_data); + stop_foreach = + !app_matched_cb(foreach_context->app_control, package, foreach_context->user_data); foreach_context->foreach_break = stop_foreach; } @@ -708,20 +717,19 @@ int app_control_foreach_app_matched_internal(app_control_h app_control, app_cont return 0; }; - foreach_context_launchable_app_t_internal foreach_context = { - .app_control = app_control, - .callback = callback, - .user_data = user_data, - .foreach_break = false - }; + foreach_context_launchable_app_t_internal foreach_context = {.app_control = app_control, + .callback = callback, + .user_data = user_data, + .foreach_break = false}; - bundle *bundle_data = NULL; + bundle* bundle_data = NULL; app_control_to_bundle(app_control, &bundle_data); - int ret = appsvc_usr_get_list(bundle_data, app_control_cb_broker_foreach_app_matched_internal, &foreach_context, getuid()); + int ret = appsvc_usr_get_list(bundle_data, app_control_cb_broker_foreach_app_matched_internal, + &foreach_context, getuid()); - if (ret < 0 ){ - switch (ret){ + if (ret < 0) { + switch (ret) { case APPSVC_RET_EINVAL: return APP_CONTROL_ERROR_INVALID_PARAMETER; @@ -730,13 +738,12 @@ int app_control_foreach_app_matched_internal(app_control_h app_control, app_cont default: return APP_CONTROL_ERROR_LAUNCH_FAILED; - } + } } return APP_CONTROL_ERROR_NONE; } - void ApplicationManager::FindAppControl(const picojson::value& args) { LoggerD("Entered"); @@ -763,8 +770,8 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { app_control_h app_control = nullptr; result = ApplicationUtils::ApplicationControlToService(app_control_obj, &app_control); - std::shared_ptr::type> - app_control_ptr(app_control, &app_control_destroy); // automatically release the memory + std::shared_ptr::type> app_control_ptr( + app_control, &app_control_destroy); // automatically release the memory if (result.IsError()) { LoggerE("Application control to service failed."); @@ -773,7 +780,8 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { } auto find = [app_control_ptr](const std::shared_ptr& response) -> void { - auto app_control_matched = [](app_control_h app_control, const char* appid, void* user_data) -> bool { + auto app_control_matched = [](app_control_h app_control, const char* appid, + void* user_data) -> bool { if (nullptr == appid) { LoggerD("appid is NULL"); return false; @@ -787,7 +795,8 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { picojson::array* array = static_cast(user_data); array->push_back(picojson::value(picojson::object())); - ApplicationUtils::CreateApplicationInformation(handle, &array->back().get()); + ApplicationUtils::CreateApplicationInformation(handle, + &array->back().get()); pkgmgrinfo_appinfo_destroy_appinfo(handle); } @@ -797,22 +806,25 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { picojson::object& response_obj = response->get(); auto it_result = response_obj.find("result"); picojson::object& result_obj = it_result->second.get(); - auto array = result_obj.insert( - std::make_pair("informationArray", picojson::value(picojson::array()))); + auto array = + result_obj.insert(std::make_pair("informationArray", picojson::value(picojson::array()))); - int ret = app_control_foreach_app_matched_internal( - app_control_ptr.get(), app_control_matched, &array.first->second.get()); + int ret = app_control_foreach_app_matched_internal(app_control_ptr.get(), app_control_matched, + &array.first->second.get()); if (APP_CONTROL_ERROR_NONE != ret) { - if(APP_CONTROL_ERROR_APP_NOT_FOUND == ret){ - LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR,"Matched Application not found"), &response_obj, - ("app_control_foreach_app_matched error: %d (%s)", ret, get_error_message(ret))); - }else if(APP_CONTROL_ERROR_LAUNCH_FAILED == ret){ - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR,"Unknown error"), &response_obj, - ("app_control_foreach_app_matched error: %d (%s)", ret, get_error_message(ret))); - }else if(APP_CONTROL_ERROR_INVALID_PARAMETER == ret){ - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR,"Invalid parameter passed"), &response_obj, - ("app_control_foreach_app_matched error: %d (%s)", ret, get_error_message(ret))); + if (APP_CONTROL_ERROR_APP_NOT_FOUND == ret) { + LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Matched Application not found"), + &response_obj, ("app_control_foreach_app_matched error: %d (%s)", ret, + get_error_message(ret))); + } else if (APP_CONTROL_ERROR_LAUNCH_FAILED == ret) { + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &response_obj, + ("app_control_foreach_app_matched error: %d (%s)", ret, get_error_message(ret))); + } else if (APP_CONTROL_ERROR_INVALID_PARAMETER == ret) { + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed"), + &response_obj, ("app_control_foreach_app_matched error: %d (%s)", ret, + get_error_message(ret))); } // remove copied ApplicationControl from result response_obj.erase(it_result); @@ -828,7 +840,8 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { // prepare result object, we need to do that here, as input parameter is passed to result callback auto ret = response_obj.insert(std::make_pair("result", picojson::value(picojson::object()))); // reinsert application control - ret.first->second.get().insert(std::make_pair("appControl", args.get("appControl"))); + ret.first->second.get().insert( + std::make_pair("appControl", args.get("appControl"))); TaskQueue::GetInstance().Queue(find, find_response, response); } @@ -847,8 +860,8 @@ void ApplicationManager::GetAppsContext(const picojson::value& args) { picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); picojson::array& array = - result_obj.insert(std::make_pair("contexts", picojson::value( - picojson::array()))).first->second.get(); + result_obj.insert(std::make_pair("contexts", picojson::value(picojson::array()))) + .first->second.get(); auto app_context_cb = [](app_context_h app_context, void* user_data) -> bool { if (nullptr == user_data) { @@ -858,8 +871,8 @@ void ApplicationManager::GetAppsContext(const picojson::value& args) { picojson::array* array = static_cast(user_data); array->push_back(picojson::value(picojson::object())); - if (!ApplicationUtils::CreateApplicationContext( - app_context, &array->back().get())) { + if (!ApplicationUtils::CreateApplicationContext(app_context, + &array->back().get())) { array->pop_back(); return false; } @@ -870,15 +883,16 @@ void ApplicationManager::GetAppsContext(const picojson::value& args) { int ret = app_manager_foreach_app_context(app_context_cb, &array); if (APP_MANAGER_ERROR_NONE != ret) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), &response_obj, - ("app_manager_foreach_app_context error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), &response_obj, + ("app_manager_foreach_app_context error: %d (%s)", ret, get_error_message(ret))); } else { ReportSuccess(result, response_obj); } }; - auto get_apps_context_response = [this, callback_id]( - const std::shared_ptr& response) -> void { + auto get_apps_context_response = + [this, callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -886,10 +900,8 @@ void ApplicationManager::GetAppsContext(const picojson::value& args) { auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_apps_context, - get_apps_context_response, - data); + TaskQueue::GetInstance().Queue(get_apps_context, get_apps_context_response, + data); } void ApplicationManager::GetAppContext(const picojson::value& args, picojson::object* out) { @@ -900,8 +912,9 @@ void ApplicationManager::GetAppContext(const picojson::value& args, picojson::ob if (context_id.is()) { try { pid = std::stoi(context_id.get()); - } catch(...) { - LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Failed to convert context id."), out); + } catch (...) { + LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Failed to convert context id."), + out); return; } } else { @@ -912,23 +925,24 @@ void ApplicationManager::GetAppContext(const picojson::value& args, picojson::ob int ret = app_manager_get_app_id(pid, &app_id); // automatically release the memory - std::unique_ptr app_id_ptr(app_id, &std::free); + std::unique_ptr app_id_ptr(app_id, &std::free); if (APP_MANAGER_ERROR_NONE != ret || nullptr == app_id) { - switch(ret) { + switch (ret) { case APP_MANAGER_ERROR_NO_SUCH_APP: LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "No such application exist."), out, - ("app_manager_get_app_id returned: APP_MANAGER_ERROR_NO_SUCH_APP")); + ("app_manager_get_app_id returned: APP_MANAGER_ERROR_NO_SUCH_APP")); return; case APP_MANAGER_ERROR_INVALID_PARAMETER: LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Application not found."), out, - ("app_manager_get_app_id returned: APP_MANAGER_ERROR_INVALID_PARAMETER")); + ("app_manager_get_app_id returned: APP_MANAGER_ERROR_INVALID_PARAMETER")); return; default: - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), out, - ("app_manager_get_app_id returned: %d (%s)", ret, get_error_message(ret))); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error."), out, + ("app_manager_get_app_id returned: %d (%s)", ret, get_error_message(ret))); return; } } @@ -953,8 +967,8 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); picojson::array& array = - result_obj.insert(std::make_pair("informationArray", picojson::value( - picojson::array()))).first->second.get(); + result_obj.insert(std::make_pair("informationArray", picojson::value(picojson::array()))) + .first->second.get(); auto app_info_cb = [](pkgmgrinfo_appinfo_h handle, void* user_data) -> int { if (nullptr == user_data) { @@ -964,7 +978,8 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { picojson::array* array = static_cast(user_data); array->push_back(picojson::value(picojson::object())); - ApplicationUtils::CreateApplicationInformation(handle, &array->back().get()); + ApplicationUtils::CreateApplicationInformation(handle, + &array->back().get()); return 0; }; @@ -979,8 +994,8 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { } }; - auto get_apps_info_response = [this, callback_id]( - const std::shared_ptr& response) -> void { + auto get_apps_info_response = + [this, callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -988,10 +1003,7 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_apps_info, - get_apps_info_response, - data); + TaskQueue::GetInstance().Queue(get_apps_info, get_apps_info_response, data); } void ApplicationManager::GetAppInfo(const std::string& app_id, picojson::object* out) { @@ -1043,7 +1055,7 @@ void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object package_id = GetPackageId(app_id); // automatically release the memory - std::unique_ptr package_id_ptr(package_id, &std::free); + std::unique_ptr package_id_ptr(package_id, &std::free); if (!package_id) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Failed to get package."), out); @@ -1053,20 +1065,20 @@ void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object package_info_h pkg_info = nullptr; int ret = package_info_create(package_id, &pkg_info); - std::unique_ptr::type, int(*)(package_info_h)> - pkg_info_ptr(pkg_info, &package_info_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(package_info_h)> pkg_info_ptr( + pkg_info, &package_info_destroy); // automatically release the memory if (PACKAGE_MANAGER_ERROR_NONE != ret) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get package info."), out, - ("Failed to get package info: %d (%s)", ret, get_error_message(ret))); + ("Failed to get package info: %d (%s)", ret, get_error_message(ret))); return; } auto cert_info_cb = [](package_info_h handle, package_cert_type_e cert_type, - const char* cert_value, void* user_data) -> bool { + const char* cert_value, void* user_data) -> bool { const char* cert_name = nullptr; - switch(cert_type) { + switch (cert_type) { case PACKAGE_INFO_AUTHOR_ROOT_CERT: cert_name = "AUTHOR_ROOT"; break; @@ -1102,8 +1114,8 @@ void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object picojson::array* array = static_cast(user_data); array->push_back(picojson::value(picojson::object())); - ApplicationUtils::CreateApplicationCertificate( - cert_name, cert_value, &array->back().get()); + ApplicationUtils::CreateApplicationCertificate(cert_name, cert_value, + &array->back().get()); return true; }; @@ -1113,8 +1125,9 @@ void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object ret = package_info_foreach_cert_info(pkg_info, cert_info_cb, &result.get()); if ((PACKAGE_MANAGER_ERROR_NONE != ret) && (PACKAGE_MANAGER_ERROR_IO_ERROR != ret)) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get certificates info."), out, - ("Failed to get certificates info: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get certificates info."), + out, + ("Failed to get certificates info: %d (%s)", ret, get_error_message(ret))); return; } @@ -1128,7 +1141,7 @@ void ApplicationManager::GetAppSharedUri(const std::string& app_id, picojson::ob package_id = GetPackageId(app_id); // automatically release the memory - std::unique_ptr package_id_ptr(package_id, &std::free); + std::unique_ptr package_id_ptr(package_id, &std::free); if (!package_id) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Failed to get package."), out); @@ -1138,12 +1151,13 @@ void ApplicationManager::GetAppSharedUri(const std::string& app_id, picojson::ob pkgmgrinfo_pkginfo_h pkg_info = nullptr; int ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(package_id, getuid(), &pkg_info); - std::unique_ptr::type, int(*)(pkgmgrinfo_pkginfo_h)> - pkg_info_ptr(pkg_info, &pkgmgrinfo_pkginfo_destroy_pkginfo); // automatically release the memory + std::unique_ptr::type, int (*)(pkgmgrinfo_pkginfo_h)> + pkg_info_ptr(pkg_info, + &pkgmgrinfo_pkginfo_destroy_pkginfo); // automatically release the memory if (PMINFO_R_OK != ret) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get package info."), out, - ("Failed to get package info: %d (%s)", ret, get_error_message(ret))); + ("Failed to get package info: %d (%s)", ret, get_error_message(ret))); return; } @@ -1152,20 +1166,18 @@ void ApplicationManager::GetAppSharedUri(const std::string& app_id, picojson::ob if (PMINFO_R_OK != ret || nullptr == root_path) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get root path."), out, - ("Failed to get root path: %d (%s)", ret, get_error_message(ret))); + ("Failed to get root path: %d (%s)", ret, get_error_message(ret))); return; } - picojson::value result = picojson::value(kTizenApisFileScheme + - root_path + - kTizenApisAppSlash + - kTizenApisAppShared + - kTizenApisAppSlash); + picojson::value result = picojson::value(kTizenApisFileScheme + root_path + kTizenApisAppSlash + + kTizenApisAppShared + kTizenApisAppSlash); ReportSuccess(result, *out); } #ifdef TIZEN_MOBILE -PlatformResult ApplicationManager::BatteryUsageFilter(const picojson::value& args, const context_history_filter_h filter, +PlatformResult ApplicationManager::BatteryUsageFilter(const picojson::value& args, + const context_history_filter_h filter, context_history_data_e* data_type_out) { LoggerD("Entered"); int ret = CONTEXT_HISTORY_ERROR_NONE; @@ -1201,7 +1213,8 @@ PlatformResult ApplicationManager::BatteryUsageFilter(const picojson::value& arg return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ApplicationManager::BatteryUsageAttributes(const context_history_record_h record, picojson::object* object) { +PlatformResult ApplicationManager::BatteryUsageAttributes(const context_history_record_h record, + picojson::object* object) { LoggerD("Entered"); int ret = CONTEXT_HISTORY_ERROR_NONE; @@ -1214,13 +1227,13 @@ PlatformResult ApplicationManager::BatteryUsageAttributes(const context_history_ ret = context_history_record_get_string(record, CONTEXT_HISTORY_APP_ID, &app_id); if (CONTEXT_HISTORY_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to get string.", - ("Failed to get string: %d (%s)", ret, get_error_message(ret))); + ("Failed to get string: %d (%s)", ret, get_error_message(ret))); } ret = context_history_record_get_double(record, CONTEXT_HISTORY_TOTAL_AMOUNT, &amount); if (CONTEXT_HISTORY_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to get amount.", - ("Failed to get amount: %d (%s)", ret, get_error_message(ret))); + ("Failed to get amount: %d (%s)", ret, get_error_message(ret))); } object->insert(std::make_pair("appId", picojson::value(app_id))); @@ -1252,23 +1265,24 @@ PlatformResult ApplicationManager::AppsUsageFilter(const picojson::value& args, } int time_span = kDefaultPeriodOfTime; - const picojson::object &JS_filter = args.get("filter").get(); + const picojson::object& JS_filter = args.get("filter").get(); auto time_span_iter = JS_filter.find("timeSpan"); - if (JS_filter.end() != time_span_iter - || (JS_filter.end() == JS_filter.find("startTime") - && JS_filter.end() == JS_filter.find("endTime"))) { - //In the second case, we treat the filter object just like an empty object. - //The default value of filter will be used instead. + if (JS_filter.end() != time_span_iter || (JS_filter.end() == JS_filter.find("startTime") && + JS_filter.end() == JS_filter.find("endTime"))) { + // In the second case, we treat the filter object just like an empty object. + // The default value of filter will be used instead. if (JS_filter.end() != time_span_iter) { time_span = static_cast(time_span_iter->second.get()); } ret = context_history_filter_set_int(filter, CONTEXT_HISTORY_FILTER_TIME_SPAN, time_span); - //context_history_filter_set_int may return only success or CONTEXT_HISTORY_ERROR_INVALID_PARAMETER - //Although this should never happen, it's better to check ret's value + // context_history_filter_set_int may return only success or + // CONTEXT_HISTORY_ERROR_INVALID_PARAMETER + // Although this should never happen, it's better to check ret's value if (CONTEXT_HISTORY_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::ABORT_ERR, "Error while setting the default TIME_SPAN value.", - ("Error while setting the default TIME_SPAN value: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::ABORT_ERR, + "Error while setting the default TIME_SPAN value.", + ("Error while setting the default TIME_SPAN value: %d (%s)", ret, + get_error_message(ret))); } } else { auto start_time_iter = JS_filter.find("startTime"); @@ -1356,18 +1370,18 @@ void ApplicationManager::GetBatteryUsageInfo(const picojson::value& args, picojs callback_id = static_cast(callback.get()); } - auto get_battery_usage = [args](const std::shared_ptr& response)-> void { + auto get_battery_usage = [args](const std::shared_ptr& response) -> void { LoggerD("Entered"); - PlatformResult result = ApplicationManager::GetContextHistory(args, &response.get()->get(), - &ApplicationManager::BatteryUsageFilter, - &ApplicationManager::BatteryUsageAttributes); + PlatformResult result = ApplicationManager::GetContextHistory( + args, &response.get()->get(), &ApplicationManager::BatteryUsageFilter, + &ApplicationManager::BatteryUsageAttributes); if (!result) { LogAndReportError(result, &response.get()->get()); } }; - auto get_battery_usage_response = [this, callback_id]( - const std::shared_ptr& response) -> void { + auto get_battery_usage_response = + [this, callback_id](const std::shared_ptr& response) -> void { LoggerD("Entered"); picojson::object& obj = response->get(); obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); @@ -1376,14 +1390,14 @@ void ApplicationManager::GetBatteryUsageInfo(const picojson::value& args, picojs auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_battery_usage, - get_battery_usage_response, - data); + TaskQueue::GetInstance().Queue(get_battery_usage, get_battery_usage_response, + data); #else - // 20170510 Context API is supported only for mobile profile, other ones would result with NotSupportedError - LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, "This feature is not supported on this profile."), out, - ("NOT_SUPPORTED_ERR: This feature is not supported on this profile")); + // 20170510 Context API is supported only for mobile profile, other ones would result with + // NotSupportedError + LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, + "This feature is not supported on this profile."), + out, ("NOT_SUPPORTED_ERR: This feature is not supported on this profile")); #endif } @@ -1393,18 +1407,18 @@ void ApplicationManager::GetAppsUsageInfo(const picojson::value& args, picojson: #ifdef TIZEN_MOBILE int callback_id = static_cast(args.get(kCallbackId).get()); - auto get_apps_usage = [args](const std::shared_ptr& response)-> void { + auto get_apps_usage = [args](const std::shared_ptr& response) -> void { LoggerD("Entered"); - PlatformResult result = ApplicationManager::GetContextHistory(args, &response.get()->get(), - &ApplicationManager::AppsUsageFilter, - &ApplicationManager::AppsUsageAttributes); + PlatformResult result = ApplicationManager::GetContextHistory( + args, &response.get()->get(), &ApplicationManager::AppsUsageFilter, + &ApplicationManager::AppsUsageAttributes); if (!result) { LogAndReportError(result, &response.get()->get()); } }; - auto get_apps_usage_response = [this, callback_id]( - const std::shared_ptr& response) -> void { + auto get_apps_usage_response = + [this, callback_id](const std::shared_ptr& response) -> void { LoggerD("Entered"); picojson::object& obj = response->get(); obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); @@ -1413,14 +1427,13 @@ void ApplicationManager::GetAppsUsageInfo(const picojson::value& args, picojson: auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_apps_usage, - get_apps_usage_response, - data); + TaskQueue::GetInstance().Queue(get_apps_usage, get_apps_usage_response, data); #else - // Context API is supported only for mobile profile, other ones would result with NotSupportedError - LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, "This feature is not supported on this profile."), out, - ("NOT_SUPPORTED_ERR: This feature is not supported on this profile")); + // Context API is supported only for mobile profile, other ones would result with + // NotSupportedError + LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, + "This feature is not supported on this profile."), + out, ("NOT_SUPPORTED_ERR: This feature is not supported on this profile")); #endif } @@ -1430,12 +1443,13 @@ void ApplicationManager::GetAppMetaData(const std::string& app_id, picojson::obj pkgmgrinfo_appinfo_h handle = nullptr; int ret = pkgmgrinfo_appinfo_get_usr_appinfo(app_id.c_str(), getuid(), &handle); - std::unique_ptr::type, int(*)(pkgmgrinfo_appinfo_h)> - pkg_info_ptr(handle, &pkgmgrinfo_appinfo_destroy_appinfo); // automatically release the memory + std::unique_ptr::type, int (*)(pkgmgrinfo_appinfo_h)> + pkg_info_ptr(handle, + &pkgmgrinfo_appinfo_destroy_appinfo); // automatically release the memory if (PMINFO_R_OK != ret) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Failed to get app info."), out, - ("Failed to get app info: %d (%s)", ret, get_error_message(ret))); + ("Failed to get app info: %d (%s)", ret, get_error_message(ret))); return; } @@ -1467,18 +1481,17 @@ void ApplicationManager::GetAppMetaData(const std::string& app_id, picojson::obj class ApplicationListChangedBroker { public: - ApplicationListChangedBroker() : event_type_() {} + ApplicationListChangedBroker() : event_type_() { + } enum class Event { kInstalled, kUpdated, kUninstalled, }; - static int ClientStatusListener(unsigned int target_uid, int id, - const char* type, const char* package, - const char* key, - const char* val, const void* msg, - void* data) { + static int ClientStatusListener(unsigned int target_uid, int id, const char* type, + const char* package, const char* key, const char* val, + const void* msg, void* data) { LoggerD("Entered"); ApplicationListChangedBroker* that = static_cast(data); @@ -1493,8 +1506,8 @@ class ApplicationListChangedBroker { return 0; } - static int AppUninstallListener(uid_t target_uid, int id, const char* type, const char* package, const char* key, - const char* val, const void* msg, void* data) { + static int AppUninstallListener(uid_t target_uid, int id, const char* type, const char* package, + const char* key, const char* val, const void* msg, void* data) { LoggerD("Entered"); ApplicationListChangedBroker* that = static_cast(data); @@ -1514,18 +1527,19 @@ class ApplicationListChangedBroker { void AddApplicationInstance(ApplicationInstance* app_instance) { LoggerD("Entered"); - app_instance_list_.push_back(app_instance); + app_instance_list_.push_back(app_instance); } void RemoveApplicationInstance(ApplicationInstance* app_instance) { LoggerD("Entered"); for (auto it = app_instance_list_.begin(); it != app_instance_list_.end(); it++) { if (*it == app_instance) { - app_instance_list_.erase(it); - return; + app_instance_list_.erase(it); + return; } } } + private: void HandleStart(const char* event_type, const char* package) { LoggerD("Entered"); @@ -1561,10 +1575,10 @@ class ApplicationListChangedBroker { switch (event_type_) { case Event::kInstalled: - case Event::kUpdated: - { + case Event::kUpdated: { pkgmgrinfo_appinfo_h handle = nullptr; - if (PMINFO_R_OK != pkgmgrinfo_appinfo_get_usr_appinfo(app_id.c_str(), getuid(), &handle)) { + if (PMINFO_R_OK != + pkgmgrinfo_appinfo_get_usr_appinfo(app_id.c_str(), getuid(), &handle)) { LoggerE("Failed to get application information handle."); continue; } @@ -1572,8 +1586,7 @@ class ApplicationListChangedBroker { ApplicationUtils::CreateApplicationInformation( handle, &info.first->second.get()); pkgmgrinfo_appinfo_destroy_appinfo(handle); - } - break; + } break; case Event::kUninstalled: LoggerD("Uninstalled called"); break; @@ -1597,10 +1610,8 @@ class ApplicationListChangedBroker { return; } - ret = package_info_foreach_app_from_package(package_info, - PACKAGE_INFO_ALLAPP, - ApplicationIdCallback, - this); + ret = package_info_foreach_app_from_package(package_info, PACKAGE_INFO_ALLAPP, + ApplicationIdCallback, this); if (PACKAGE_MANAGER_ERROR_NONE != ret) { LoggerE("Failed to get application IDs: %d (%s)", ret, get_error_message(ret)); } @@ -1622,8 +1633,8 @@ class ApplicationListChangedBroker { } } - static bool ApplicationIdCallback(package_info_app_component_type_e comp_type, - const char* app_id, void* user_data) { + static bool ApplicationIdCallback(package_info_app_component_type_e comp_type, const char* app_id, + void* user_data) { LoggerD("Entered"); if (nullptr != app_id) { static_cast(user_data)->app_list_.push_back(app_id); @@ -1672,30 +1683,31 @@ void ApplicationManager::StartAppInfoEventListener(picojson::object* out) { LoggerD("Entered"); if (nullptr == pkgmgr_client_handle_ || nullptr == pkgmgr_client_uninstall_handle_) { - if(nullptr == pkgmgr_client_handle_) { + if (nullptr == pkgmgr_client_handle_) { pkgmgr_client_handle_ = pkgmgr_client_new(PC_LISTENING); } - if(nullptr == pkgmgr_client_uninstall_handle_) { + if (nullptr == pkgmgr_client_uninstall_handle_) { pkgmgr_client_uninstall_handle_ = pkgmgr_client_new(PC_LISTENING); } if (nullptr == pkgmgr_client_handle_ || nullptr == pkgmgr_client_uninstall_handle_) { - if(nullptr != pkgmgr_client_handle_) { + if (nullptr != pkgmgr_client_handle_) { pkgmgr_client_free(pkgmgr_client_handle_); pkgmgr_client_handle_ = nullptr; } - if(nullptr != pkgmgr_client_uninstall_handle_) { + if (nullptr != pkgmgr_client_uninstall_handle_) { pkgmgr_client_free(pkgmgr_client_uninstall_handle_); pkgmgr_client_uninstall_handle_ = nullptr; } - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to register listener."), out); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to register listener."), + out); return; } g_application_list_changed_broker.AddApplicationInstance(&instance_); - pkgmgr_client_set_status_type(pkgmgr_client_handle_, - PACKAGE_MANAGER_STATUS_TYPE_INSTALL | PACKAGE_MANAGER_STATUS_TYPE_UPGRADE); + pkgmgr_client_set_status_type(pkgmgr_client_handle_, PACKAGE_MANAGER_STATUS_TYPE_INSTALL | + PACKAGE_MANAGER_STATUS_TYPE_UPGRADE); pkgmgr_client_set_status_type(pkgmgr_client_uninstall_handle_, PACKAGE_MANAGER_STATUS_TYPE_UNINSTALL); @@ -1717,11 +1729,11 @@ void ApplicationManager::StopAppInfoEventListener() { LoggerD("Entered"); if (nullptr != pkgmgr_client_handle_ || nullptr != pkgmgr_client_uninstall_handle_) { - if(nullptr != pkgmgr_client_handle_) { + if (nullptr != pkgmgr_client_handle_) { pkgmgr_client_free(pkgmgr_client_handle_); pkgmgr_client_handle_ = nullptr; } - if(nullptr != pkgmgr_client_uninstall_handle_) { + if (nullptr != pkgmgr_client_uninstall_handle_) { pkgmgr_client_free(pkgmgr_client_uninstall_handle_); pkgmgr_client_uninstall_handle_ = nullptr; } @@ -1737,7 +1749,8 @@ void ApplicationManager::GetApplicationInformationSize(const picojson::value& ar const auto& package_id = args.get("packageId"); if (!package_id.is()) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + out); return; } @@ -1760,7 +1773,6 @@ void ApplicationManager::GetApplicationInformationSize(const picojson::value& ar pkgmgr_client_free(pc); } - picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); result_obj.insert(std::make_pair("size", picojson::value(static_cast(size)))); @@ -1768,10 +1780,8 @@ void ApplicationManager::GetApplicationInformationSize(const picojson::value& ar ReportSuccess(result, *out); } -void ApplicationManager::BroadcastEventHelper( - const picojson::value& args, - picojson::object& out, bool trusted) { - +void ApplicationManager::BroadcastEventHelper(const picojson::value& args, picojson::object& out, + bool trusted) { LoggerD("Entered"); int ret; @@ -1805,9 +1815,7 @@ void ApplicationManager::BroadcastEventHelper( } } -void ApplicationManager::OnEvent(const char* event_name, - bundle* event_data, - void* user_data) { +void ApplicationManager::OnEvent(const char* event_name, bundle* event_data, void* user_data) { LoggerD("Entered"); LOGGER(DEBUG) << event_name; @@ -1824,7 +1832,7 @@ void ApplicationManager::OnEvent(const char* event_name, int ret; char* val = nullptr; - if (event_map_.count(event_name)) { // system event + if (event_map_.count(event_name)) { // system event const std::string& key = event_map_.at(event_name); std::string state = "true"; if (key != "") { @@ -1840,7 +1848,7 @@ void ApplicationManager::OnEvent(const char* event_name, LoggerD("State is %s", state.c_str()); event_o["value"] = picojson::value(state); - } else { // user event + } else { // user event ret = bundle_get_str(event_data, "data", &val); if (EVENT_ERROR_NONE != ret) { LoggerE("failed to read bundle data, error: %d (%s)", ret, get_error_message(ret)); @@ -1907,10 +1915,10 @@ void ApplicationManager::StopEventListener(const std::string& event_name) { } } -void ApplicationManager::OnStatusEvent(const char *type, const char *app_id, +void ApplicationManager::OnStatusEvent(const char* type, const char* app_id, app_manager_event_type_e event_type, app_manager_event_state_e event_state, - app_manager_event_h handle, void *user_data) { + app_manager_event_h handle, void* user_data) { LoggerD("Entered"); if (APP_MANAGER_EVENT_STATE_COMPLETED != event_state) { @@ -1949,9 +1957,13 @@ void ApplicationManager::OnStatusEvent(const char *type, const char *app_id, } #ifdef TIZEN_MOBILE -PlatformResult ApplicationManager::GetContextHistory(const picojson::value& args, picojson::object* out, - common::PlatformResult (*modify_filter_cb)(const picojson::value&, const context_history_filter_h, context_history_data_e* data_type), - common::PlatformResult (*add_attributes_to_object)(const context_history_record_h, picojson::object*)) { +PlatformResult ApplicationManager::GetContextHistory( + const picojson::value& args, picojson::object* out, + common::PlatformResult (*modify_filter_cb)(const picojson::value&, + const context_history_filter_h, + context_history_data_e* data_type), + common::PlatformResult (*add_attributes_to_object)(const context_history_record_h, + picojson::object*)) { LoggerD("Entered"); context_history_list_h list = nullptr; context_history_h handle = nullptr; @@ -1965,13 +1977,15 @@ PlatformResult ApplicationManager::GetContextHistory(const picojson::value& args int ret = context_history_create(&handle); if (CONTEXT_HISTORY_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to create context handle.", + return LogAndCreateResult( + ErrorCode::ABORT_ERR, "Failed to create context handle.", ("Failed to create context handle: %d (%s)", ret, get_error_message(ret))); } ret = context_history_filter_create(&filter); if (CONTEXT_HISTORY_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to create filter handle.", + return LogAndCreateResult( + ErrorCode::ABORT_ERR, "Failed to create filter handle.", ("Failed to create filter handle: %d (%s)", ret, get_error_message(ret))); } @@ -1991,14 +2005,14 @@ PlatformResult ApplicationManager::GetContextHistory(const picojson::value& args return PlatformResult(ErrorCode::NO_ERROR); } else if (CONTEXT_HISTORY_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to get list.", - ("Failed to get list: %d (%s)", ret, get_error_message(ret))); + ("Failed to get list: %d (%s)", ret, get_error_message(ret))); } int size = 0; ret = context_history_list_get_count(list, &size); if (CONTEXT_HISTORY_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to get list size.", - ("Failed to get list size: %d (%s)", ret, get_error_message(ret))); + ("Failed to get list size: %d (%s)", ret, get_error_message(ret))); } array_obj.resize(size, picojson::value(picojson::object())); @@ -2011,7 +2025,8 @@ PlatformResult ApplicationManager::GetContextHistory(const picojson::value& args ret = context_history_list_get_current(list, &record); if (CONTEXT_HISTORY_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to get current record.", + return LogAndCreateResult( + ErrorCode::ABORT_ERR, "Failed to get current record.", ("Failed to get current record: %d (%s)", ret, get_error_message(ret))); } @@ -2023,7 +2038,7 @@ PlatformResult ApplicationManager::GetContextHistory(const picojson::value& args ret = context_history_list_move_next(list); if (CONTEXT_HISTORY_ERROR_NONE != ret && CONTEXT_HISTORY_ERROR_NO_DATA != ret) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to move iterator.", - ("Failed to move iterator: %d (%s)", ret, get_error_message(ret))); + ("Failed to move iterator: %d (%s)", ret, get_error_message(ret))); } } @@ -2075,5 +2090,5 @@ PlatformResult ApplicationManager::StopStatusChangeListener() { return PlatformResult(ErrorCode::NO_ERROR); } -} // namespace application -} // namespace extension +} // namespace application +} // namespace extension diff --git a/src/application/application_manager.h b/src/application/application_manager.h old mode 100755 new mode 100644 index 164fcb5..6bb4ecc --- a/src/application/application_manager.h +++ b/src/application/application_manager.h @@ -20,12 +20,12 @@ #include #include #include -#include -#include #include -#include #include #include +#include +#include +#include #ifdef TIZEN_MOBILE #include #endif @@ -82,29 +82,34 @@ class ApplicationManager { JsonCallback event_callback_; JsonCallback status_callback_; std::map event_handler_map_; - static void OnEvent(const char* event_name, - bundle* event_data, - void* user_data); - static void OnStatusEvent(const char *type, const char *app_id, + static void OnEvent(const char* event_name, bundle* event_data, void* user_data); + static void OnStatusEvent(const char* type, const char* app_id, app_manager_event_type_e event_type, - app_manager_event_state_e event_state, - app_manager_event_h handle, - void *user_data); + app_manager_event_state_e event_state, app_manager_event_h handle, + void* user_data); #ifdef TIZEN_MOBILE - static common::PlatformResult GetContextHistory(const picojson::value& args, picojson::object* out, - common::PlatformResult (*)(const picojson::value&, const context_history_filter_h, context_history_data_e* data_type), - common::PlatformResult (*)(const context_history_record_h, picojson::object*)); - - static common::PlatformResult BatteryUsageFilter(const picojson::value&, const context_history_filter_h, context_history_data_e* data_type); - static common::PlatformResult BatteryUsageAttributes(const context_history_record_h, picojson::object*); - - static common::PlatformResult AppsUsageFilter(const picojson::value&, const context_history_filter_h, context_history_data_e* data_type); - static common::PlatformResult AppsUsageAttributes(const context_history_record_h, picojson::object*); + static common::PlatformResult GetContextHistory( + const picojson::value& args, picojson::object* out, + common::PlatformResult (*)(const picojson::value&, const context_history_filter_h, + context_history_data_e* data_type), + common::PlatformResult (*)(const context_history_record_h, picojson::object*)); + + static common::PlatformResult BatteryUsageFilter(const picojson::value&, + const context_history_filter_h, + context_history_data_e* data_type); + static common::PlatformResult BatteryUsageAttributes(const context_history_record_h, + picojson::object*); + + static common::PlatformResult AppsUsageFilter(const picojson::value&, + const context_history_filter_h, + context_history_data_e* data_type); + static common::PlatformResult AppsUsageAttributes(const context_history_record_h, + picojson::object*); #endif }; -} // namespace application -} // namespace extension +} // namespace application +} // namespace extension -#endif // SRC_APPLICATION_APPLICATION_MANAGER_H__ +#endif // SRC_APPLICATION_APPLICATION_MANAGER_H__ diff --git a/src/application/application_utils.cc b/src/application/application_utils.cc index 060dd09..a41e697 100644 --- a/src/application/application_utils.cc +++ b/src/application/application_utils.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "application_utils.h" #include @@ -81,15 +81,15 @@ void ApplicationUtils::CreateApplicationInformation(const pkgmgrinfo_appinfo_h h ret = pkgmgrinfo_appinfo_foreach_category( handle, [](const char* category, void* user_data) -> int { - picojson::array* categories_array = static_cast(user_data); + picojson::array* categories_array = static_cast(user_data); - if ((nullptr != category) && (nullptr != categories_array)) { - categories_array->push_back(picojson::value(category)); - } + if ((nullptr != category) && (nullptr != categories_array)) { + categories_array->push_back(picojson::value(category)); + } - return 0; - }, - &categories_array); + return 0; + }, + &categories_array); app_info->insert(std::make_pair("categories", categories)); @@ -140,7 +140,7 @@ bool ApplicationUtils::CreateApplicationContext(const app_context_h handle, int ret = app_context_get_app_id(handle, &app_id); // automatically release the memory - std::unique_ptr app_id_ptr(app_id, &std::free); + std::unique_ptr app_id_ptr(app_id, &std::free); if ((APP_MANAGER_ERROR_NONE != ret) || (nullptr == app_id)) { LoggerD("Failed to get application ID from context: %d (%s)", ret, get_error_message(ret)); @@ -150,7 +150,7 @@ bool ApplicationUtils::CreateApplicationContext(const app_context_h handle, pid_t pid; ret = app_context_get_pid(handle, &pid); - if(ret != APP_MANAGER_ERROR_NONE) { + if (ret != APP_MANAGER_ERROR_NONE) { LoggerD("Failed to get pid from context: %d (%s)", ret, get_error_message(ret)); return false; } @@ -162,34 +162,27 @@ bool ApplicationUtils::CreateApplicationContext(const app_context_h handle, void ApplicationUtils::CreateApplicationContext(pid_t pid, const std::string& app_id, picojson::object* app_context) { - LoggerD("Enter"); app_context->insert(std::make_pair("id", picojson::value(std::to_string(pid)))); app_context->insert(std::make_pair("appId", picojson::value(app_id))); } -void ApplicationUtils::CreateApplicationCertificate(const char* cert_type, - const char* cert_value, +void ApplicationUtils::CreateApplicationCertificate(const char* cert_type, const char* cert_value, picojson::object* app_certificate) { - LoggerD("Enter"); app_certificate->insert(std::make_pair("type", picojson::value(cert_type))); app_certificate->insert(std::make_pair("value", picojson::value(cert_value))); } -void ApplicationUtils::CreateApplicationMetaData(const char* key, - const char* value, +void ApplicationUtils::CreateApplicationMetaData(const char* key, const char* value, picojson::object* app_meta_data) { - LoggerD("Enter"); app_meta_data->insert(std::make_pair("key", picojson::value(key))); app_meta_data->insert(std::make_pair("value", picojson::value(value))); } PlatformResult ApplicationUtils::ApplicationControlToService( - const picojson::object& app_control_obj, - app_control_h* app_control) { - + const picojson::object& app_control_obj, app_control_h* app_control) { LoggerD("Enter"); const auto it_operation = app_control_obj.find("operation"); const auto it_uri = app_control_obj.find("uri"); @@ -198,12 +191,9 @@ PlatformResult ApplicationUtils::ApplicationControlToService( const auto it_data = app_control_obj.find("data"); const auto it_app_control_end = app_control_obj.end(); - if (it_operation == it_app_control_end || - it_uri == it_app_control_end || - it_mime == it_app_control_end || - it_category == it_app_control_end || - it_data == it_app_control_end || - !it_operation->second.is() || + if (it_operation == it_app_control_end || it_uri == it_app_control_end || + it_mime == it_app_control_end || it_category == it_app_control_end || + it_data == it_app_control_end || !it_operation->second.is() || !it_data->second.is()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed."); } @@ -213,10 +203,10 @@ PlatformResult ApplicationUtils::ApplicationControlToService( if (APP_CONTROL_ERROR_NONE != result) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Creation AppControl failed.", - ("Problem with create handle.")); + ("Problem with create handle.")); } - std::unique_ptr::type, int(*)(app_control_h)> app_control_ptr( + std::unique_ptr::type, int (*)(app_control_h)> app_control_ptr( app_control_tmp, &app_control_destroy); // operation @@ -257,19 +247,15 @@ PlatformResult ApplicationUtils::ApplicationControlToService( } PlatformResult ApplicationUtils::ApplicationControlDataToServiceExtraData( - const picojson::object& app_control_data, - app_control_h app_control) { - + const picojson::object& app_control_data, app_control_h app_control) { LoggerD("Enter"); const auto it_key = app_control_data.find("key"); const auto it_value = app_control_data.find("value"); const auto it_app_control_data_end = app_control_data.end(); - if (it_key == it_app_control_data_end || - it_value == it_app_control_data_end || - !it_key->second.is() || - !it_value->second.is()) { + if (it_key == it_app_control_data_end || it_value == it_app_control_data_end || + !it_key->second.is() || !it_value->second.is()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed.", ("Problem with key or value.")); } @@ -345,9 +331,8 @@ void ApplicationUtils::ServiceToApplicationControl(app_control_h app_control, app_control, &app_control_obj->find("data")->second.get()); } -void ApplicationUtils::ServiceExtraDataToApplicationControlData(app_control_h app_control, - const std::string& key, - picojson::object* app_control_data) { +void ApplicationUtils::ServiceExtraDataToApplicationControlData( + app_control_h app_control, const std::string& key, picojson::object* app_control_data) { LoggerD("Enter"); int ret = 0; @@ -403,8 +388,7 @@ bool ApplicationUtils::ServiceToApplicationControlDataArray(app_control_h app_co return APP_CONTROL_ERROR_NONE == ret; } -bool ApplicationUtils::ServiceExtraDataCallback(app_control_h app_control, - const char* key, +bool ApplicationUtils::ServiceExtraDataCallback(app_control_h app_control, const char* key, void* user_data) { picojson::array* data = static_cast(user_data); @@ -414,5 +398,5 @@ bool ApplicationUtils::ServiceExtraDataCallback(app_control_h app_control, return true; } -} // namespace application -} // namespace extension +} // namespace application +} // namespace extension diff --git a/src/application/application_utils.h b/src/application/application_utils.h old mode 100755 new mode 100644 index d66af26..455f197 --- a/src/application/application_utils.h +++ b/src/application/application_utils.h @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef SRC_APPLICATION_APPLICATION_UTILS_H__ #define SRC_APPLICATION_APPLICATION_UTILS_H__ -#include #include #include +#include #include "common/picojson.h" #include "common/platform_result.h" @@ -32,27 +32,22 @@ class ApplicationUtils { static void CreateApplicationInformation(const pkgmgrinfo_appinfo_h handle, picojson::object* app_info); - static bool CreateApplicationContext(const app_context_h handle, - picojson::object* app_context); + static bool CreateApplicationContext(const app_context_h handle, picojson::object* app_context); - static void CreateApplicationContext(pid_t pid, - const std::string& app_id, + static void CreateApplicationContext(pid_t pid, const std::string& app_id, picojson::object* app_context); - static void CreateApplicationCertificate(const char* cert_type, - const char* cert_value, + static void CreateApplicationCertificate(const char* cert_type, const char* cert_value, picojson::object* app_certificate); - static void CreateApplicationMetaData(const char* key, - const char* value, + static void CreateApplicationMetaData(const char* key, const char* value, picojson::object* app_meta_data); static common::PlatformResult ApplicationControlToService(const picojson::object& app_control_obj, app_control_h* app_control); static common::PlatformResult ApplicationControlDataToServiceExtraData( - const picojson::object& app_control_data, - app_control_h app_control); + const picojson::object& app_control_data, app_control_h app_control); static void ServiceToApplicationControl(app_control_h app_control, picojson::object* app_control_obj); @@ -63,13 +58,12 @@ class ApplicationUtils { static bool ServiceToApplicationControlDataArray(app_control_h app_control, picojson::array* data); + private: - static bool ServiceExtraDataCallback(app_control_h app_control, - const char* key, - void* user_data); + static bool ServiceExtraDataCallback(app_control_h app_control, const char* key, void* user_data); }; -} // namespace application -} // namespace extension +} // namespace application +} // namespace extension -#endif // SRC_APPLICATION_APPLICATION_UTILS_H__ +#endif // SRC_APPLICATION_APPLICATION_UTILS_H__ diff --git a/src/application/requested_application_control.cc b/src/application/requested_application_control.cc old mode 100755 new mode 100644 index 04adbc4..1c24f1a --- a/src/application/requested_application_control.cc +++ b/src/application/requested_application_control.cc @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "requested_application_control.h" -#include #include +#include #include #include @@ -38,15 +38,15 @@ PlatformResult RequestedApplicationControl::set_bundle(const std::string& encode if (encoded_bundle != bundle_) { bundle_ = encoded_bundle; - bundle* bundle = bundle_decode((bundle_raw*)(encoded_bundle.c_str()), - encoded_bundle.length()); + bundle* bundle = bundle_decode((bundle_raw*)(encoded_bundle.c_str()), encoded_bundle.length()); app_control_h app_control = nullptr; int ret = app_control_create_event(bundle, &app_control); bundle_free(bundle); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create app_control.", - ("Failed to create app_control: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to create app_control.", + ("Failed to create app_control: %d (%s)", ret, get_error_message(ret))); } set_app_control(app_control); @@ -79,8 +79,8 @@ void RequestedApplicationControl::ToJson(picojson::object* out) { if (app_control_) { out->insert(std::make_pair("callerAppId", picojson::value(caller_app_id_))); - auto appControl = out->insert(std::make_pair( - "appControl", picojson::value(picojson::object()))); + auto appControl = + out->insert(std::make_pair("appControl", picojson::value(picojson::object()))); ApplicationUtils::ServiceToApplicationControl( app_control_.get(), &appControl.first->second.get()); } @@ -91,7 +91,8 @@ void RequestedApplicationControl::ReplyResult(const picojson::value& args, picoj const auto& data_arr = args.get("data"); if (!data_arr.is()) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + out); return; } @@ -102,24 +103,22 @@ void RequestedApplicationControl::ReplyResult(const picojson::value& args, picoj PlatformResult result = set_bundle(encoded_bundle); if (result.IsError()) { - LogAndReportError(result, out, - ("Failed set_bundle()")); + LogAndReportError(result, out, ("Failed set_bundle()")); return; } // create reply app_control_h reply; app_control_create(&reply); - std::unique_ptr::type, int(*)(app_control_h)> - reply_ptr(reply, &app_control_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(app_control_h)> reply_ptr( + reply, &app_control_destroy); // automatically release the memory if (!data.empty()) { for (auto iter = data.begin(); iter != data.end(); ++iter) { result = ApplicationUtils::ApplicationControlDataToServiceExtraData( iter->get(), reply); if (result.IsError()) { - LogAndReportError(result, out, - ("Failed ApplicationControlDataToServiceExtraData()")); + LogAndReportError(result, out, ("Failed ApplicationControlDataToServiceExtraData()")); return; } } @@ -128,11 +127,11 @@ void RequestedApplicationControl::ReplyResult(const picojson::value& args, picoj } // send reply - int ret = app_control_reply_to_launch_request( - reply, app_control_.get(), APP_CONTROL_RESULT_SUCCEEDED); + int ret = + app_control_reply_to_launch_request(reply, app_control_.get(), APP_CONTROL_RESULT_SUCCEEDED); if (APP_CONTROL_ERROR_NONE != ret) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Cannot find caller."), out, - ("Cannot find caller: %d (%s)", ret, get_error_message(ret))); + ("Cannot find caller: %d (%s)", ret, get_error_message(ret))); return; } @@ -154,14 +153,15 @@ void RequestedApplicationControl::ReplyFailure(picojson::object* out) { // create reply app_control_h reply; app_control_create(&reply); - std::unique_ptr::type, int(*)(app_control_h)> - reply_ptr(reply, &app_control_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(app_control_h)> reply_ptr( + reply, &app_control_destroy); // automatically release the memory // send reply - int ret = app_control_reply_to_launch_request(reply, app_control_.get(), APP_CONTROL_RESULT_FAILED); + int ret = + app_control_reply_to_launch_request(reply, app_control_.get(), APP_CONTROL_RESULT_FAILED); if (APP_CONTROL_ERROR_NONE != ret) { LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Cannot find caller."), out, - ("Cannot find caller: %d (%s)", ret, get_error_message(ret))); + ("Cannot find caller: %d (%s)", ret, get_error_message(ret))); return; } diff --git a/src/application/requested_application_control.h b/src/application/requested_application_control.h old mode 100755 new mode 100644 index 859e822..1792488 --- a/src/application/requested_application_control.h +++ b/src/application/requested_application_control.h @@ -13,19 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef SRC_APPLICATION_REQUESTED_APPLICATION_CONTROL_H_ #define SRC_APPLICATION_REQUESTED_APPLICATION_CONTROL_H_ -#include #include +#include #include #include -#include "common/picojson.h" #include "common/extension.h" +#include "common/picojson.h" #include "common/platform_result.h" #include "tizen/tizen.h" diff --git a/src/archive/archive_callback_data.cc b/src/archive/archive_callback_data.cc old mode 100755 new mode 100644 index 65ecfc9..450d9c0 --- a/src/archive/archive_callback_data.cc +++ b/src/archive/archive_callback_data.cc @@ -21,12 +21,12 @@ #include "common/tools.h" #include "archive_file.h" +#include "archive_instance.h" +#include "archive_manager.h" #include "archive_utils.h" +#include "defs.h" #include "un_zip.h" #include "zip.h" -#include "archive_manager.h" -#include "defs.h" -#include "archive_instance.h" namespace extension { namespace archive { @@ -34,94 +34,82 @@ namespace archive { using common::tools::ReportSuccess; //---------------------------------------------------------------------------------------- -//OperationCallbackData +// OperationCallbackData //---------------------------------------------------------------------------------------- -OperationCallbackData::OperationCallbackData(ArchiveCallbackType callback_type, ArchiveInstance& instance) : - m_callback_type(callback_type), - m_op_id(-1), - m_cid(-1), - m_handle(-1), - instance_(instance), - m_is_error(false), - m_is_canceled(false), - m_err_code(ErrorCode::NO_ERROR) -{ - LoggerD("Entered"); -} - -OperationCallbackData::~OperationCallbackData() -{ - LoggerD("Entered"); - if(m_op_id > -1){ - ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); - } +OperationCallbackData::OperationCallbackData(ArchiveCallbackType callback_type, + ArchiveInstance& instance) + : m_callback_type(callback_type), + m_op_id(-1), + m_cid(-1), + m_handle(-1), + instance_(instance), + m_is_error(false), + m_is_canceled(false), + m_err_code(ErrorCode::NO_ERROR) { + LoggerD("Entered"); } -void OperationCallbackData::setError(const ErrorCode &err_code, - const std::string &err_message) -{ - LoggerD("Entered"); - //store only first error - if (!m_is_error) { - m_err_code = err_code; - m_err_message = err_message; - m_is_error = true; - } +OperationCallbackData::~OperationCallbackData() { + LoggerD("Entered"); + if (m_op_id > -1) { + ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); + } } -bool OperationCallbackData::isError() const -{ - LoggerD("Entered"); - return m_is_error; +void OperationCallbackData::setError(const ErrorCode& err_code, const std::string& err_message) { + LoggerD("Entered"); + // store only first error + if (!m_is_error) { + m_err_code = err_code; + m_err_message = err_message; + m_is_error = true; + } } -bool OperationCallbackData::isCanceled() const -{ - LoggerD("Enter"); - return m_is_canceled; +bool OperationCallbackData::isError() const { + LoggerD("Entered"); + return m_is_error; } -void OperationCallbackData::setOperationId(long op_id) -{ - LoggerD("Entered"); - m_op_id = op_id; +bool OperationCallbackData::isCanceled() const { + LoggerD("Enter"); + return m_is_canceled; } -long OperationCallbackData::getOperationId() const -{ - LoggerD("Entered"); - return m_op_id; +void OperationCallbackData::setOperationId(long op_id) { + LoggerD("Entered"); + m_op_id = op_id; } -void OperationCallbackData::setCallbackId(double cid) -{ - LoggerD("Enter"); - m_cid = cid; +long OperationCallbackData::getOperationId() const { + LoggerD("Entered"); + return m_op_id; } -double OperationCallbackData::getCallbackId() const -{ - LoggerD("Enter"); - return m_cid; +void OperationCallbackData::setCallbackId(double cid) { + LoggerD("Enter"); + m_cid = cid; } -void OperationCallbackData::setHandle(long handle) -{ - LoggerD("Enter"); - m_handle = handle; +double OperationCallbackData::getCallbackId() const { + LoggerD("Enter"); + return m_cid; } -long OperationCallbackData::getHandle() const -{ - LoggerD("Enter"); - return m_handle; +void OperationCallbackData::setHandle(long handle) { + LoggerD("Enter"); + m_handle = handle; } -void OperationCallbackData::setIsCanceled(bool canceled) -{ - LoggerD("Enter"); - m_is_canceled = canceled; +long OperationCallbackData::getHandle() const { + LoggerD("Enter"); + return m_handle; +} + +void OperationCallbackData::setIsCanceled(bool canceled) { + LoggerD("Enter"); + m_is_canceled = canceled; } void OperationCallbackData::PostMessage(const char* msg) { @@ -129,690 +117,607 @@ void OperationCallbackData::PostMessage(const char* msg) { Instance::PostMessage(&instance_, msg); } -const ErrorCode& OperationCallbackData::getErrorCode() const -{ - LoggerD("Entered"); - return m_err_code; +const ErrorCode& OperationCallbackData::getErrorCode() const { + LoggerD("Entered"); + return m_err_code; } -const std::string& OperationCallbackData::getErrorMessage() const -{ - LoggerD("Entered"); - return m_err_message; +const std::string& OperationCallbackData::getErrorMessage() const { + LoggerD("Entered"); + return m_err_message; } -ArchiveCallbackType OperationCallbackData::getCallbackType() const -{ - LoggerD("Entered"); - return m_callback_type; +ArchiveCallbackType OperationCallbackData::getCallbackType() const { + LoggerD("Entered"); + return m_callback_type; } -ArchiveFilePtr OperationCallbackData::getArchiveFile() const -{ - LoggerD("Enter"); - return m_caller_instance; +ArchiveFilePtr OperationCallbackData::getArchiveFile() const { + LoggerD("Enter"); + return m_caller_instance; } -void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) -{ - LoggerD("Enter"); - m_caller_instance = caller; +void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) { + LoggerD("Enter"); + m_caller_instance = caller; } //---------------------------------------------------------------------------------------- -//OpenCallbackData +// OpenCallbackData //---------------------------------------------------------------------------------------- -OpenCallbackData::OpenCallbackData(ArchiveInstance& instance): - OperationCallbackData(OPEN_CALLBACK_DATA, instance) -{ - LoggerD("Entered"); -} - -OpenCallbackData::~OpenCallbackData() -{ - LoggerD("Entered"); -} - -PlatformResult OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerE("Entered"); - - filesystem::FilePtr file = archive_file_ptr->getFile(); - if (!file) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null"); - } - filesystem::NodePtr node = file->getNode(); - if(!node) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node is null"); +OpenCallbackData::OpenCallbackData(ArchiveInstance& instance) + : OperationCallbackData(OPEN_CALLBACK_DATA, instance) { + LoggerD("Entered"); +} + +OpenCallbackData::~OpenCallbackData() { + LoggerD("Entered"); +} + +PlatformResult OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerE("Entered"); + + filesystem::FilePtr file = archive_file_ptr->getFile(); + if (!file) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null"); + } + filesystem::NodePtr node = file->getNode(); + if (!node) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node is null"); + } + const FileMode fm = archive_file_ptr->m_file_mode; + unsigned long long size = 0; + PlatformResult result = node->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail node->getSize()"); + return result; + } + if (0 == size) { + if (FileMode::READ_WRITE == fm || FileMode::WRITE == fm || FileMode::ADD == fm) { + LoggerD("Empty file obtained for writing/appending"); + + // Do not create empty archive with minizip library - it will not be loaded + // by unzip. + // + // For explanation please see: + // ArchiveFile.h m_created_as_new_empty_archive description + // + archive_file_ptr->setCreatedAsNewEmptyArchive(true); + archive_file_ptr->setEntryMap(ArchiveFileEntryPtrMapPtr(new ArchiveFileEntryPtrMap())); + archive_file_ptr->setIsOpen(true); + } else { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid ZIP archive", + ("The file is empty")); } - const FileMode fm = archive_file_ptr->m_file_mode; - unsigned long long size = 0; - PlatformResult result = node->getSize(&size); + } else { + archive_file_ptr->setIsOpen(true); + result = archive_file_ptr->updateListOfEntries(); if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail node->getSize()"); - return result; - } - if (0 == size) { - if(FileMode::READ_WRITE == fm || - FileMode::WRITE == fm || - FileMode::ADD == fm) { - LoggerD("Empty file obtained for writing/appending"); - - // Do not create empty archive with minizip library - it will not be loaded - // by unzip. - // - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - archive_file_ptr->setCreatedAsNewEmptyArchive(true); - archive_file_ptr->setEntryMap(ArchiveFileEntryPtrMapPtr( - new ArchiveFileEntryPtrMap())); - archive_file_ptr->setIsOpen(true); - } - else { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid ZIP archive", ("The file is empty")); - } - } - else { - archive_file_ptr->setIsOpen(true); - result = archive_file_ptr->updateListOfEntries(); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail archive_file_ptr->updateListOfEntries()"); - return result; - } + LoggerE("Fail archive_file_ptr->updateListOfEntries()"); + return result; } + } - guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); - if (!id) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); - } - return PlatformResult(ErrorCode::NO_ERROR); + guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); + if (!id) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); + } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- -//GetEntriesCallbackData +// GetEntriesCallbackData //---------------------------------------------------------------------------------------- -GetEntriesCallbackData::GetEntriesCallbackData(ArchiveInstance& instance): - OperationCallbackData(GET_ENTRIES_CALLBACK_DATA, instance) -{ - LoggerD("Entered"); +GetEntriesCallbackData::GetEntriesCallbackData(ArchiveInstance& instance) + : OperationCallbackData(GET_ENTRIES_CALLBACK_DATA, instance) { + LoggerD("Entered"); } -GetEntriesCallbackData::~GetEntriesCallbackData() -{ - LoggerD("Entered"); +GetEntriesCallbackData::~GetEntriesCallbackData() { + LoggerD("Entered"); } -ArchiveFileEntryPtrMapPtr GetEntriesCallbackData::getEntries() const -{ - LoggerD("Entered"); - return m_entries; +ArchiveFileEntryPtrMapPtr GetEntriesCallbackData::getEntries() const { + LoggerD("Entered"); + return m_entries; } -void GetEntriesCallbackData::setEntries(ArchiveFileEntryPtrMapPtr entries) -{ - LoggerD("Entered"); - m_entries = entries; +void GetEntriesCallbackData::setEntries(ArchiveFileEntryPtrMapPtr entries) { + LoggerD("Entered"); + m_entries = entries; } -PlatformResult GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); +PlatformResult GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); - setEntries(archive_file_ptr->getEntryMap()); + setEntries(archive_file_ptr->getEntryMap()); - guint id = g_idle_add(ArchiveFile::getEntriesTaskCompleteCB, this); - if (!id) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); - } - return PlatformResult(ErrorCode::NO_ERROR); + guint id = g_idle_add(ArchiveFile::getEntriesTaskCompleteCB, this); + if (!id) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); + } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- -//GetEntryByNameCallbackData +// GetEntryByNameCallbackData //---------------------------------------------------------------------------------------- -GetEntryByNameCallbackData::GetEntryByNameCallbackData(ArchiveInstance& instance): - OperationCallbackData(GET_ENTRY_BY_NAME_CALLBACK_DATA, instance) -{ - LoggerD("Entered"); +GetEntryByNameCallbackData::GetEntryByNameCallbackData(ArchiveInstance& instance) + : OperationCallbackData(GET_ENTRY_BY_NAME_CALLBACK_DATA, instance) { + LoggerD("Entered"); } -GetEntryByNameCallbackData::~GetEntryByNameCallbackData() -{ - LoggerD("Entered"); +GetEntryByNameCallbackData::~GetEntryByNameCallbackData() { + LoggerD("Entered"); } -const std::string& GetEntryByNameCallbackData::getName() const -{ - LoggerD("Entered"); - return m_name; +const std::string& GetEntryByNameCallbackData::getName() const { + LoggerD("Entered"); + return m_name; } -void GetEntryByNameCallbackData::setName(const std::string& name) -{ - LoggerD("Entered"); - m_name = name; +void GetEntryByNameCallbackData::setName(const std::string& name) { + LoggerD("Entered"); + m_name = name; } -ArchiveFileEntryPtr GetEntryByNameCallbackData::getFileEntry() const -{ - LoggerD("Entered"); - return m_file_entry; +ArchiveFileEntryPtr GetEntryByNameCallbackData::getFileEntry() const { + LoggerD("Entered"); + return m_file_entry; } -void GetEntryByNameCallbackData::setFileEntry(ArchiveFileEntryPtr entry) -{ - LoggerD("Entered"); - m_file_entry = entry; +void GetEntryByNameCallbackData::setFileEntry(ArchiveFileEntryPtr entry) { + LoggerD("Entered"); + m_file_entry = entry; } -PlatformResult GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); +PlatformResult GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); - ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); - auto it = entries->find(getName()); + ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); + auto it = entries->find(getName()); - //Not found but if our name does not contain '/' - //try looking for directory with such name - // - if (it == entries->end() && !isDirectoryPath(getName())) { - const std::string try_directory = getName() + "/"; - LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); - it = entries->find(try_directory); - } + // Not found but if our name does not contain '/' + // try looking for directory with such name + // + if (it == entries->end() && !isDirectoryPath(getName())) { + const std::string try_directory = getName() + "/"; + LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); + it = entries->find(try_directory); + } - if (it == entries->end()) { - SLoggerE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); - } + if (it == entries->end()) { + SLoggerE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); + } - setFileEntry(it->second); + setFileEntry(it->second); - guint id = g_idle_add(ArchiveFile::getEntryByNameTaskCompleteCB, this); - if (!id) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); - } - return PlatformResult(ErrorCode::NO_ERROR); + guint id = g_idle_add(ArchiveFile::getEntryByNameTaskCompleteCB, this); + if (!id) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); + } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- -//BaseProgressCallback +// BaseProgressCallback //---------------------------------------------------------------------------------------- -BaseProgressCallback::BaseProgressCallback(ArchiveCallbackType callback_type, ArchiveInstance& instance): - OperationCallbackData(callback_type, instance), - m_overwrite(false) -{ - LoggerD("Entered"); +BaseProgressCallback::BaseProgressCallback(ArchiveCallbackType callback_type, + ArchiveInstance& instance) + : OperationCallbackData(callback_type, instance), m_overwrite(false) { + LoggerD("Entered"); } -BaseProgressCallback::~BaseProgressCallback() -{ - LoggerD("Entered"); +BaseProgressCallback::~BaseProgressCallback() { + LoggerD("Entered"); } -bool BaseProgressCallback::getOverwrite() const -{ - LoggerD("Entered"); - return m_overwrite; +bool BaseProgressCallback::getOverwrite() const { + LoggerD("Entered"); + return m_overwrite; } -void BaseProgressCallback::setOverwrite(bool overwrite) -{ - LoggerD("Entered"); - m_overwrite = overwrite; +void BaseProgressCallback::setOverwrite(bool overwrite) { + LoggerD("Entered"); + m_overwrite = overwrite; } -struct ProgressHolder -{ - ProgressHolder() : - overall_progress(0.0), - callback(NULL) - { - }; +struct ProgressHolder { + ProgressHolder() : overall_progress(0.0), callback(NULL){}; - double overall_progress; - ArchiveFileEntryPtr currently_processed_entry; - BaseProgressCallback* callback; + double overall_progress; + ArchiveFileEntryPtr currently_processed_entry; + BaseProgressCallback* callback; }; -void BaseProgressCallback::callSuccessCallbackOnMainThread() -{ - LoggerD("Entered"); +void BaseProgressCallback::callSuccessCallbackOnMainThread() { + LoggerD("Entered"); - guint id = g_idle_add(BaseProgressCallback::callSuccessCallbackCB, - static_cast(this)); - if (!id) { - LoggerE("g_idle_add fails - success callback will not be called"); - } + guint id = g_idle_add(BaseProgressCallback::callSuccessCallbackCB, static_cast(this)); + if (!id) { + LoggerE("g_idle_add fails - success callback will not be called"); + } } -gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) -{ - LoggerD("Entered"); +gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) { + LoggerD("Entered"); - BaseProgressCallback* callback = static_cast(data); - if (!callback) { - LoggerE("callback pointer is NULL"); - return false; - } + BaseProgressCallback* callback = static_cast(data); + if (!callback) { + LoggerE("callback pointer is NULL"); + return false; + } - std::unique_ptr cb_ptr(callback); + std::unique_ptr cb_ptr(callback); - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - if (!callback->isError()) { - ReportSuccess(obj); - LoggerD("%s", val.serialize().c_str()); + if (!callback->isError()) { + ReportSuccess(obj); + LoggerD("%s", val.serialize().c_str()); - Instance::PostMessage(&callback->instance_, val.serialize().c_str()); - } else { - LoggerW("Not calling error callback in such case"); - } + Instance::PostMessage(&callback->instance_, val.serialize().c_str()); + } else { + LoggerW("Not calling error callback in such case"); + } - callback->setArchiveFile(ArchiveFilePtr()); - ArchiveManager::getInstance().eraseElementFromArchiveFileMap(callback->m_op_id); + callback->setArchiveFile(ArchiveFilePtr()); + ArchiveManager::getInstance().eraseElementFromArchiveFileMap(callback->m_op_id); - return false; + return false; } -void BaseProgressCallback::callProgressCallback(long operationId, - double value, - const std::string& filename, - double callbackId) -{ - LoggerD("Entered"); +void BaseProgressCallback::callProgressCallback(long operationId, double value, + const std::string& filename, double callbackId) { + LoggerD("Entered"); - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); - obj[JSON_LISTENER_ID] = picojson::value(JSON_ONPROGRESS_CALLBACK); + obj[JSON_LISTENER_ID] = picojson::value(JSON_ONPROGRESS_CALLBACK); - picojson::object result; - result[JSON_ACTION] = picojson::value(JSON_CALLBACK_PROGRESS); - result[PARAM_OPERATION_ID] = picojson::value(static_cast(operationId)); - result[PARAM_VALUE] = picojson::value(value); - result[PARAM_FILENAME] = picojson::value(filename); + picojson::object result; + result[JSON_ACTION] = picojson::value(JSON_CALLBACK_PROGRESS); + result[PARAM_OPERATION_ID] = picojson::value(static_cast(operationId)); + result[PARAM_VALUE] = picojson::value(value); + result[PARAM_FILENAME] = picojson::value(filename); - ReportSuccess(picojson::value(result), obj); - LoggerD("%s", val.serialize().c_str()); + ReportSuccess(picojson::value(result), obj); + LoggerD("%s", val.serialize().c_str()); - Instance::PostMessage(&instance_, val.serialize().c_str()); + Instance::PostMessage(&instance_, val.serialize().c_str()); } void BaseProgressCallback::callProgressCallbackOnMainThread(const double progress, - ArchiveFileEntryPtr current_entry) -{ - LoggerD("Entered"); - - ProgressHolder* ph = new(std::nothrow) ProgressHolder(); - - if(ph) { - ph->overall_progress = progress; - ph->currently_processed_entry = current_entry; - ph->callback = this; - - guint id = g_idle_add(BaseProgressCallback::callProgressCallbackCB, - static_cast(ph)); - if (!id) { - LoggerE("g_idle_add fails"); - delete ph; - ph = NULL; - } - } else { - LoggerE("Couldn't allocate ProgressHolder"); - } -} + ArchiveFileEntryPtr current_entry) { + LoggerD("Entered"); -gboolean BaseProgressCallback::callProgressCallbackCB(void* data) -{ - LoggerD("Entered"); + ProgressHolder* ph = new (std::nothrow) ProgressHolder(); - ProgressHolder* ph = static_cast(data); - if (!ph) { - LoggerE("ph is null"); - return false; - } + if (ph) { + ph->overall_progress = progress; + ph->currently_processed_entry = current_entry; + ph->callback = this; - std::unique_ptr ph_ptr(ph); - if (!ph->callback) { - LoggerE("ph->callback is null"); - return false; + guint id = g_idle_add(BaseProgressCallback::callProgressCallbackCB, static_cast(ph)); + if (!id) { + LoggerE("g_idle_add fails"); + delete ph; + ph = NULL; } + } else { + LoggerE("Couldn't allocate ProgressHolder"); + } +} - LoggerW("STUB Not checking if context is still alive"); +gboolean BaseProgressCallback::callProgressCallbackCB(void* data) { + LoggerD("Entered"); - ph->callback->callProgressCallback( - ph->callback->m_op_id, - ph->overall_progress, - ph->currently_processed_entry->getName(), - ph->callback->m_cid); + ProgressHolder* ph = static_cast(data); + if (!ph) { + LoggerE("ph is null"); + return false; + } + std::unique_ptr ph_ptr(ph); + if (!ph->callback) { + LoggerE("ph->callback is null"); return false; + } + + LoggerW("STUB Not checking if context is still alive"); + + ph->callback->callProgressCallback(ph->callback->m_op_id, ph->overall_progress, + ph->currently_processed_entry->getName(), ph->callback->m_cid); + + return false; } //---------------------------------------------------------------------------------------- -//AddProgressCallback +// AddProgressCallback //---------------------------------------------------------------------------------------- -AddProgressCallback::AddProgressCallback(ArchiveInstance& instance): - BaseProgressCallback(ADD_PROGRESS_CALLBACK, instance) -{ - LoggerD("Entered"); +AddProgressCallback::AddProgressCallback(ArchiveInstance& instance) + : BaseProgressCallback(ADD_PROGRESS_CALLBACK, instance) { + LoggerD("Entered"); } -AddProgressCallback::~AddProgressCallback() -{ - LoggerD("Entered"); +AddProgressCallback::~AddProgressCallback() { + LoggerD("Entered"); } -ArchiveFileEntryPtr AddProgressCallback::getFileEntry() const -{ - LoggerD("Entered"); - return m_file_entry; +ArchiveFileEntryPtr AddProgressCallback::getFileEntry() const { + LoggerD("Entered"); + return m_file_entry; } -void AddProgressCallback::setFileEntry(ArchiveFileEntryPtr file_entry) -{ - LoggerD("Entered"); - m_file_entry = file_entry; +void AddProgressCallback::setFileEntry(ArchiveFileEntryPtr file_entry) { + LoggerD("Entered"); + m_file_entry = file_entry; } -void AddProgressCallback::setBasePath(const std::string& path) -{ - LoggerD("Entered"); - m_base_path = path; - m_base_virt_path = common::FilesystemProvider::Create().GetVirtualPath(m_base_path); - std::string::size_type pos = m_base_virt_path.find(filesystem::Path::getSeparator()); - if (pos != std::string::npos) - { - m_base_virt_path = m_base_virt_path.substr(pos + 1); - } - else - { - m_base_virt_path = ""; - } +void AddProgressCallback::setBasePath(const std::string& path) { + LoggerD("Entered"); + m_base_path = path; + m_base_virt_path = common::FilesystemProvider::Create().GetVirtualPath(m_base_path); + std::string::size_type pos = m_base_virt_path.find(filesystem::Path::getSeparator()); + if (pos != std::string::npos) { + m_base_virt_path = m_base_virt_path.substr(pos + 1); + } else { + m_base_virt_path = ""; + } } -const std::string& AddProgressCallback::getBasePath() -{ - LoggerD("Entered"); - return m_base_path; +const std::string& AddProgressCallback::getBasePath() { + LoggerD("Entered"); + return m_base_path; } -const std::string& AddProgressCallback::getBaseVirtualPath() -{ - LoggerD("Entered"); - return m_base_virt_path; +const std::string& AddProgressCallback::getBaseVirtualPath() { + LoggerD("Entered"); + return m_base_virt_path; } -PlatformResult AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); +PlatformResult AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); - if(!m_file_entry) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", ("ArchiveFileEntry is not set in callback")); - } + if (!m_file_entry) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", + ("ArchiveFileEntry is not set in callback")); + } - if(!archive_file_ptr) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("archive_file_ptr is NULL")); - } + if (!archive_file_ptr) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", + ("archive_file_ptr is NULL")); + } - AddProgressCallback* callback = this; + AddProgressCallback* callback = this; - ZipPtr zip; - PlatformResult result = archive_file_ptr->createZipObject(&zip); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("archive_file_ptr->createZipObject()"); - return result; - } + ZipPtr zip; + PlatformResult result = archive_file_ptr->createZipObject(&zip); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("archive_file_ptr->createZipObject()"); + return result; + } - result = zip->addFile(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("zip->addFile()"); - return result; - } + result = zip->addFile(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("zip->addFile()"); + return result; + } - // Zip is no more needed but it locks file opening while - // it is needed to read entries from file - result = zip->close(); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("zip->close()"); - return result; - } + // Zip is no more needed but it locks file opening while + // it is needed to read entries from file + result = zip->close(); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("zip->close()"); + return result; + } - //We have just finished adding file to archive so now - //this archive file should be valid .zip archive and - //we can remove CreatedAsNewEmptyArchive flag - archive_file_ptr->setCreatedAsNewEmptyArchive(false); + // We have just finished adding file to archive so now + // this archive file should be valid .zip archive and + // we can remove CreatedAsNewEmptyArchive flag + archive_file_ptr->setCreatedAsNewEmptyArchive(false); - LoggerD("Update decompressed size and entry list"); - // update informations about decompressed size and entry list - return archive_file_ptr->updateListOfEntries(); + LoggerD("Update decompressed size and entry list"); + // update informations about decompressed size and entry list + return archive_file_ptr->updateListOfEntries(); } //---------------------------------------------------------------------------------------- -//ExtractAllProgressCallback +// ExtractAllProgressCallback //---------------------------------------------------------------------------------------- -ExtractAllProgressCallback::ExtractAllProgressCallback(ArchiveInstance& instance): - BaseProgressCallback(EXTRACT_ALL_PROGRESS_CALLBACK, instance), - m_files_to_extract(0), - m_expected_decompressed_size(0), - m_current_file_size(0), - m_current_file_extracted_bytes(0), - m_files_extracted(0), - m_progress_overall(0), - m_overall_decompressed(0) -{ - LoggerD("Entered"); +ExtractAllProgressCallback::ExtractAllProgressCallback(ArchiveInstance& instance) + : BaseProgressCallback(EXTRACT_ALL_PROGRESS_CALLBACK, instance), + m_files_to_extract(0), + m_expected_decompressed_size(0), + m_current_file_size(0), + m_current_file_extracted_bytes(0), + m_files_extracted(0), + m_progress_overall(0), + m_overall_decompressed(0) { + LoggerD("Entered"); } -ExtractAllProgressCallback::~ExtractAllProgressCallback() -{ - LoggerD("Entered"); +ExtractAllProgressCallback::~ExtractAllProgressCallback() { + LoggerD("Entered"); } -filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const -{ - LoggerD("Entered"); - return m_directory; +filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const { + LoggerD("Entered"); + return m_directory; } -void ExtractAllProgressCallback::setDirectory(filesystem::FilePtr directory) -{ - LoggerD("Entered"); - m_directory = directory; +void ExtractAllProgressCallback::setDirectory(filesystem::FilePtr directory) { + LoggerD("Entered"); + m_directory = directory; } -void ExtractAllProgressCallback::startedExtractingFile(unsigned long current_file_size) -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::startedExtractingFile(unsigned long current_file_size) { + LoggerD("Entered"); - m_current_file_size = current_file_size; - m_current_file_extracted_bytes = 0; + m_current_file_size = current_file_size; + m_current_file_extracted_bytes = 0; } -void ExtractAllProgressCallback::extractedPartOfFile(unsigned long bytes_decompressed) -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::extractedPartOfFile(unsigned long bytes_decompressed) { + LoggerD("Entered"); - m_current_file_extracted_bytes += bytes_decompressed; - updateOverallProgress(bytes_decompressed); + m_current_file_extracted_bytes += bytes_decompressed; + updateOverallProgress(bytes_decompressed); } -void ExtractAllProgressCallback::finishedExtractingFile() -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::finishedExtractingFile() { + LoggerD("Entered"); - m_current_file_size = 0; - m_current_file_extracted_bytes = 0; - ++m_files_extracted; - updateOverallProgress(0); + m_current_file_size = 0; + m_current_file_extracted_bytes = 0; + ++m_files_extracted; + updateOverallProgress(0); } -void ExtractAllProgressCallback::updateOverallProgress(unsigned long bytes_decompressed) -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::updateOverallProgress(unsigned long bytes_decompressed) { + LoggerD("Entered"); - m_overall_decompressed += bytes_decompressed; - m_progress_overall = - static_cast(m_overall_decompressed + m_files_extracted) / - static_cast(m_expected_decompressed_size + m_files_to_extract); + m_overall_decompressed += bytes_decompressed; + m_progress_overall = static_cast(m_overall_decompressed + m_files_extracted) / + static_cast(m_expected_decompressed_size + m_files_to_extract); - LoggerD("%s of %s - %f%% (%d/%d files)", - bytesToReadableString(m_overall_decompressed).c_str(), - bytesToReadableString(m_expected_decompressed_size).c_str(), - m_progress_overall * 100.0, - m_files_extracted, m_files_to_extract); + LoggerD("%s of %s - %f%% (%d/%d files)", bytesToReadableString(m_overall_decompressed).c_str(), + bytesToReadableString(m_expected_decompressed_size).c_str(), m_progress_overall * 100.0, + m_files_extracted, m_files_to_extract); } -double ExtractAllProgressCallback::getCurrentFileProgress() const -{ - LoggerD("Entered"); +double ExtractAllProgressCallback::getCurrentFileProgress() const { + LoggerD("Entered"); - if(m_current_file_size > 0) { - return static_cast(m_current_file_extracted_bytes) / - static_cast(m_current_file_size); - } - else { - return 1.0; - } + if (m_current_file_size > 0) { + return static_cast(m_current_file_extracted_bytes) / + static_cast(m_current_file_size); + } else { + return 1.0; + } } -double ExtractAllProgressCallback::getOverallProgress() const -{ - LoggerD("Entered"); +double ExtractAllProgressCallback::getOverallProgress() const { + LoggerD("Entered"); - return m_progress_overall; + return m_progress_overall; } -PlatformResult ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); - return archive_file_ptr->extractAllTask(this); +PlatformResult ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); + return archive_file_ptr->extractAllTask(this); } -void ExtractAllProgressCallback::setExpectedDecompressedSize(unsigned long exp_dec_size) -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::setExpectedDecompressedSize(unsigned long exp_dec_size) { + LoggerD("Entered"); - m_expected_decompressed_size = exp_dec_size; + m_expected_decompressed_size = exp_dec_size; } -unsigned long ExtractAllProgressCallback::getExpectedDecompressedSize() const -{ - LoggerD("Entered"); +unsigned long ExtractAllProgressCallback::getExpectedDecompressedSize() const { + LoggerD("Entered"); - return m_expected_decompressed_size; + return m_expected_decompressed_size; } -void ExtractAllProgressCallback::setNumberOfFilesToExtract(unsigned long files_count) -{ - LoggerD("Entered"); +void ExtractAllProgressCallback::setNumberOfFilesToExtract(unsigned long files_count) { + LoggerD("Entered"); - m_files_to_extract = files_count; + m_files_to_extract = files_count; } -unsigned long ExtractAllProgressCallback::getNumberOfFilesToExtract() const -{ - LoggerD("Entered"); +unsigned long ExtractAllProgressCallback::getNumberOfFilesToExtract() const { + LoggerD("Entered"); - return m_files_to_extract; + return m_files_to_extract; } //---------------------------------------------------------------------------------------- -//OperationCanceledException +// OperationCanceledException //---------------------------------------------------------------------------------------- const char* OPERATION_CANCELED_EXCEPTION = "OperationCanceledException"; -OperationCanceledException::OperationCanceledException(const char* message) -{ - LoggerD("Entered"); +OperationCanceledException::OperationCanceledException(const char* message) { + LoggerD("Entered"); } //---------------------------------------------------------------------------------------- -//ExtractEntryProgressCallback +// ExtractEntryProgressCallback //---------------------------------------------------------------------------------------- -ExtractEntryProgressCallback::ExtractEntryProgressCallback(ArchiveInstance& instance): - ExtractAllProgressCallback(instance), - m_strip_name(false) -{ - LoggerD("Entered"); - m_callback_type = EXTRACT_ENTRY_PROGRESS_CALLBACK; +ExtractEntryProgressCallback::ExtractEntryProgressCallback(ArchiveInstance& instance) + : ExtractAllProgressCallback(instance), m_strip_name(false) { + LoggerD("Entered"); + m_callback_type = EXTRACT_ENTRY_PROGRESS_CALLBACK; } -ExtractEntryProgressCallback::~ExtractEntryProgressCallback() -{ - LoggerD("Entered"); +ExtractEntryProgressCallback::~ExtractEntryProgressCallback() { + LoggerD("Entered"); } -ArchiveFileEntryPtr ExtractEntryProgressCallback::getArchiveFileEntry() -{ - LoggerD("Entered"); - return m_archive_file_entry; +ArchiveFileEntryPtr ExtractEntryProgressCallback::getArchiveFileEntry() { + LoggerD("Entered"); + return m_archive_file_entry; } -void ExtractEntryProgressCallback::setArchiveFileEntry(ArchiveFileEntryPtr afentry) -{ - LoggerD("Entered"); - m_archive_file_entry = afentry; +void ExtractEntryProgressCallback::setArchiveFileEntry(ArchiveFileEntryPtr afentry) { + LoggerD("Entered"); + m_archive_file_entry = afentry; } -void ExtractEntryProgressCallback::setStripName(bool strip_name) -{ - LoggerD("Entered"); - m_strip_name = strip_name; +void ExtractEntryProgressCallback::setStripName(bool strip_name) { + LoggerD("Entered"); + m_strip_name = strip_name; } -bool ExtractEntryProgressCallback::getStripName() const -{ - LoggerD("Entered"); - return m_strip_name; +bool ExtractEntryProgressCallback::getStripName() const { + LoggerD("Entered"); + return m_strip_name; } -void ExtractEntryProgressCallback::setStripBasePath( - const std::string& strip_base_path) -{ - LoggerD("Entered"); - m_strip_base_path = strip_base_path; +void ExtractEntryProgressCallback::setStripBasePath(const std::string& strip_base_path) { + LoggerD("Entered"); + m_strip_base_path = strip_base_path; } -const std::string& ExtractEntryProgressCallback::getStripBasePath() const -{ - LoggerD("Entered"); - return m_strip_base_path; +const std::string& ExtractEntryProgressCallback::getStripBasePath() const { + LoggerD("Entered"); + return m_strip_base_path; } -PlatformResult ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); +PlatformResult ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); - if(!m_archive_file_entry) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("ArchiveFileEntry is not set in callback")); - } + if (!m_archive_file_entry) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", + ("ArchiveFileEntry is not set in callback")); + } - if(!archive_file_ptr) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("archive_file_ptr is NULL")); - } + if (!archive_file_ptr) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", + ("archive_file_ptr is NULL")); + } - UnZipPtr unzip; - PlatformResult result = archive_file_ptr->createUnZipObject(&unzip); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("archive_file_ptr->createUnZipObject()"); - return result; - } + UnZipPtr unzip; + PlatformResult result = archive_file_ptr->createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("archive_file_ptr->createUnZipObject()"); + return result; + } - return unzip->extractTo(this); + return unzip->extractTo(this); } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/archive_callback_data.h b/src/archive/archive_callback_data.h index 4815e9e..7d2aed5 100644 --- a/src/archive/archive_callback_data.h +++ b/src/archive/archive_callback_data.h @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef __ARCHIVE_CALLBACK_DATA_H__ #define __ARCHIVE_CALLBACK_DATA_H__ -#include -#include #include +#include +#include +#include "archive_file_entry.h" #include "common/platform_result.h" #include "filesystem_file.h" -#include "archive_file_entry.h" namespace extension { namespace archive { @@ -36,14 +35,14 @@ class ArchiveFileEntry; typedef std::shared_ptr ArchiveFileEntryPtr; enum ArchiveCallbackType { - OPERATION_CALLBACK_DATA = 0, - OPEN_CALLBACK_DATA = 1, - GET_ENTRIES_CALLBACK_DATA = 2, - GET_ENTRY_BY_NAME_CALLBACK_DATA = 3, - BASE_PROGRESS_CALLBACK = 4, - EXTRACT_ALL_PROGRESS_CALLBACK = 5, - EXTRACT_ENTRY_PROGRESS_CALLBACK = 6, - ADD_PROGRESS_CALLBACK = 7 + OPERATION_CALLBACK_DATA = 0, + OPEN_CALLBACK_DATA = 1, + GET_ENTRIES_CALLBACK_DATA = 2, + GET_ENTRY_BY_NAME_CALLBACK_DATA = 3, + BASE_PROGRESS_CALLBACK = 4, + EXTRACT_ALL_PROGRESS_CALLBACK = 5, + EXTRACT_ENTRY_PROGRESS_CALLBACK = 6, + ADD_PROGRESS_CALLBACK = 7 }; class ArchiveFile; @@ -51,225 +50,212 @@ typedef std::shared_ptr ArchiveFilePtr; class ArchiveInstance; -class OperationCallbackData -{ -public: - OperationCallbackData(ArchiveCallbackType callback_type, ArchiveInstance& instance); - virtual ~OperationCallbackData(); +class OperationCallbackData { + public: + OperationCallbackData(ArchiveCallbackType callback_type, ArchiveInstance& instance); + virtual ~OperationCallbackData(); - void setError(const ErrorCode &err_code, - const std::string &err_message); - bool isError() const; - const ErrorCode& getErrorCode() const; - const std::string& getErrorMessage() const; + void setError(const ErrorCode& err_code, const std::string& err_message); + bool isError() const; + const ErrorCode& getErrorCode() const; + const std::string& getErrorMessage() const; - void setOperationId(long op_id); - long getOperationId() const; - void setCallbackId(double cid); - double getCallbackId() const; - void setHandle(long handle); - long getHandle() const; + void setOperationId(long op_id); + long getOperationId() const; + void setCallbackId(double cid); + double getCallbackId() const; + void setHandle(long handle); + long getHandle() const; - ArchiveCallbackType getCallbackType() const; + ArchiveCallbackType getCallbackType() const; - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; - ArchiveFilePtr getArchiveFile() const; - void setArchiveFile(ArchiveFilePtr caller); + ArchiveFilePtr getArchiveFile() const; + void setArchiveFile(ArchiveFilePtr caller); - bool isCanceled() const; - void setIsCanceled(bool canceled); + bool isCanceled() const; + void setIsCanceled(bool canceled); - void PostMessage(const char* msg); + void PostMessage(const char* msg); -protected: - ArchiveCallbackType m_callback_type; - long m_op_id; - double m_cid; - long m_handle; - ArchiveInstance& instance_; + protected: + ArchiveCallbackType m_callback_type; + long m_op_id; + double m_cid; + long m_handle; + ArchiveInstance& instance_; -private: - bool m_is_error; - bool m_is_canceled; - ErrorCode m_err_code; - std::string m_err_message; + private: + bool m_is_error; + bool m_is_canceled; + ErrorCode m_err_code; + std::string m_err_message; - ArchiveFilePtr m_caller_instance; + ArchiveFilePtr m_caller_instance; }; -class OpenCallbackData : public OperationCallbackData -{ -public: - explicit OpenCallbackData(ArchiveInstance& instance); - virtual ~OpenCallbackData(); +class OpenCallbackData : public OperationCallbackData { + public: + explicit OpenCallbackData(ArchiveInstance& instance); + virtual ~OpenCallbackData(); - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); -private: - std::string m_filename; + private: + std::string m_filename; }; -class GetEntriesCallbackData : public OperationCallbackData -{ -public: - explicit GetEntriesCallbackData(ArchiveInstance& instance); - virtual ~GetEntriesCallbackData(); +class GetEntriesCallbackData : public OperationCallbackData { + public: + explicit GetEntriesCallbackData(ArchiveInstance& instance); + virtual ~GetEntriesCallbackData(); - ArchiveFileEntryPtrMapPtr getEntries() const; - void setEntries(ArchiveFileEntryPtrMapPtr entries); + ArchiveFileEntryPtrMapPtr getEntries() const; + void setEntries(ArchiveFileEntryPtrMapPtr entries); - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); -private: - ArchiveFileEntryPtrMapPtr m_entries; + private: + ArchiveFileEntryPtrMapPtr m_entries; }; -class GetEntryByNameCallbackData : public OperationCallbackData -{ -public: - explicit GetEntryByNameCallbackData(ArchiveInstance& instance); - virtual ~GetEntryByNameCallbackData(); +class GetEntryByNameCallbackData : public OperationCallbackData { + public: + explicit GetEntryByNameCallbackData(ArchiveInstance& instance); + virtual ~GetEntryByNameCallbackData(); - const std::string& getName() const; - void setName(const std::string& name); + const std::string& getName() const; + void setName(const std::string& name); - ArchiveFileEntryPtr getFileEntry() const; - void setFileEntry(ArchiveFileEntryPtr entry); + ArchiveFileEntryPtr getFileEntry() const; + void setFileEntry(ArchiveFileEntryPtr entry); - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); -private: - std::string m_name; - ArchiveFileEntryPtr m_file_entry; + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + private: + std::string m_name; + ArchiveFileEntryPtr m_file_entry; }; -class BaseProgressCallback : public OperationCallbackData -{ -public: - BaseProgressCallback(ArchiveCallbackType callback_type, ArchiveInstance& instance); - virtual ~BaseProgressCallback(); +class BaseProgressCallback : public OperationCallbackData { + public: + BaseProgressCallback(ArchiveCallbackType callback_type, ArchiveInstance& instance); + virtual ~BaseProgressCallback(); - bool getOverwrite() const; - void setOverwrite(bool overwrite); + bool getOverwrite() const; + void setOverwrite(bool overwrite); - void callProgressCallbackOnMainThread(const double progress, - ArchiveFileEntryPtr current_entry); - void callSuccessCallbackOnMainThread(); + void callProgressCallbackOnMainThread(const double progress, ArchiveFileEntryPtr current_entry); + void callSuccessCallbackOnMainThread(); - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; -protected: - void callProgressCallback(long operationId, - double value, - const std::string& filename, - double callbackId); + protected: + void callProgressCallback(long operationId, double value, const std::string& filename, + double callbackId); -private: - static gboolean callProgressCallbackCB(void* data); - static gboolean callSuccessCallbackCB(void* data); + private: + static gboolean callProgressCallbackCB(void* data); + static gboolean callSuccessCallbackCB(void* data); - bool m_overwrite; + bool m_overwrite; }; -class AddProgressCallback : public BaseProgressCallback -{ -public: - explicit AddProgressCallback(ArchiveInstance& instance); - virtual ~AddProgressCallback(); +class AddProgressCallback : public BaseProgressCallback { + public: + explicit AddProgressCallback(ArchiveInstance& instance); + virtual ~AddProgressCallback(); - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); - void setBasePath(const std::string& path); - const std::string& getBasePath(); - const std::string& getBaseVirtualPath(); + void setBasePath(const std::string& path); + const std::string& getBasePath(); + const std::string& getBaseVirtualPath(); - ArchiveFileEntryPtr getFileEntry() const; - void setFileEntry(ArchiveFileEntryPtr file_entry); + ArchiveFileEntryPtr getFileEntry() const; + void setFileEntry(ArchiveFileEntryPtr file_entry); -private: - ArchiveFileEntryPtr m_file_entry; - ArchiveFileEntryPtrMapPtr m_entry_map; - std::string m_base_path; - std::string m_base_virt_path; + private: + ArchiveFileEntryPtr m_file_entry; + ArchiveFileEntryPtrMapPtr m_entry_map; + std::string m_base_path; + std::string m_base_virt_path; }; -class ExtractAllProgressCallback : public BaseProgressCallback -{ -public: - explicit ExtractAllProgressCallback(ArchiveInstance& instance); - virtual ~ExtractAllProgressCallback(); +class ExtractAllProgressCallback : public BaseProgressCallback { + public: + explicit ExtractAllProgressCallback(ArchiveInstance& instance); + virtual ~ExtractAllProgressCallback(); - filesystem::FilePtr getDirectory() const; - void setDirectory(filesystem::FilePtr directory); + filesystem::FilePtr getDirectory() const; + void setDirectory(filesystem::FilePtr directory); - void startedExtractingFile(unsigned long current_file_size); - void extractedPartOfFile(unsigned long bytes_decompressed); - void finishedExtractingFile(); + void startedExtractingFile(unsigned long current_file_size); + void extractedPartOfFile(unsigned long bytes_decompressed); + void finishedExtractingFile(); - double getCurrentFileProgress() const; - double getOverallProgress() const; + double getCurrentFileProgress() const; + double getOverallProgress() const; - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); - void setExpectedDecompressedSize(unsigned long exp_dec_size); - unsigned long getExpectedDecompressedSize() const; + void setExpectedDecompressedSize(unsigned long exp_dec_size); + unsigned long getExpectedDecompressedSize() const; - void setNumberOfFilesToExtract(unsigned long files_count); - unsigned long getNumberOfFilesToExtract() const; + void setNumberOfFilesToExtract(unsigned long files_count); + unsigned long getNumberOfFilesToExtract() const; -private: - void updateOverallProgress(unsigned long bytes_decompressed); + private: + void updateOverallProgress(unsigned long bytes_decompressed); - filesystem::FilePtr m_directory; + filesystem::FilePtr m_directory; - // - // Constant values set before extracting entries: - // - unsigned long m_files_to_extract; - unsigned long m_expected_decompressed_size; + // + // Constant values set before extracting entries: + // + unsigned long m_files_to_extract; + unsigned long m_expected_decompressed_size; - // - // Values updated during extraction - // + // + // Values updated during extraction + // - unsigned long m_current_file_size; - unsigned long m_current_file_extracted_bytes; - unsigned long m_files_extracted; + unsigned long m_current_file_size; + unsigned long m_current_file_extracted_bytes; + unsigned long m_files_extracted; - double m_progress_overall; - unsigned long m_overall_decompressed; + double m_progress_overall; + unsigned long m_overall_decompressed; }; -class ExtractEntryProgressCallback : public ExtractAllProgressCallback -{ -public: - explicit ExtractEntryProgressCallback(ArchiveInstance& instance); - virtual ~ExtractEntryProgressCallback(); +class ExtractEntryProgressCallback : public ExtractAllProgressCallback { + public: + explicit ExtractEntryProgressCallback(ArchiveInstance& instance); + virtual ~ExtractEntryProgressCallback(); - ArchiveFileEntryPtr getArchiveFileEntry(); - void setArchiveFileEntry(ArchiveFileEntryPtr afentry); + ArchiveFileEntryPtr getArchiveFileEntry(); + void setArchiveFileEntry(ArchiveFileEntryPtr afentry); - void setStripName(bool strip_name); - bool getStripName() const; + void setStripName(bool strip_name); + bool getStripName() const; - void setStripBasePath(const std::string& strip_base_path); - const std::string& getStripBasePath() const; + void setStripBasePath(const std::string& strip_base_path); + const std::string& getStripBasePath() const; - virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); -private: - ArchiveFileEntryPtr m_archive_file_entry; - bool m_strip_name; - std::string m_strip_base_path; + private: + ArchiveFileEntryPtr m_archive_file_entry; + bool m_strip_name; + std::string m_strip_base_path; }; class OperationCanceledException { -public: - OperationCanceledException(const char* message = "Operation Canceled"); + public: + OperationCanceledException(const char* message = "Operation Canceled"); }; - } } -#endif //__ARCHIVE_CALLBACK_DATA_H__ +#endif //__ARCHIVE_CALLBACK_DATA_H__ diff --git a/src/archive/archive_extension.cc b/src/archive/archive_extension.cc old mode 100755 new mode 100644 index d0c2b9d..dfa97a8 --- a/src/archive/archive_extension.cc +++ b/src/archive/archive_extension.cc @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "archive_extension.h" #include "archive_instance.h" @@ -22,26 +21,22 @@ // This will be generated from archive_api.js extern const char kSource_archive_api[]; -common::Extension* CreateExtension() -{ - LoggerD("Enter"); - return new ArchiveExtension; +common::Extension* CreateExtension() { + LoggerD("Enter"); + return new ArchiveExtension; } -ArchiveExtension::ArchiveExtension() -{ - LoggerD("Enter"); - SetExtensionName("tizen.archive"); - SetJavaScriptAPI(kSource_archive_api); +ArchiveExtension::ArchiveExtension() { + LoggerD("Enter"); + SetExtensionName("tizen.archive"); + SetJavaScriptAPI(kSource_archive_api); } -ArchiveExtension::~ArchiveExtension() -{ - LoggerD("Enter"); +ArchiveExtension::~ArchiveExtension() { + LoggerD("Enter"); } -common::Instance* ArchiveExtension::CreateInstance() -{ - LoggerD("Enter"); - return new extension::archive::ArchiveInstance(); +common::Instance* ArchiveExtension::CreateInstance() { + LoggerD("Enter"); + return new extension::archive::ArchiveInstance(); } diff --git a/src/archive/archive_extension.h b/src/archive/archive_extension.h old mode 100755 new mode 100644 index 3514201..e3e734e --- a/src/archive/archive_extension.h +++ b/src/archive/archive_extension.h @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef ARCHIVE_ARCHIVE_EXTENSION_H_ #define ARCHIVE_ARCHIVE_EXTENSION_H_ #include "common/extension.h" -class ArchiveExtension: public common::Extension { -public: - ArchiveExtension(); - virtual ~ArchiveExtension(); +class ArchiveExtension : public common::Extension { + public: + ArchiveExtension(); + virtual ~ArchiveExtension(); -private: - virtual common::Instance* CreateInstance(); + private: + virtual common::Instance* CreateInstance(); }; -#endif // ARCHIVE_ARCHIVE_EXTENSION_H_ +#endif // ARCHIVE_ARCHIVE_EXTENSION_H_ diff --git a/src/archive/archive_file.cc b/src/archive/archive_file.cc old mode 100755 new mode 100644 index e016136..f52da91 --- a/src/archive/archive_file.cc +++ b/src/archive/archive_file.cc @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "archive_file.h" -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/tools.h" +#include "archive_instance.h" #include "archive_manager.h" #include "archive_utils.h" #include "defs.h" #include "un_zip.h" #include "zip.h" -#include "archive_instance.h" using common::tools::ReportError; using common::tools::ReportSuccess; @@ -33,729 +33,692 @@ using common::tools::ReportSuccess; namespace extension { namespace archive { -Permission::Permission(bool r, bool w, bool rw, bool a){ - LoggerD("Enter"); - permission[0] = r; - permission[1] = w; - permission[2] = rw; - permission[3] = a; +Permission::Permission(bool r, bool w, bool rw, bool a) { + LoggerD("Enter"); + permission[0] = r; + permission[1] = w; + permission[2] = rw; + permission[3] = a; } PermissionMap ArchiveFile::s_permission_map = { - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, - Permission(NOT_ALLOWED, ALLOWED, ALLOWED, ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)} -}; - -ArchiveFile::ArchiveFile() : - enable_shared_from_this(), - m_task_queue(), - m_file_mode(), - m_decompressed_size(0), - m_is_open(false), - m_overwrite(false), - m_created_as_new_empty_archive(false) -{ - LoggerD("Entered"); -} - -ArchiveFile::ArchiveFile(FileMode file_mode) : - enable_shared_from_this(), - m_task_queue(), - m_decompressed_size(0), - m_is_open(false), - m_overwrite(false), - m_created_as_new_empty_archive(false) -{ - LoggerD("Enter"); - m_file_mode = file_mode; -} - -ArchiveFile::~ArchiveFile() -{ - LoggerD("Entered"); - - if(m_entry_map) { - LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(NULL); - } - } - } -} - -gboolean ArchiveFile::openTaskCompleteCB(void *data) -{ - LoggerD("Entered"); - - auto callback = static_cast(data); - if (!callback) { - LoggerE("callback is null"); - return false; - } - - auto archive_file = callback->getArchiveFile(); - - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, Permission(NOT_ALLOWED, ALLOWED, ALLOWED, ALLOWED)}, + {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, + Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, + {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, + Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, + {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, + Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}}; + +ArchiveFile::ArchiveFile() + : enable_shared_from_this(), + m_task_queue(), + m_file_mode(), + m_decompressed_size(0), + m_is_open(false), + m_overwrite(false), + m_created_as_new_empty_archive(false) { + LoggerD("Entered"); +} + +ArchiveFile::ArchiveFile(FileMode file_mode) + : enable_shared_from_this(), + m_task_queue(), + m_decompressed_size(0), + m_is_open(false), + m_overwrite(false), + m_created_as_new_empty_archive(false) { + LoggerD("Enter"); + m_file_mode = file_mode; +} + +ArchiveFile::~ArchiveFile() { + LoggerD("Entered"); + + if (m_entry_map) { + LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); + for (auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { + if (it->second) { + it->second->setArchiveFileNonProtectPtr(NULL); + } + } + } +} + +gboolean ArchiveFile::openTaskCompleteCB(void* data) { + LoggerD("Entered"); + + auto callback = static_cast(data); + if (!callback) { + LoggerE("callback is null"); + return false; + } - if (!callback->isError()) { - long handle = ArchiveManager::getInstance().addPrivData(archive_file); + auto archive_file = callback->getArchiveFile(); - std::string fm_str; - PlatformResult result = fileModeToString(archive_file->getFileMode(), &fm_str); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("%s (%d)", result.message().c_str(), result.error_code()); - delete callback; - callback = NULL; - return false; - } + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - picojson::value ret_val = picojson::value(picojson::object()); - picojson::object& ret = ret_val.get(); + if (!callback->isError()) { + long handle = ArchiveManager::getInstance().addPrivData(archive_file); - ret[ARCHIVE_FILE_ATTR_MODE] = picojson::value(fm_str); - ret[ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE] = picojson::value(); - ret[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(handle)); - - ReportSuccess(ret_val, obj); - } else { - PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); - ReportError(ret, &obj); + std::string fm_str; + PlatformResult result = fileModeToString(archive_file->getFileMode(), &fm_str); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("%s (%d)", result.message().c_str(), result.error_code()); + delete callback; + callback = NULL; + return false; } - LoggerD("%s", val.serialize().c_str()); - - callback->PostMessage(val.serialize().c_str()); - - delete callback; - callback = NULL; - - return false; -} + picojson::value ret_val = picojson::value(picojson::object()); + picojson::object& ret = ret_val.get(); -gboolean ArchiveFile::callErrorCallback(void* data) -{ - LoggerD("Entered"); + ret[ARCHIVE_FILE_ATTR_MODE] = picojson::value(fm_str); + ret[ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE] = picojson::value(); + ret[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(handle)); - auto callback = static_cast(data); - if (!callback) { - LoggerE("callback is null"); - return false; - } + ReportSuccess(ret_val, obj); + } else { + PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); + ReportError(ret, &obj); + } - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + LoggerD("%s", val.serialize().c_str()); - if (!callback->isError()) { - LoggerW("The success callback should be not be called in this case"); - } else { - PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); - ReportError(ret, &obj); - } + callback->PostMessage(val.serialize().c_str()); - LoggerD("%s", val.serialize().c_str()); + delete callback; + callback = NULL; - callback->PostMessage(val.serialize().c_str()); + return false; +} - delete callback; - callback = NULL; +gboolean ArchiveFile::callErrorCallback(void* data) { + LoggerD("Entered"); + auto callback = static_cast(data); + if (!callback) { + LoggerE("callback is null"); return false; -} - -void ArchiveFile::taskManagerThread(gpointer data, gpointer user_data) -{ - LoggerD("Entered"); - ArchiveFileHolder* archive_file_holder = static_cast(data); - if (!archive_file_holder) { - LoggerE("archive_file_holder is null"); - return; - } + } - if (!archive_file_holder->ptr){ - LoggerE("archive_file is null"); - delete archive_file_holder; - archive_file_holder = NULL; - return; - } + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - PlatformResult result(ErrorCode::NO_ERROR); + if (!callback->isError()) { + LoggerW("The success callback should be not be called in this case"); + } else { + PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); + ReportError(ret, &obj); + } - while(true){ - OperationCallbackData* callback = NULL; + LoggerD("%s", val.serialize().c_str()); - result = PlatformResult(ErrorCode::NO_ERROR); + callback->PostMessage(val.serialize().c_str()); - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - if(archive_file_holder->ptr->m_task_queue.empty()){ - break; - } - callback = archive_file_holder->ptr->m_task_queue.back().second; - } + delete callback; + callback = NULL; - if (callback) { - if (!callback->isCanceled()){ - result = callback->executeOperation(archive_file_holder->ptr); - } - - if (ErrorCode::OPERATION_CANCELED_ERR == result.error_code()) { - delete callback; - callback = NULL; - } else if (ErrorCode::NO_ERROR != result.error_code()) { - LoggerE("taskManagerThread fails, %d: %s", result.error_code(), - result.message().c_str()); - callback->setError(result.error_code(), result.message().c_str()); - if (!g_idle_add(callErrorCallback, static_cast(callback))) { - LoggerE("g_idle_add fails"); - delete callback; - callback = NULL; - } - } - } + return false; +} - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } - } +void ArchiveFile::taskManagerThread(gpointer data, gpointer user_data) { + LoggerD("Entered"); + ArchiveFileHolder* archive_file_holder = static_cast(data); + if (!archive_file_holder) { + LoggerE("archive_file_holder is null"); + return; + } + if (!archive_file_holder->ptr) { + LoggerE("archive_file is null"); delete archive_file_holder; archive_file_holder = NULL; - return; -} + } -PlatformResult ArchiveFile::addOperation(OperationCallbackData* callback) -{ - LoggerD("Entered callback type:%d", callback->getCallbackType()); + PlatformResult result(ErrorCode::NO_ERROR); - const long operation_id = callback->getOperationId(); - callback->setArchiveFile(shared_from_this()); - std::size_t size = 0; - { - std::lock_guard lock(m_mutex); - m_task_queue.push_front(CallbackPair(operation_id, callback)); - size = m_task_queue.size(); - } - if(1 == size) { - ArchiveFileHolder* holder = new(std::nothrow) ArchiveFileHolder(); - if(!holder) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); - } - holder->ptr = shared_from_this(); - - // operations would be executed asynchronously on one background thread - // (no risk of parallel operations on file) - if (!g_thread_pool_push(ArchiveManager::getInstance().getThreadPool(), - static_cast(holder), NULL)) { - delete holder; - holder = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Thread creation failed"); - } - } - return PlatformResult(ErrorCode::NO_ERROR); -} + while (true) { + OperationCallbackData* callback = NULL; -PlatformResult ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) -{ - LoggerD("Enter"); - filesystem::FilePtr directory = callback->getDirectory(); + result = PlatformResult(ErrorCode::NO_ERROR); - if(!directory) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Directory is null"); - } else { - if(!directory->getNode()){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node in directory is null"); + { + std::lock_guard lock(archive_file_holder->ptr->m_mutex); + if (archive_file_holder->ptr->m_task_queue.empty()) { + break; + } + callback = archive_file_holder->ptr->m_task_queue.back().second; + } + + if (callback) { + if (!callback->isCanceled()) { + result = callback->executeOperation(archive_file_holder->ptr); + } + + if (ErrorCode::OPERATION_CANCELED_ERR == result.error_code()) { + delete callback; + callback = NULL; + } else if (ErrorCode::NO_ERROR != result.error_code()) { + LoggerE("taskManagerThread fails, %d: %s", result.error_code(), result.message().c_str()); + callback->setError(result.error_code(), result.message().c_str()); + if (!g_idle_add(callErrorCallback, static_cast(callback))) { + LoggerE("g_idle_add fails"); + delete callback; + callback = NULL; } + } } - if(!m_file) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null"); + { + std::lock_guard lock(archive_file_holder->ptr->m_mutex); + archive_file_holder->ptr->m_task_queue.pop_back(); + } + } + + delete archive_file_holder; + archive_file_holder = NULL; + + return; +} + +PlatformResult ArchiveFile::addOperation(OperationCallbackData* callback) { + LoggerD("Entered callback type:%d", callback->getCallbackType()); + + const long operation_id = callback->getOperationId(); + callback->setArchiveFile(shared_from_this()); + std::size_t size = 0; + { + std::lock_guard lock(m_mutex); + m_task_queue.push_front(CallbackPair(operation_id, callback)); + size = m_task_queue.size(); + } + if (1 == size) { + ArchiveFileHolder* holder = new (std::nothrow) ArchiveFileHolder(); + if (!holder) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); + } + holder->ptr = shared_from_this(); + + // operations would be executed asynchronously on one background thread + // (no risk of parallel operations on file) + if (!g_thread_pool_push(ArchiveManager::getInstance().getThreadPool(), + static_cast(holder), NULL)) { + delete holder; + holder = NULL; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Thread creation failed"); + } + } + return PlatformResult(ErrorCode::NO_ERROR); +} + +PlatformResult ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) { + LoggerD("Enter"); + filesystem::FilePtr directory = callback->getDirectory(); + + if (!directory) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Directory is null"); + } else { + if (!directory->getNode()) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node in directory is null"); + } + } + + if (!m_file) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null"); + } else { + if (!m_file->getNode()) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node in file is null"); + } + } + + // For explanation please see: + // ArchiveFile.h m_created_as_new_empty_archive description + // + unsigned long long size = 0; + PlatformResult result = m_file->getNode()->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail m_file->getNode()->getSize()"); + return result; + } + if (size == 0) { + LoggerD("Zip file: %s is empty", m_file->getNode()->getPath()->getFullPath().c_str()); + + if (m_created_as_new_empty_archive) { + // We do not call progress callback since we do not have any ArchiveFileEntry + callback->callSuccessCallbackOnMainThread(); + return PlatformResult(ErrorCode::NO_ERROR); } else { - if(!m_file->getNode()){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node in file is null"); - } - } - - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - unsigned long long size = 0; - PlatformResult result = m_file->getNode()->getSize(&size); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail m_file->getNode()->getSize()"); - return result; - } - if(size == 0) { - LoggerD("Zip file: %s is empty", - m_file->getNode()->getPath()->getFullPath().c_str()); - - if(m_created_as_new_empty_archive) { - //We do not call progress callback since we do not have any ArchiveFileEntry - callback->callSuccessCallbackOnMainThread(); - return PlatformResult(ErrorCode::NO_ERROR); - } - else { - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive", ("m_created_as_new_empty_archive is false")); - } + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive", + ("m_created_as_new_empty_archive is false")); } + } - UnZipPtr unzip; - result = createUnZipObject(&unzip); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail createUnZipObject()"); - return result; - } + UnZipPtr unzip; + result = createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail createUnZipObject()"); + return result; + } - return unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); + return unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); } -PlatformResult ArchiveFile::getEntries(GetEntriesCallbackData* callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get list of files in archive", ("callback is NULL")); - } +PlatformResult ArchiveFile::getEntries(GetEntriesCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get list of files in archive", + ("callback is NULL")); + } - if(!m_is_open){ - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); - } + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, + "ArchiveFile closed - operation not permitted"); + } - return addOperation(callback); + return addOperation(callback); } -gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) -{ - LoggerD("Entered"); - LoggerW("STUB Not calling success/error callback"); +gboolean ArchiveFile::getEntriesTaskCompleteCB(void* data) { + LoggerD("Entered"); + LoggerW("STUB Not calling success/error callback"); - auto callback = static_cast(data); - if (!callback) { - LoggerE("callback is null"); - return false; - } + auto callback = static_cast(data); + if (!callback) { + LoggerE("callback is null"); + return false; + } - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - - if (!callback->isError()) { - picojson::value arr_val = picojson::value(picojson::array()); - picojson::array& arr = arr_val.get(); - - ArchiveFileEntryPtrMapPtr entries = callback->getEntries(); - for(auto it = entries->begin(); it != entries->end(); it++) { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - - obj[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value( - it->second->getName()); - obj[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( - static_cast(it->second->getSize())); - obj[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( - static_cast(it->second->getModified())); - obj[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( - static_cast(it->second->getCompressedSize())); - obj[ARCHIVE_FILE_HANDLE] = picojson::value( - static_cast(callback->getHandle())); - - arr.push_back(val); - } + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - ReportSuccess(arr_val, obj); - } else { - PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); - ReportError(ret, &obj); + if (!callback->isError()) { + picojson::value arr_val = picojson::value(picojson::array()); + picojson::array& arr = arr_val.get(); + + ArchiveFileEntryPtrMapPtr entries = callback->getEntries(); + for (auto it = entries->begin(); it != entries->end(); it++) { + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + + obj[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value(it->second->getName()); + obj[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = + picojson::value(static_cast(it->second->getSize())); + obj[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = + picojson::value(static_cast(it->second->getModified())); + obj[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = + picojson::value(static_cast(it->second->getCompressedSize())); + obj[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(callback->getHandle())); + + arr.push_back(val); } - LoggerD("%s", val.serialize().c_str()); + ReportSuccess(arr_val, obj); + } else { + PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); + ReportError(ret, &obj); + } - callback->PostMessage(val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - delete callback; - callback = NULL; + callback->PostMessage(val.serialize().c_str()); - return false; + delete callback; + callback = NULL; + + return false; } -PlatformResult ArchiveFile::extractAll(ExtractAllProgressCallback *callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract all files from archive", ("callback is NULL")); - } +PlatformResult ArchiveFile::extractAll(ExtractAllProgressCallback* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract all files from archive", + ("callback is NULL")); + } - if(!m_is_open){ - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); - } + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, + "ArchiveFile closed - operation not permitted"); + } - return addOperation(callback); + return addOperation(callback); } -PlatformResult ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("callback is NULL")); - } +PlatformResult ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", + ("callback is NULL")); + } - // FIXME according to documentation: - // if archive was closed, any further operation attempt will make InvalidStateError - // but method extract() from ArchiveFileEntryObject is not permitted to throw above exception + // FIXME according to documentation: + // if archive was closed, any further operation attempt will make InvalidStateError + // but method extract() from ArchiveFileEntryObject is not permitted to throw above exception - // uncomment in case when this method have permission to throwing InvalidStateError - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Archive is not opened"); - } + // uncomment in case when this method have permission to throwing InvalidStateError + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Archive is not opened"); + } - return addOperation(callback); + return addOperation(callback); } +PlatformResult ArchiveFile::add(AddProgressCallback* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", + ("callback is NULL")); + } + if (FileMode::READ == m_file_mode) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Add not allowed for \"r\" access mode", + ("Trying to add file when READ access mode selected")); + } -PlatformResult ArchiveFile::add(AddProgressCallback *callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", ("callback is NULL")); - } - if(FileMode::READ == m_file_mode) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Add not allowed for \"r\" access mode", ("Trying to add file when READ access mode selected")); - } - - if(!m_is_open){ - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); - } + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, + "ArchiveFile closed - operation not permitted"); + } - return addOperation(callback); + return addOperation(callback); } -void ArchiveFile::close() -{ - LoggerD("Entered"); +void ArchiveFile::close() { + LoggerD("Entered"); - if(!m_is_open){ - LoggerD("Archive already closed"); - } - m_is_open = false; + if (!m_is_open) { + LoggerD("Archive already closed"); + } + m_is_open = false; - return; + return; } -PlatformResult ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get archive file entries by name", ("callback is NULL")); - } +PlatformResult ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get archive file entries by name", + ("callback is NULL")); + } - if(!m_is_open){ - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); - } + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, + "ArchiveFile closed - operation not permitted"); + } - return addOperation(callback); + return addOperation(callback); } -gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) -{ - LoggerD("Entered"); +gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void* data) { + LoggerD("Entered"); - auto callback = static_cast(data); - if (!callback) { - LoggerE("callback is null"); - return false; - } + auto callback = static_cast(data); + if (!callback) { + LoggerE("callback is null"); + return false; + } - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - if (!callback->isError()) { - ArchiveFileEntryPtr ent = callback->getFileEntry(); + if (!callback->isError()) { + ArchiveFileEntryPtr ent = callback->getFileEntry(); - picojson::value ret_val = picojson::value(picojson::object()); - picojson::object& ret = ret_val.get(); + picojson::value ret_val = picojson::value(picojson::object()); + picojson::object& ret = ret_val.get(); - ret[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value(ent->getName()); - ret[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( - static_cast(ent->getSize())); - ret[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( - static_cast(ent->getModified())); - ret[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( - static_cast(ent->getCompressedSize())); - ret[ARCHIVE_FILE_HANDLE] = picojson::value( - static_cast(callback->getHandle())); + ret[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value(ent->getName()); + ret[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value(static_cast(ent->getSize())); + ret[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = + picojson::value(static_cast(ent->getModified())); + ret[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = + picojson::value(static_cast(ent->getCompressedSize())); + ret[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(callback->getHandle())); - ReportSuccess(ret_val, obj); - } else { - PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); - ReportError(ret, &obj); - } + ReportSuccess(ret_val, obj); + } else { + PlatformResult ret = PlatformResult(callback->getErrorCode(), callback->getErrorMessage()); + ReportError(ret, &obj); + } - LoggerD("%s", val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - callback->PostMessage(val.serialize().c_str()); + callback->PostMessage(val.serialize().c_str()); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return false; + return false; } -filesystem::FilePtr ArchiveFile::getFile() const -{ - LoggerD("Entered"); - return m_file; +filesystem::FilePtr ArchiveFile::getFile() const { + LoggerD("Entered"); + return m_file; } -void ArchiveFile::setFile(filesystem::FilePtr file) -{ - LoggerD("Entered"); - m_file = file; +void ArchiveFile::setFile(filesystem::FilePtr file) { + LoggerD("Entered"); + m_file = file; } -bool ArchiveFile::isOverwrite() const -{ - return m_overwrite; +bool ArchiveFile::isOverwrite() const { + return m_overwrite; } -void ArchiveFile::setOverwrite(bool overwrite) -{ - LoggerD("Entered"); - m_overwrite = overwrite; +void ArchiveFile::setOverwrite(bool overwrite) { + LoggerD("Entered"); + m_overwrite = overwrite; } -unsigned long ArchiveFile::getDecompressedSize() const -{ - LoggerD("Entered"); - return m_decompressed_size; +unsigned long ArchiveFile::getDecompressedSize() const { + LoggerD("Entered"); + return m_decompressed_size; } -void ArchiveFile::setDecompressedSize(unsigned long decompressed_size) -{ - LoggerD("Entered"); - m_decompressed_size = decompressed_size; +void ArchiveFile::setDecompressedSize(unsigned long decompressed_size) { + LoggerD("Entered"); + m_decompressed_size = decompressed_size; } -bool ArchiveFile::isOpen() const -{ - LoggerD("Entered"); - return m_is_open; +bool ArchiveFile::isOpen() const { + LoggerD("Entered"); + return m_is_open; } -void ArchiveFile::setIsOpen(bool is_open) -{ - LoggerD("Entered"); - m_is_open = is_open; +void ArchiveFile::setIsOpen(bool is_open) { + LoggerD("Entered"); + m_is_open = is_open; } -ArchiveFileEntryPtrMapPtr ArchiveFile::getEntryMap() const -{ - LoggerD("Entered"); - return m_entry_map; +ArchiveFileEntryPtrMapPtr ArchiveFile::getEntryMap() const { + LoggerD("Entered"); + return m_entry_map; } -void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) -{ - LoggerD("Entered"); +void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) { + LoggerD("Entered"); - if(m_entry_map) { - LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(NULL); - } - } + if (m_entry_map) { + LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); + for (auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { + if (it->second) { + it->second->setArchiveFileNonProtectPtr(NULL); + } } + } - m_entry_map = entries; + m_entry_map = entries; - LoggerD("Linking new m_entry_map ArchiveFileEntries (%d) with ArchiveFile object", - m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(this); - } + LoggerD("Linking new m_entry_map ArchiveFileEntries (%d) with ArchiveFile object", + m_entry_map->size()); + for (auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { + if (it->second) { + it->second->setArchiveFileNonProtectPtr(this); } + } } -PlatformResult ArchiveFile::createUnZipObject(UnZipPtr* unzip) -{ - LoggerD("Entered"); - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); - } +PlatformResult ArchiveFile::createUnZipObject(UnZipPtr* unzip) { + LoggerD("Entered"); + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); + } - if (!m_file) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("m_file is null")); - } + if (!m_file) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("m_file is null")); + } - filesystem::NodePtr node = m_file->getNode(); - if(!node) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("Node is null")); - } + filesystem::NodePtr node = m_file->getNode(); + if (!node) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("Node is null")); + } - return UnZip::open(m_file->getNode()->getPath()->getFullPath(), unzip); + return UnZip::open(m_file->getNode()->getPath()->getFullPath(), unzip); } -PlatformResult ArchiveFile::createZipObject(ZipPtr* zip) -{ - LoggerD("Entered"); - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); - } +PlatformResult ArchiveFile::createZipObject(ZipPtr* zip) { + LoggerD("Entered"); + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); + } - if (!m_file) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("m_file is null")); - } + if (!m_file) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is null", ("m_file is null")); + } - filesystem::NodePtr node = m_file->getNode(); - if(!node) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node is null"); - } + filesystem::NodePtr node = m_file->getNode(); + if (!node) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Node is null"); + } - return Zip::open(m_file->getNode()->getPath()->getFullPath(), zip); + return Zip::open(m_file->getNode()->getPath()->getFullPath(), zip); } -bool ArchiveFile::isAllowedOperation(const std::string& method_name) -{ - LoggerD("Entered"); - PermissionMap::iterator it = s_permission_map.find(method_name); - if (it != s_permission_map.end()) { - return it->second.permission[m_file_mode]; - } - return false; +bool ArchiveFile::isAllowedOperation(const std::string& method_name) { + LoggerD("Entered"); + PermissionMap::iterator it = s_permission_map.find(method_name); + if (it != s_permission_map.end()) { + return it->second.permission[m_file_mode]; + } + return false; } -FileMode ArchiveFile::getFileMode() const -{ - LoggerD("Entered"); - return m_file_mode; +FileMode ArchiveFile::getFileMode() const { + LoggerD("Entered"); + return m_file_mode; } -void ArchiveFile::setFileMode(FileMode file_mode) -{ - LoggerD("Entered"); - m_file_mode = file_mode; +void ArchiveFile::setFileMode(FileMode file_mode) { + LoggerD("Entered"); + m_file_mode = file_mode; } -void ArchiveFile::setCreatedAsNewEmptyArchive(bool new_and_empty) -{ - LoggerD("Entered"); - m_created_as_new_empty_archive = new_and_empty; +void ArchiveFile::setCreatedAsNewEmptyArchive(bool new_and_empty) { + LoggerD("Entered"); + m_created_as_new_empty_archive = new_and_empty; } -bool ArchiveFile::isCreatedAsNewEmptyArchive() const -{ - LoggerD("Entered"); - return m_created_as_new_empty_archive; +bool ArchiveFile::isCreatedAsNewEmptyArchive() const { + LoggerD("Entered"); + return m_created_as_new_empty_archive; } -PlatformResult ArchiveFile::updateListOfEntries() -{ - LoggerD("Entered"); - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - unsigned long long size = 0; - PlatformResult result = m_file->getNode()->getSize(&size); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } +PlatformResult ArchiveFile::updateListOfEntries() { + LoggerD("Entered"); + // For explanation please see: + // ArchiveFile.h m_created_as_new_empty_archive description + // + unsigned long long size = 0; + PlatformResult result = m_file->getNode()->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } - if(size == 0) { - LoggerD("Zip file: %s is empty", - m_file->getNode()->getPath()->getFullPath().c_str()); + if (size == 0) { + LoggerD("Zip file: %s is empty", m_file->getNode()->getPath()->getFullPath().c_str()); - if(m_created_as_new_empty_archive) { - LoggerD("OK this is empty archive = nothing to do yet"); - return PlatformResult(ErrorCode::NO_ERROR); - } - else { - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive", ("m_created_as_new_empty_archive is false")); - } + if (m_created_as_new_empty_archive) { + LoggerD("OK this is empty archive = nothing to do yet"); + return PlatformResult(ErrorCode::NO_ERROR); + } else { + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive", + ("m_created_as_new_empty_archive is false")); } + } - UnZipPtr unzip; - result = createUnZipObject(&unzip); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerD("Fail createUnZipObject()"); - return result; - } + UnZipPtr unzip; + result = createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerD("Fail createUnZipObject()"); + return result; + } - unsigned long decompressedSize = 0; - ArchiveFileEntryPtrMapPtr emap; - result = unzip->listEntries(&decompressedSize, &emap); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerD("Fail unzip->listEntries()"); - return result; - } + unsigned long decompressedSize = 0; + ArchiveFileEntryPtrMapPtr emap; + result = unzip->listEntries(&decompressedSize, &emap); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerD("Fail unzip->listEntries()"); + return result; + } - setEntryMap(emap); - setDecompressedSize(decompressedSize); - return PlatformResult(ErrorCode::NO_ERROR); + setEntryMap(emap); + setDecompressedSize(decompressedSize); + return PlatformResult(ErrorCode::NO_ERROR); } -bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, - bool* out_is_directory, - std::string* out_matching_name) -{ - LoggerD("Enter"); +bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, bool* out_is_directory, + std::string* out_matching_name) { + LoggerD("Enter"); - if(!m_entry_map) { - LoggerW("m_entry_map is NULL"); - return false; - } - - const bool name_in_zip_is_dir = isDirectoryPath(name_in_zip); - bool set_is_directory = false; - bool set_name_exists = false; - - //Try exact name: - auto it = m_entry_map->find(name_in_zip); - if(it != m_entry_map->end()) { - set_is_directory = name_in_zip_is_dir; - set_name_exists = true; + if (!m_entry_map) { + LoggerW("m_entry_map is NULL"); + return false; + } + + const bool name_in_zip_is_dir = isDirectoryPath(name_in_zip); + bool set_is_directory = false; + bool set_name_exists = false; + + // Try exact name: + auto it = m_entry_map->find(name_in_zip); + if (it != m_entry_map->end()) { + set_is_directory = name_in_zip_is_dir; + set_name_exists = true; + } else { + if (name_in_zip_is_dir) { + // If name_in_zip is pointing at directory try file + it = m_entry_map->find(removeTrailingDirectorySlashFromPath(name_in_zip)); + set_is_directory = false; + } else { + // If name_in_zip is pointing at file try directory + it = m_entry_map->find(name_in_zip + "/"); + set_is_directory = true; } - else { - if(name_in_zip_is_dir) { - //If name_in_zip is pointing at directory try file - it = m_entry_map->find(removeTrailingDirectorySlashFromPath(name_in_zip)); - set_is_directory = false; - } else { - //If name_in_zip is pointing at file try directory - it = m_entry_map->find(name_in_zip + "/"); - set_is_directory = true; - } - if(it != m_entry_map->end()) { - set_name_exists = true; - } + if (it != m_entry_map->end()) { + set_name_exists = true; } + } - if(!set_name_exists) { - LoggerE("Fail: name do not exists"); - return false; - } + if (!set_name_exists) { + LoggerE("Fail: name do not exists"); + return false; + } - if(out_is_directory) { - *out_is_directory = set_is_directory; - } - if(out_matching_name) { - *out_matching_name = it->first; - } + if (out_is_directory) { + *out_is_directory = set_is_directory; + } + if (out_matching_name) { + *out_matching_name = it->first; + } - return true; + return true; } -} // archive -} // extension +} // archive +} // extension diff --git a/src/archive/archive_file.h b/src/archive/archive_file.h index c81b86d..f3c5095 100644 --- a/src/archive/archive_file.h +++ b/src/archive/archive_file.h @@ -18,16 +18,16 @@ #define _TIZEN_ARCHIVE_ARCHIVE_FILE_H_ #include +#include #include #include #include -#include #include "archive_callback_data.h" +#include "archive_file_entry.h" #include "filesystem_file.h" #include "un_zip.h" #include "zip.h" -#include "archive_file_entry.h" namespace extension { namespace archive { @@ -46,21 +46,13 @@ class ExtractEntryProgressCallback; class Zip; class ZipAddRequest; -enum FileMode { - READ = 0, - WRITE, - READ_WRITE, - ADD -}; +enum FileMode { READ = 0, WRITE, READ_WRITE, ADD }; -enum IsAllowed { - NOT_ALLOWED = false, - ALLOWED = true -}; +enum IsAllowed { NOT_ALLOWED = false, ALLOWED = true }; struct Permission { - Permission(bool r, bool w, bool rw, bool a); - bool permission[4]; + Permission(bool r, bool w, bool rw, bool a); + bool permission[4]; }; typedef std::shared_ptr ArchiveFilePtr; @@ -69,113 +61,113 @@ typedef std::vector ArchiveFileEntryPtrVector; typedef std::map PermissionMap; typedef std::pair PermissionPair; -struct ArchiveFileHolder{ - ArchiveFilePtr ptr; +struct ArchiveFileHolder { + ArchiveFilePtr ptr; }; class ArchiveFile : public std::enable_shared_from_this { -public: - ArchiveFile(); - ArchiveFile(FileMode file_mode); - virtual ~ArchiveFile(); - - common::PlatformResult getEntries(GetEntriesCallbackData* callback); - common::PlatformResult getEntryByName(GetEntryByNameCallbackData* callback); - common::PlatformResult extractAll(ExtractAllProgressCallback *callback); - common::PlatformResult add(AddProgressCallback *callback); - void close(); - - filesystem::FilePtr getFile() const; - void setFile(filesystem::FilePtr file); - bool isOverwrite() const; - void setOverwrite(bool overwrite); - unsigned long getDecompressedSize() const; - void setDecompressedSize(unsigned long decompressed_size); - bool isOpen() const; - void setIsOpen(bool is_open); - - ArchiveFileEntryPtrMapPtr getEntryMap() const; - void setEntryMap(ArchiveFileEntryPtrMapPtr entries); - bool isEntryWithNameInArchive(const std::string& name_in_zip, - bool* out_is_directory = NULL, - std::string* out_matching_name = NULL); - - //Used by ArchiveFileEntry - common::PlatformResult extractEntryTo(ExtractEntryProgressCallback* callback); - - bool isAllowedOperation(const std::string& method_name); - FileMode getFileMode() const; - void setFileMode(FileMode file_mode); - - void setCreatedAsNewEmptyArchive(bool new_and_empty); - bool isCreatedAsNewEmptyArchive() const; - - PlatformResult updateListOfEntries(); -private: - PlatformResult createUnZipObject(UnZipPtr* unzip); - PlatformResult createZipObject(ZipPtr* zip); - - std::deque m_task_queue; - std::mutex m_mutex; - - filesystem::FilePtr m_file; - - FileMode m_file_mode; - static PermissionMap s_permission_map; - - unsigned long m_decompressed_size; - bool m_is_open; - /** - * If set to true, during decompression archive will had permission to overwriting files. - * Warning: If decompressing file have got the same name as existing directory - * in place where file should be decompressed, directory will be deleted. - */ - bool m_overwrite; - ArchiveFileEntryPtrMapPtr m_entry_map; - - /** - * If we execute tizen.open(destFile , "w"/"rw"/ "a", ..., {overwrite: true}), - * destFile will be empty file with size = 0, which cannot be - * opened with minizip library. - * - * Zip file format restricts that at least one file / folder is compressed, - * threfore after creating new empty archive we cannot save it. - * Until we execute archive.add destFile is empty file with size 0 bytes. - * - * Unfortunately if we try to execute archive.getEntries or archive.extractAll - * minizip library will fail to open empty archive. To fix this issue we will - * use flag "created_as_new_empty_archive" which informs that this is new and - * empty archive threfore we should not try to open it. - * - * In extractAll we will just call success callback - there was nothing to extract - * but no error occured. In get entries we just should return empty list of entries. - */ - bool m_created_as_new_empty_archive; - - static gboolean openTaskCompleteCB(void *data); - static gboolean getEntriesTaskCompleteCB(void *data); - static gboolean getEntryByNameTaskCompleteCB(void *data); - - static void taskManagerThread(gpointer data, gpointer user_data); - common::PlatformResult addOperation(OperationCallbackData* callback); - static gboolean callErrorCallback(void* data); - - PlatformResult extractAllTask(ExtractAllProgressCallback* callback); - - friend class ExtractAllProgressCallback; - friend class UnZipExtractRequest; - friend class OpenCallbackData; - friend class GetEntriesCallbackData; - friend class GetEntryByNameCallbackData; - friend class ExtractEntryProgressCallback; - friend class ArchiveManager; - friend class AddProgressCallback; - friend class Zip; - friend class ZipAddRequest; - friend class BaseProgressCallback; + public: + ArchiveFile(); + ArchiveFile(FileMode file_mode); + virtual ~ArchiveFile(); + + common::PlatformResult getEntries(GetEntriesCallbackData* callback); + common::PlatformResult getEntryByName(GetEntryByNameCallbackData* callback); + common::PlatformResult extractAll(ExtractAllProgressCallback* callback); + common::PlatformResult add(AddProgressCallback* callback); + void close(); + + filesystem::FilePtr getFile() const; + void setFile(filesystem::FilePtr file); + bool isOverwrite() const; + void setOverwrite(bool overwrite); + unsigned long getDecompressedSize() const; + void setDecompressedSize(unsigned long decompressed_size); + bool isOpen() const; + void setIsOpen(bool is_open); + + ArchiveFileEntryPtrMapPtr getEntryMap() const; + void setEntryMap(ArchiveFileEntryPtrMapPtr entries); + bool isEntryWithNameInArchive(const std::string& name_in_zip, bool* out_is_directory = NULL, + std::string* out_matching_name = NULL); + + // Used by ArchiveFileEntry + common::PlatformResult extractEntryTo(ExtractEntryProgressCallback* callback); + + bool isAllowedOperation(const std::string& method_name); + FileMode getFileMode() const; + void setFileMode(FileMode file_mode); + + void setCreatedAsNewEmptyArchive(bool new_and_empty); + bool isCreatedAsNewEmptyArchive() const; + + PlatformResult updateListOfEntries(); + + private: + PlatformResult createUnZipObject(UnZipPtr* unzip); + PlatformResult createZipObject(ZipPtr* zip); + + std::deque m_task_queue; + std::mutex m_mutex; + + filesystem::FilePtr m_file; + + FileMode m_file_mode; + static PermissionMap s_permission_map; + + unsigned long m_decompressed_size; + bool m_is_open; + /** + * If set to true, during decompression archive will had permission to overwriting files. + * Warning: If decompressing file have got the same name as existing directory + * in place where file should be decompressed, directory will be deleted. + */ + bool m_overwrite; + ArchiveFileEntryPtrMapPtr m_entry_map; + + /** + * If we execute tizen.open(destFile , "w"/"rw"/ "a", ..., {overwrite: true}), + * destFile will be empty file with size = 0, which cannot be + * opened with minizip library. + * + * Zip file format restricts that at least one file / folder is compressed, + * threfore after creating new empty archive we cannot save it. + * Until we execute archive.add destFile is empty file with size 0 bytes. + * + * Unfortunately if we try to execute archive.getEntries or archive.extractAll + * minizip library will fail to open empty archive. To fix this issue we will + * use flag "created_as_new_empty_archive" which informs that this is new and + * empty archive threfore we should not try to open it. + * + * In extractAll we will just call success callback - there was nothing to extract + * but no error occured. In get entries we just should return empty list of entries. + */ + bool m_created_as_new_empty_archive; + + static gboolean openTaskCompleteCB(void* data); + static gboolean getEntriesTaskCompleteCB(void* data); + static gboolean getEntryByNameTaskCompleteCB(void* data); + + static void taskManagerThread(gpointer data, gpointer user_data); + common::PlatformResult addOperation(OperationCallbackData* callback); + static gboolean callErrorCallback(void* data); + + PlatformResult extractAllTask(ExtractAllProgressCallback* callback); + + friend class ExtractAllProgressCallback; + friend class UnZipExtractRequest; + friend class OpenCallbackData; + friend class GetEntriesCallbackData; + friend class GetEntryByNameCallbackData; + friend class ExtractEntryProgressCallback; + friend class ArchiveManager; + friend class AddProgressCallback; + friend class Zip; + friend class ZipAddRequest; + friend class BaseProgressCallback; }; -} // archive -} // extension +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/archive_file_entry.cc b/src/archive/archive_file_entry.cc old mode 100755 new mode 100644 index 6ead8af..d66a1c6 --- a/src/archive/archive_file_entry.cc +++ b/src/archive/archive_file_entry.cc @@ -30,142 +30,122 @@ namespace archive { static const unsigned int s_default_compression_level = 5; -ArchiveFileEntry::ArchiveFileEntry(filesystem::FilePtr file) : - std::enable_shared_from_this(), - m_file(file), - m_archive(NULL), - m_striped(false), - m_size(0), - m_compressed_size(0), - m_modified(0), - m_compression_level(s_default_compression_level) -{ - LoggerD("Entered"); +ArchiveFileEntry::ArchiveFileEntry(filesystem::FilePtr file) + : std::enable_shared_from_this(), + m_file(file), + m_archive(NULL), + m_striped(false), + m_size(0), + m_compressed_size(0), + m_modified(0), + m_compression_level(s_default_compression_level) { + LoggerD("Entered"); } -ArchiveFileEntry::~ArchiveFileEntry() -{ - LoggerD("Entered"); +ArchiveFileEntry::~ArchiveFileEntry() { + LoggerD("Entered"); } -unsigned long ArchiveFileEntry::getCompressedSize() const -{ - return m_compressed_size; +unsigned long ArchiveFileEntry::getCompressedSize() const { + return m_compressed_size; } -void ArchiveFileEntry::setCompressedSize(unsigned long compressed_size) -{ - m_compressed_size = compressed_size; +void ArchiveFileEntry::setCompressedSize(unsigned long compressed_size) { + m_compressed_size = compressed_size; } -filesystem::FilePtr ArchiveFileEntry::getFile() const -{ - return m_file; +filesystem::FilePtr ArchiveFileEntry::getFile() const { + return m_file; } -void ArchiveFileEntry::setFile(filesystem::FilePtr file) -{ - m_file = file; +void ArchiveFileEntry::setFile(filesystem::FilePtr file) { + m_file = file; } -unsigned long ArchiveFileEntry::getSize() const -{ - return m_size; +unsigned long ArchiveFileEntry::getSize() const { + return m_size; } -void ArchiveFileEntry::setSize(unsigned long size) -{ - m_size = size; +void ArchiveFileEntry::setSize(unsigned long size) { + m_size = size; } -const std::string& ArchiveFileEntry::getName() const -{ - return m_name; +const std::string& ArchiveFileEntry::getName() const { + return m_name; } -void ArchiveFileEntry::setName(const std::string& name) -{ - m_name = name; +void ArchiveFileEntry::setName(const std::string& name) { + m_name = name; } -void ArchiveFileEntry::setModified(time_t time) -{ - m_modified = time; +void ArchiveFileEntry::setModified(time_t time) { + m_modified = time; } -time_t ArchiveFileEntry::getModified() const -{ - return m_modified; +time_t ArchiveFileEntry::getModified() const { + return m_modified; } -const std::string& ArchiveFileEntry::getDestination() const -{ - return m_destination; +const std::string& ArchiveFileEntry::getDestination() const { + return m_destination; } -void ArchiveFileEntry::setDestination(const std::string& destination) -{ - m_destination = destination; +void ArchiveFileEntry::setDestination(const std::string& destination) { + m_destination = destination; } -bool ArchiveFileEntry::getStriped() const -{ - return m_striped; +bool ArchiveFileEntry::getStriped() const { + return m_striped; } -void ArchiveFileEntry::setStriped(bool striped) -{ - m_striped = striped; +void ArchiveFileEntry::setStriped(bool striped) { + m_striped = striped; } -void ArchiveFileEntry::setCompressionLevel(unsigned int level) -{ - m_compression_level = level; +void ArchiveFileEntry::setCompressionLevel(unsigned int level) { + m_compression_level = level; } -unsigned int ArchiveFileEntry::getCompressionLevel() const -{ - return m_compression_level; +unsigned int ArchiveFileEntry::getCompressionLevel() const { + return m_compression_level; } -void ArchiveFileEntry::setArchiveFileNonProtectPtr(ArchiveFile* ptr) -{ - m_archive = ptr; +void ArchiveFileEntry::setArchiveFileNonProtectPtr(ArchiveFile* ptr) { + m_archive = ptr; } -ArchiveFile* ArchiveFileEntry::getArchiveFileNonProtectPtr() -{ - return m_archive; +ArchiveFile* ArchiveFileEntry::getArchiveFileNonProtectPtr() { + return m_archive; } -PlatformResult ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) -{ - if(!m_archive) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("m_archive is NULL")); - } - - //Callback should be associated with this instance of ArchiveFileEntry - callback->setArchiveFileEntry(shared_from_this()); +PlatformResult ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) { + if (!m_archive) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", + ("m_archive is NULL")); + } - // - // If strip name was set in JS layer we need to generate srip base path - // - if(callback->getStripName()) { + // Callback should be associated with this instance of ArchiveFileEntry + callback->setArchiveFileEntry(shared_from_this()); - //Get base path - left side of last slash - std::string base_path_name = getBasePathFromPath(m_name); - if(!isDirectoryPath(base_path_name) && !base_path_name.empty()) { - base_path_name += "/"; - } + // + // If strip name was set in JS layer we need to generate srip base path + // + if (callback->getStripName()) { + // Get base path - left side of last slash + std::string base_path_name = getBasePathFromPath(m_name); + if (!isDirectoryPath(base_path_name) && !base_path_name.empty()) { + base_path_name += "/"; + } - LoggerD("strip name is: true; archive file entry name is: [%s]; " - "stripBasePath will be: [%s]", - m_name.c_str(), base_path_name.c_str()); + LoggerD( + "strip name is: true; archive file entry name is: [%s]; " + "stripBasePath will be: [%s]", + m_name.c_str(), base_path_name.c_str()); - callback->setStripBasePath(base_path_name); - } + callback->setStripBasePath(base_path_name); + } - return m_archive->extractEntryTo(callback); + return m_archive->extractEntryTo(callback); } -} // archive -} // extension +} // archive +} // extension diff --git a/src/archive/archive_file_entry.h b/src/archive/archive_file_entry.h index bbd72f8..bc9ba08 100644 --- a/src/archive/archive_file_entry.h +++ b/src/archive/archive_file_entry.h @@ -34,46 +34,46 @@ class ExtractEntryProgressCallback; typedef std::map ArchiveFileEntryPtrMap; typedef std::shared_ptr ArchiveFileEntryPtrMapPtr; -class ArchiveFileEntry : public std::enable_shared_from_this { -public: - ArchiveFileEntry(filesystem::FilePtr file = filesystem::FilePtr()); - ~ArchiveFileEntry(); +class ArchiveFileEntry : public std::enable_shared_from_this { + public: + ArchiveFileEntry(filesystem::FilePtr file = filesystem::FilePtr()); + ~ArchiveFileEntry(); - unsigned long getCompressedSize() const; - void setCompressedSize(unsigned long compressedSize); - filesystem::FilePtr getFile() const; - void setFile(filesystem::FilePtr file); - unsigned long getSize() const; - void setSize(unsigned long size); - const std::string& getName() const; - void setName(const std::string& name); - void setModified(time_t time); - time_t getModified() const; - const std::string& getDestination() const; - void setDestination(const std::string& destination); - bool getStriped() const; - void setStriped(bool striped); - void setCompressionLevel(unsigned int level); - unsigned int getCompressionLevel() const; + unsigned long getCompressedSize() const; + void setCompressedSize(unsigned long compressedSize); + filesystem::FilePtr getFile() const; + void setFile(filesystem::FilePtr file); + unsigned long getSize() const; + void setSize(unsigned long size); + const std::string& getName() const; + void setName(const std::string& name); + void setModified(time_t time); + time_t getModified() const; + const std::string& getDestination() const; + void setDestination(const std::string& destination); + bool getStriped() const; + void setStriped(bool striped); + void setCompressionLevel(unsigned int level); + unsigned int getCompressionLevel() const; - void setArchiveFileNonProtectPtr(ArchiveFile* ptr); - ArchiveFile* getArchiveFileNonProtectPtr(); + void setArchiveFileNonProtectPtr(ArchiveFile* ptr); + ArchiveFile* getArchiveFileNonProtectPtr(); - common::PlatformResult extractTo(ExtractEntryProgressCallback* callback); + common::PlatformResult extractTo(ExtractEntryProgressCallback* callback); -private: - filesystem::FilePtr m_file; - ArchiveFile* m_archive; - std::string m_name; - std::string m_destination; - bool m_striped; - unsigned long m_size; - unsigned long m_compressed_size; - time_t m_modified; - unsigned int m_compression_level; + private: + filesystem::FilePtr m_file; + ArchiveFile* m_archive; + std::string m_name; + std::string m_destination; + bool m_striped; + unsigned long m_size; + unsigned long m_compressed_size; + time_t m_modified; + unsigned int m_compression_level; }; -} // archive -} // extension +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/archive_instance.cc b/src/archive/archive_instance.cc old mode 100755 new mode 100644 index ce68703..6c26eda --- a/src/archive/archive_instance.cc +++ b/src/archive/archive_instance.cc @@ -18,17 +18,17 @@ //#include "archive_manager.h" +#include #include #include -#include -#include "common/current_application.h" -#include "common/picojson.h" -#include "common/logger.h" -#include "common/filesystem/filesystem_provider.h" -#include "common/tools.h" #include "archive_callback_data.h" #include "archive_manager.h" #include "archive_utils.h" +#include "common/current_application.h" +#include "common/filesystem/filesystem_provider.h" +#include "common/logger.h" +#include "common/picojson.h" +#include "common/tools.h" #include "defs.h" namespace extension { @@ -38,8 +38,8 @@ using common::tools::ReportSuccess; using common::tools::ReportError; namespace { -const std::string kPrivilegeFilesystemRead = "http://tizen.org/privilege/filesystem.read"; -const std::string kPrivilegeFilesystemWrite = "http://tizen.org/privilege/filesystem.write"; +const std::string kPrivilegeFilesystemRead = "http://tizen.org/privilege/filesystem.read"; +const std::string kPrivilegeFilesystemWrite = "http://tizen.org/privilege/filesystem.write"; const std::string kArchiveFileEntryOptDest = "destination"; const std::string kArchiveFileEntryOptStrip = "stripSourceDirectory"; @@ -50,577 +50,568 @@ const std::string kFastCompressionStr = "FAST"; const std::string kNormalCompressionStr = "NORMAL"; const std::string kBestCompressionStr = "BEST"; -} // namespace +} // namespace ArchiveInstance::ArchiveInstance() { - LoggerD("Entered"); + LoggerD("Entered"); - using std::placeholders::_1; - using std::placeholders::_2; + using std::placeholders::_1; + using std::placeholders::_2; - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&ArchiveInstance::x, this, _1, _2)); - #define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&ArchiveInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&ArchiveInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&ArchiveInstance::x, this, _1, _2)); - REGISTER_ASYNC("ArchiveManager_open", Open); - REGISTER_SYNC("ArchiveManager_abort", Abort); + REGISTER_ASYNC("ArchiveManager_open", Open); + REGISTER_SYNC("ArchiveManager_abort", Abort); - REGISTER_ASYNC("ArchiveFile_add", Add); - REGISTER_ASYNC("ArchiveFile_extractAll", ExtractAll); - REGISTER_ASYNC("ArchiveFile_getEntries", GetEntries); - REGISTER_ASYNC("ArchiveFile_getEntryByName", GetEntryByName); - REGISTER_SYNC("ArchiveFile_close", Close); + REGISTER_ASYNC("ArchiveFile_add", Add); + REGISTER_ASYNC("ArchiveFile_extractAll", ExtractAll); + REGISTER_ASYNC("ArchiveFile_getEntries", GetEntries); + REGISTER_ASYNC("ArchiveFile_getEntryByName", GetEntryByName); + REGISTER_SYNC("ArchiveFile_close", Close); - REGISTER_ASYNC("ArchiveFileEntry_extract", Extract); + REGISTER_ASYNC("ArchiveFileEntry_extract", Extract); - REGISTER_SYNC("Archive_fetchVirtualRoots", FetchVirtualRoots); + REGISTER_SYNC("Archive_fetchVirtualRoots", FetchVirtualRoots); - #undef REGISTER_ASYNC - #undef REGISTER_SYNC +#undef REGISTER_ASYNC +#undef REGISTER_SYNC } ArchiveInstance::~ArchiveInstance() { - LoggerD("Entered"); + LoggerD("Entered"); } void ArchiveInstance::PostError(const PlatformResult& e, double callback_id) { - LoggerD("Entered"); + LoggerD("Entered"); - LoggerE("Posting an error: %d, message: %s", e.error_code(), e.message().c_str()); + LoggerE("Posting an error: %d, message: %s", e.error_code(), e.message().c_str()); - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback_id); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback_id); - ReportError(e, &obj); + ReportError(e, &obj); - Instance::PostMessage(this, val.serialize().c_str()); + Instance::PostMessage(this, val.serialize().c_str()); } void ArchiveInstance::Open(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); - - picojson::object data = args.get(); - picojson::value v_file = data.at(PARAM_FILE); - picojson::value v_mode = data.at(PARAM_MODE); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::object options = data.at(PARAM_OPTIONS).get(); - picojson::value v_overwrite = options.at(PARAM_OVERWRITE); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - FileMode fm; - PlatformResult result = stringToFileMode(v_mode.get(), &fm); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("File mode conversions error"); - PostError(result, callbackId); - return; - } + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); + + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); + + picojson::object data = args.get(); + picojson::value v_file = data.at(PARAM_FILE); + picojson::value v_mode = data.at(PARAM_MODE); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::object options = data.at(PARAM_OPTIONS).get(); + picojson::value v_overwrite = options.at(PARAM_OVERWRITE); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + FileMode fm; + PlatformResult result = stringToFileMode(v_mode.get(), &fm); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("File mode conversions error"); + PostError(result, callbackId); + return; + } - OpenCallbackData *callback = new OpenCallbackData(*this); + OpenCallbackData* callback = new OpenCallbackData(*this); - FilePtr file_ptr; + FilePtr file_ptr; - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - bool overwrite = false; - if(v_overwrite.is()) { - overwrite = v_overwrite.get(); - } + bool overwrite = false; + if (v_overwrite.is()) { + overwrite = v_overwrite.get(); + } - std::string location_full_path = v_file.get(); - PathPtr path = Path::create(location_full_path); + std::string location_full_path = v_file.get(); + PathPtr path = Path::create(location_full_path); - struct stat info; - if (lstat(path->getFullPath().c_str(), &info) == 0) { - NodePtr node; - result = Node::resolve(path, &node); + struct stat info; + if (lstat(path->getFullPath().c_str(), &info) == 0) { + NodePtr node; + result = Node::resolve(path, &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } + + file_ptr = FilePtr(new File(node, File::PermissionList())); + LoggerD("open: %s mode: 0x%x overwrite: %d", location_full_path.c_str(), fm, overwrite); + if (FileMode::WRITE == fm || FileMode::READ_WRITE == fm) { + if (overwrite) { + LoggerD("Deleting existing file: %s", location_full_path.c_str()); + result = file_ptr->getNode()->remove(OPT_RECURSIVE); if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } - - file_ptr = FilePtr(new File(node, File::PermissionList())); - LoggerD("open: %s mode: 0x%x overwrite: %d", location_full_path.c_str(), fm, overwrite); - if (FileMode::WRITE == fm || FileMode::READ_WRITE == fm) { - if (overwrite) { - LoggerD("Deleting existing file: %s", location_full_path.c_str()); - result = file_ptr->getNode()->remove(OPT_RECURSIVE); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Couldn't remove existing file: %s", location_full_path.c_str()); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } - file_ptr.reset(); //We need to create new empty file - } else if (FileMode::WRITE == fm) { - SLoggerE("open: %s with mode: \"w\" file exists and overwrite is FALSE!", - location_full_path.c_str()); - PostError(PlatformResult(ErrorCode::INVALID_MODIFICATION_ERR, - "Zip archive already exists"), callbackId); - delete callback; - callback = NULL; - return; - } + LoggerE("Couldn't remove existing file: %s", location_full_path.c_str()); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; } + file_ptr.reset(); // We need to create new empty file + } else if (FileMode::WRITE == fm) { + SLoggerE("open: %s with mode: \"w\" file exists and overwrite is FALSE!", + location_full_path.c_str()); + PostError(PlatformResult(ErrorCode::INVALID_MODIFICATION_ERR, "Zip archive already exists"), + callbackId); + delete callback; + callback = NULL; + return; + } } + } - if (!file_ptr) { - NodePtr node_ptr; - - if (FileMode::WRITE == fm || - FileMode::READ_WRITE == fm || - FileMode::ADD == fm) { - LoggerD("Archive file not found - trying to create new one at: " - "full: %s", location_full_path.c_str()); - - std::string parent_path_string = path->getPath(); - PathPtr parent_path = Path::create(parent_path_string); - LoggerD("Parent path: %s", parent_path_string.c_str()); - - NodePtr parent_node; - PlatformResult result = Node::resolve(parent_path, &parent_node); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } - - parent_node->setPermissions(PERM_READ | PERM_WRITE); - std::string filename = path->getName(); - LoggerD("File name: %s", filename.c_str()); - result = parent_node->createChild(Path::create(filename), NT_FILE, &node_ptr); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } - } else { - LoggerE("Archive file not found"); - PostError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Archive file not found"), callbackId); - delete callback; - callback = NULL; - return; - } - file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); - } + if (!file_ptr) { + NodePtr node_ptr; - ArchiveFilePtr afp = ArchiveFilePtr(new ArchiveFile(fm)); - afp->setFile(file_ptr); - afp->setOverwrite(overwrite); - callback->setArchiveFile(afp); + if (FileMode::WRITE == fm || FileMode::READ_WRITE == fm || FileMode::ADD == fm) { + LoggerD( + "Archive file not found - trying to create new one at: " + "full: %s", + location_full_path.c_str()); - result = ArchiveManager::getInstance().open(callback); + std::string parent_path_string = path->getPath(); + PathPtr parent_path = Path::create(parent_path_string); + LoggerD("Parent path: %s", parent_path_string.c_str()); - if (result) { - ReportSuccess(out); + NodePtr parent_node; + PlatformResult result = Node::resolve(parent_path, &parent_node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } + + parent_node->setPermissions(PERM_READ | PERM_WRITE); + std::string filename = path->getName(); + LoggerD("File name: %s", filename.c_str()); + result = parent_node->createChild(Path::create(filename), NT_FILE, &node_ptr); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } } else { - LogAndReportError(result, &out, ("Failed to open archive.")); + LoggerE("Archive file not found"); + PostError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Archive file not found"), callbackId); + delete callback; + callback = NULL; + return; } + file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); + } + + ArchiveFilePtr afp = ArchiveFilePtr(new ArchiveFile(fm)); + afp->setFile(file_ptr); + afp->setOverwrite(overwrite); + callback->setArchiveFile(afp); + + result = ArchiveManager::getInstance().open(callback); + + if (result) { + ReportSuccess(out); + } else { + LogAndReportError(result, &out, ("Failed to open archive.")); + } } -void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); +void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); - picojson::object data = args.get(); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::object data = args.get(); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - const long op_id = static_cast(v_op_id.get()); + const long op_id = static_cast(v_op_id.get()); - ArchiveManager::getInstance().abort(op_id); + ArchiveManager::getInstance().abort(op_id); - ReportSuccess(out); + ReportSuccess(out); } unsigned int ConvertStringToCompressionLevel(const std::string& level) { LoggerD("Entered"); if (kNoCompressionStr == level) { - return Z_NO_COMPRESSION; + return Z_NO_COMPRESSION; } else if (kFastCompressionStr == level) { - return Z_BEST_SPEED; + return Z_BEST_SPEED; } else if (kBestCompressionStr == level) { - return Z_BEST_COMPRESSION; + return Z_BEST_COMPRESSION; } else { - return Z_DEFAULT_COMPRESSION; + return Z_DEFAULT_COMPRESSION; } } -void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); - - picojson::object data = args.get(); - picojson::value v_source = data.at(PARAM_SOURCE_FILE); - picojson::value v_options = data.at(PARAM_OPTIONS); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - const long handle = static_cast(v_handle.get()); - - AddProgressCallback *callback = new AddProgressCallback(*this); - - NodePtr node; - PlatformResult result = Node::resolve(Path::create(v_source.get()), &node); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } +void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); + + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); + + picojson::object data = args.get(); + picojson::value v_source = data.at(PARAM_SOURCE_FILE); + picojson::value v_options = data.at(PARAM_OPTIONS); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + const long handle = static_cast(v_handle.get()); + + AddProgressCallback* callback = new AddProgressCallback(*this); + + NodePtr node; + PlatformResult result = Node::resolve(Path::create(v_source.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - ArchiveFileEntryPtr afep = ArchiveFileEntryPtr(new ArchiveFileEntry(file_ptr)); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); + ArchiveFileEntryPtr afep = ArchiveFileEntryPtr(new ArchiveFileEntry(file_ptr)); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setFileEntry(afep); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setFileEntry(afep); - callback->setBasePath(file_ptr->getNode()->getPath()->getPath()); + callback->setBasePath(file_ptr->getNode()->getPath()->getPath()); - // check and set options - LoggerD("Processing OPTIONS dictionary: %s", v_options.serialize().c_str()); - const auto& dest = v_options.get(kArchiveFileEntryOptDest); - if (dest.is()) { - std::string dic_destination = dest.get(); - LoggerD("Setting destination path to: \"%s\"",dic_destination.c_str()); - afep->setDestination(dic_destination); - } + // check and set options + LoggerD("Processing OPTIONS dictionary: %s", v_options.serialize().c_str()); + const auto& dest = v_options.get(kArchiveFileEntryOptDest); + if (dest.is()) { + std::string dic_destination = dest.get(); + LoggerD("Setting destination path to: \"%s\"", dic_destination.c_str()); + afep->setDestination(dic_destination); + } - const auto& strip = v_options.get(kArchiveFileEntryOptStrip); - if (strip.is()) { - bool dic_strip = strip.get(); - LoggerD("Setting strip option to: %d", dic_strip); - afep->setStriped(dic_strip); - } + const auto& strip = v_options.get(kArchiveFileEntryOptStrip); + if (strip.is()) { + bool dic_strip = strip.get(); + LoggerD("Setting strip option to: %d", dic_strip); + afep->setStriped(dic_strip); + } - const auto& level = v_options.get(kArchiveFileEntryOptCompressionLevel); - if (level.is()) { - std::string dic_compression_level = level.get(); - LoggerD("Setting compression level to: \"%s\"", dic_compression_level.c_str()); - afep->setCompressionLevel(ConvertStringToCompressionLevel(dic_compression_level)); - } + const auto& level = v_options.get(kArchiveFileEntryOptCompressionLevel); + if (level.is()) { + std::string dic_compression_level = level.get(); + LoggerD("Setting compression level to: \"%s\"", dic_compression_level.c_str()); + afep->setCompressionLevel(ConvertStringToCompressionLevel(dic_compression_level)); + } - LoggerD("base path:%s base virt:%s", callback->getBasePath().c_str(), - callback->getBaseVirtualPath().c_str()); + LoggerD("base path:%s base virt:%s", callback->getBasePath().c_str(), + callback->getBaseVirtualPath().c_str()); - ArchiveFilePtr priv; - result = ArchiveManager::getInstance().getPrivData(handle, &priv); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + ArchiveFilePtr priv; + result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD)) { - LoggerE("Not allowed operation"); - delete callback; - callback = NULL; - return; - } + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; + } - result = priv->add(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + result = priv->add(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } } -void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); - - picojson::object data = args.get(); - picojson::value v_dest_dir = data.at(PARAM_DESTINATION_DIR); - picojson::value v_overwrite = data.at(PARAM_OVERWRITE); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - const long handle = static_cast(v_handle.get()); - - ExtractAllProgressCallback *callback = new ExtractAllProgressCallback(*this); - - NodePtr node; - PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } +void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); + + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); + + picojson::object data = args.get(); + picojson::value v_dest_dir = data.at(PARAM_DESTINATION_DIR); + picojson::value v_overwrite = data.at(PARAM_OVERWRITE); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + const long handle = static_cast(v_handle.get()); + + ExtractAllProgressCallback* callback = new ExtractAllProgressCallback(*this); + + NodePtr node; + PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - callback->setDirectory(file_ptr); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + callback->setDirectory(file_ptr); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - if (v_overwrite.is()) { - callback->setOverwrite(v_overwrite.get()); - } + if (v_overwrite.is()) { + callback->setOverwrite(v_overwrite.get()); + } - ArchiveFilePtr priv; - result = ArchiveManager::getInstance().getPrivData(handle, &priv); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + ArchiveFilePtr priv; + result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL)) { - LoggerE("Not allowed operation"); - delete callback; - callback = NULL; - return; - } + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; + } - result = priv->extractAll(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + result = priv->extractAll(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } } -void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); +void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); - picojson::object data = args.get(); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + picojson::object data = args.get(); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - const long handle = static_cast(v_handle.get()); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + const long handle = static_cast(v_handle.get()); - GetEntriesCallbackData *callback = new GetEntriesCallbackData(*this); + GetEntriesCallbackData* callback = new GetEntriesCallbackData(*this); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setHandle(handle); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setHandle(handle); - ArchiveFilePtr priv; - PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES)) { - LoggerE("Not allowed operation"); - delete callback; - callback = NULL; - return; - } + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; + } - result = priv->getEntries(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + result = priv->getEntries(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } } -void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); +void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); - picojson::object data = args.get(); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - picojson::value v_name = data.at(PARAM_NAME); + picojson::object data = args.get(); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + picojson::value v_name = data.at(PARAM_NAME); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - const long handle = static_cast(v_handle.get()); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + const long handle = static_cast(v_handle.get()); - GetEntryByNameCallbackData *callback = new GetEntryByNameCallbackData(*this); + GetEntryByNameCallbackData* callback = new GetEntryByNameCallbackData(*this); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setName(v_name.get()); - callback->setHandle(handle); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setName(v_name.get()); + callback->setHandle(handle); - ArchiveFilePtr priv; - PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME)) { - LoggerE("Not allowed operation"); - delete callback; - callback = NULL; - return; - } + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; + } - result = priv->getEntryByName(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + result = priv->getEntryByName(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } } -void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); +void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); - picojson::object data = args.get(); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + picojson::object data = args.get(); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - const long handle = static_cast(v_handle.get()); + const long handle = static_cast(v_handle.get()); - ArchiveFilePtr priv; - PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); - if (result.error_code() == ErrorCode::NO_ERROR) { - priv->close(); - ArchiveManager::getInstance().erasePrivData(handle); - } else { - LoggerD("Close method was called on already closed archive. Just end execution"); - LoggerD("%s", result.message().c_str()); - } + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() == ErrorCode::NO_ERROR) { + priv->close(); + ArchiveManager::getInstance().erasePrivData(handle); + } else { + LoggerD("Close method was called on already closed archive. Just end execution"); + LoggerD("%s", result.message().c_str()); + } - ReportSuccess(out); + ReportSuccess(out); } -void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out) -{ - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); - - picojson::object data = args.get(); - picojson::value v_dest_dir = data.at(PARAM_DESTINATION_DIR); - picojson::value v_strip_name = data.at(PARAM_STRIP_NAME); - picojson::value v_overwrite = data.at(PARAM_OVERWRITE); - picojson::value v_op_id = data.at(PARAM_OPERATION_ID); - picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); - picojson::value v_entry_name = data.at(PARAM_NAME); - - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - const long operationId = static_cast(v_op_id.get()); - const long handle = static_cast(v_handle.get()); - - ExtractEntryProgressCallback *callback = new ExtractEntryProgressCallback(*this); - - NodePtr node; - PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Filesystem exception - calling error callback"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } +void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); + + CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); + + picojson::object data = args.get(); + picojson::value v_dest_dir = data.at(PARAM_DESTINATION_DIR); + picojson::value v_strip_name = data.at(PARAM_STRIP_NAME); + picojson::value v_overwrite = data.at(PARAM_OVERWRITE); + picojson::value v_op_id = data.at(PARAM_OPERATION_ID); + picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); + picojson::value v_entry_name = data.at(PARAM_NAME); + + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(v_op_id.get()); + const long handle = static_cast(v_handle.get()); + + ExtractEntryProgressCallback* callback = new ExtractEntryProgressCallback(*this); + + NodePtr node; + PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - callback->setDirectory(file_ptr); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + callback->setDirectory(file_ptr); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - if (v_overwrite.is()) { - callback->setOverwrite(v_overwrite.get()); - } - if (v_strip_name.is()) { - callback->setStripName(v_strip_name.get()); - } + if (v_overwrite.is()) { + callback->setOverwrite(v_overwrite.get()); + } + if (v_strip_name.is()) { + callback->setStripName(v_strip_name.get()); + } - ArchiveFilePtr archive_file_ptr; - result = ArchiveManager::getInstance().getPrivData(handle, &archive_file_ptr); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - return; - } + ArchiveFilePtr archive_file_ptr; + result = ArchiveManager::getInstance().getPrivData(handle, &archive_file_ptr); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); - auto it = entries->find(v_entry_name.get()); + ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); + auto it = entries->find(v_entry_name.get()); - //Not found but if our name does not contain '/' - //try looking for directory with such name - if (entries->end() == it && !isDirectoryPath(v_entry_name.get())) { - const std::string try_directory = v_entry_name.get() + "/"; - LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); - it = entries->find(try_directory); - } + // Not found but if our name does not contain '/' + // try looking for directory with such name + if (entries->end() == it && !isDirectoryPath(v_entry_name.get())) { + const std::string try_directory = v_entry_name.get() + "/"; + LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); + it = entries->find(try_directory); + } - if (entries->end() == it) { - LoggerE("Failed to find entry"); - PostError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to find entry"), callbackId); - delete callback; - callback = NULL; - return; - } + if (entries->end() == it) { + LoggerE("Failed to find entry"); + PostError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to find entry"), callbackId); + delete callback; + callback = NULL; + return; + } - result = it->second->extractTo(callback); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("ArchiveFileEntry.extractTo error"); - PostError(result, callbackId); - delete callback; - callback = NULL; - return; - } + result = it->second->extractTo(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("ArchiveFileEntry.extractTo error"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } } void ArchiveInstance::FetchVirtualRoots(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + LoggerD("Entered"); - picojson::array roots; - for (const auto& root : common::FilesystemProvider::Create().GetVirtualPaths() ) { - roots.push_back(root.ToJson()); - } - ReportSuccess(picojson::value(roots), out); + picojson::array roots; + for (const auto& root : common::FilesystemProvider::Create().GetVirtualPaths()) { + roots.push_back(root.ToJson()); + } + ReportSuccess(picojson::value(roots), out); } -} // namespace archive -} // namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/archive_instance.h b/src/archive/archive_instance.h old mode 100755 new mode 100644 index 355aa92..8b55ebf --- a/src/archive/archive_instance.h +++ b/src/archive/archive_instance.h @@ -24,37 +24,37 @@ namespace extension { namespace archive { -class ArchiveInstance: public common::ParsedInstance { -public: - ArchiveInstance(); - virtual ~ArchiveInstance(); - -private: - ArchiveInstance(ArchiveInstance const&); - void operator=(ArchiveInstance const&); - - /* ArchiveManager methods */ - void Open(const picojson::value& args, picojson::object& out); - void Abort(const picojson::value& args, picojson::object& out); - - /* ArchiveFile methods */ - void Add(const picojson::value& args, picojson::object& out); - void ExtractAll(const picojson::value& args, picojson::object& out); - void GetEntries(const picojson::value& args, picojson::object& out); - void GetEntryByName(const picojson::value& args, picojson::object& out); - void Close(const picojson::value& args, picojson::object& out); - - /* ArchiveFileEntry methods */ - void Extract(const picojson::value& args, picojson::object& out); - - /* Filesystem related method */ - void FetchVirtualRoots(const picojson::value& args, picojson::object& out); - - void PostError(const common::PlatformException& e, double callback_id); - void PostError(const common::PlatformResult& e, double callback_id); +class ArchiveInstance : public common::ParsedInstance { + public: + ArchiveInstance(); + virtual ~ArchiveInstance(); + + private: + ArchiveInstance(ArchiveInstance const&); + void operator=(ArchiveInstance const&); + + /* ArchiveManager methods */ + void Open(const picojson::value& args, picojson::object& out); + void Abort(const picojson::value& args, picojson::object& out); + + /* ArchiveFile methods */ + void Add(const picojson::value& args, picojson::object& out); + void ExtractAll(const picojson::value& args, picojson::object& out); + void GetEntries(const picojson::value& args, picojson::object& out); + void GetEntryByName(const picojson::value& args, picojson::object& out); + void Close(const picojson::value& args, picojson::object& out); + + /* ArchiveFileEntry methods */ + void Extract(const picojson::value& args, picojson::object& out); + + /* Filesystem related method */ + void FetchVirtualRoots(const picojson::value& args, picojson::object& out); + + void PostError(const common::PlatformException& e, double callback_id); + void PostError(const common::PlatformResult& e, double callback_id); }; -} // namespace archive -} // namespace extension +} // namespace archive +} // namespace extension -#endif // ARCHIVE_ARCHIVE_INSTANCE_H_ +#endif // ARCHIVE_ARCHIVE_INSTANCE_H_ diff --git a/src/archive/archive_manager.cc b/src/archive/archive_manager.cc old mode 100755 new mode 100644 index bed9feb..45f6335 --- a/src/archive/archive_manager.cc +++ b/src/archive/archive_manager.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "archive_manager.h" #include #include "common/logger.h" @@ -24,106 +24,95 @@ namespace archive { using namespace filesystem; -ArchiveManager::ArchiveManager(): - m_next_unique_id(0) -{ - LoggerD("Initialize ArchiveManager"); - // create thread pool with max threads = 1 to make API calls async but - // only one call at time - m_pool = g_thread_pool_new(ArchiveFile::taskManagerThread, NULL, 1, true, NULL); +ArchiveManager::ArchiveManager() : m_next_unique_id(0) { + LoggerD("Initialize ArchiveManager"); + // create thread pool with max threads = 1 to make API calls async but + // only one call at time + m_pool = g_thread_pool_new(ArchiveFile::taskManagerThread, NULL, 1, true, NULL); } -ArchiveManager::~ArchiveManager() -{ - LoggerD("Deinitialize ArchiveManager"); - //finish only current task and wait for thread to stop - g_thread_pool_free(m_pool, true, true); +ArchiveManager::~ArchiveManager() { + LoggerD("Deinitialize ArchiveManager"); + // finish only current task and wait for thread to stop + g_thread_pool_free(m_pool, true, true); } -ArchiveManager& ArchiveManager::getInstance() -{ - LoggerD("Entered"); - static ArchiveManager instance; - return instance; +ArchiveManager& ArchiveManager::getInstance() { + LoggerD("Entered"); + static ArchiveManager instance; + return instance; } -GThreadPool* ArchiveManager::getThreadPool() -{ +GThreadPool* ArchiveManager::getThreadPool() { return m_pool; } -void ArchiveManager::abort(long operation_id) -{ - LoggerD("Entered"); - - ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); - if (it != m_archive_file_map.end()) { - ArchiveFilePtr archive_file_ptr = it->second; - std::lock_guard lock(archive_file_ptr->m_mutex); - - std::size_t size = archive_file_ptr->m_task_queue.size(); - for(std::size_t i = 0; i < size; ++i){ - if(operation_id == archive_file_ptr->m_task_queue[i].first){ - archive_file_ptr->m_task_queue[i].second->setIsCanceled(true); - return; - } - } +void ArchiveManager::abort(long operation_id) { + LoggerD("Entered"); + + ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); + if (it != m_archive_file_map.end()) { + ArchiveFilePtr archive_file_ptr = it->second; + std::lock_guard lock(archive_file_ptr->m_mutex); + + std::size_t size = archive_file_ptr->m_task_queue.size(); + for (std::size_t i = 0; i < size; ++i) { + if (operation_id == archive_file_ptr->m_task_queue[i].first) { + archive_file_ptr->m_task_queue[i].second->setIsCanceled(true); + return; + } } - LoggerD("The Operation Identifier not found"); + } + LoggerD("The Operation Identifier not found"); } -void ArchiveManager::erasePrivData(long handle) -{ - LoggerD("Entered"); +void ArchiveManager::erasePrivData(long handle) { + LoggerD("Entered"); - ArchiveFileMap::iterator it = m_priv_map.find(handle); - if (it != m_priv_map.end()) { - m_priv_map.erase(it); - } + ArchiveFileMap::iterator it = m_priv_map.find(handle); + if (it != m_priv_map.end()) { + m_priv_map.erase(it); + } } -long ArchiveManager::addPrivData(ArchiveFilePtr archive_file_ptr) -{ - LoggerD("Entered"); +long ArchiveManager::addPrivData(ArchiveFilePtr archive_file_ptr) { + LoggerD("Entered"); - long handle = ++m_next_unique_id; - m_priv_map.insert(ArchiveFilePair(handle, archive_file_ptr)); - return handle; + long handle = ++m_next_unique_id; + m_priv_map.insert(ArchiveFilePair(handle, archive_file_ptr)); + return handle; } -PlatformResult ArchiveManager::getPrivData(long handle, ArchiveFilePtr* archive_file) -{ - ArchiveFileMap::iterator it = m_priv_map.find(handle); - if (it != m_priv_map.end()) { - *archive_file = it->second; - return PlatformResult(ErrorCode::NO_ERROR); - } - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Priv is null"); +PlatformResult ArchiveManager::getPrivData(long handle, ArchiveFilePtr* archive_file) { + ArchiveFileMap::iterator it = m_priv_map.find(handle); + if (it != m_priv_map.end()) { + *archive_file = it->second; + return PlatformResult(ErrorCode::NO_ERROR); + } + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Priv is null"); } -PlatformResult ArchiveManager::open(OpenCallbackData* callback) -{ - LoggerD("Entered"); +PlatformResult ArchiveManager::open(OpenCallbackData* callback) { + LoggerD("Entered"); - //ArchiveFilePtr a_ptr = callback->getArchiveFile(); -// std::string filename = callback->getFile(); -// -// NodePtr node = Node::resolve(Path::create(filename)); -// FilePtr file_ptr = FilePtr(new File(node, std::vector(), filename)); -// ArchiveFilePtr a_ptr = ArchiveFilePtr(new ArchiveFile(FileMode::READ)); + // ArchiveFilePtr a_ptr = callback->getArchiveFile(); + // std::string filename = callback->getFile(); + // + // NodePtr node = Node::resolve(Path::create(filename)); + // FilePtr file_ptr = FilePtr(new File(node, std::vector(), filename)); + // ArchiveFilePtr a_ptr = ArchiveFilePtr(new ArchiveFile(FileMode::READ)); - ArchiveFilePtr a_ptr = callback->getArchiveFile(); - return a_ptr->addOperation(callback); + ArchiveFilePtr a_ptr = callback->getArchiveFile(); + return a_ptr->addOperation(callback); } -void ArchiveManager::eraseElementFromArchiveFileMap(long operation_id) -{ - LoggerD("Entered"); - ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); - if (it != m_archive_file_map.end()) { - m_archive_file_map.erase(it); - } +void ArchiveManager::eraseElementFromArchiveFileMap(long operation_id) { + LoggerD("Entered"); + ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); + if (it != m_archive_file_map.end()) { + m_archive_file_map.erase(it); + } } -} // archive -} // extension +} // archive +} // extension diff --git a/src/archive/archive_manager.h b/src/archive/archive_manager.h index fb9f19a..9cb66d5 100644 --- a/src/archive/archive_manager.h +++ b/src/archive/archive_manager.h @@ -17,13 +17,13 @@ #ifndef _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ #define _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ +#include #include #include #include -#include -#include "archive_file.h" #include "archive_callback_data.h" +#include "archive_file.h" namespace extension { namespace archive { @@ -32,33 +32,33 @@ typedef std::map ArchiveFileMap; typedef std::pair ArchiveFilePair; class ArchiveManager { -public: - static ArchiveManager& getInstance(); - ~ArchiveManager(); + public: + static ArchiveManager& getInstance(); + ~ArchiveManager(); - void abort(long operation_id); - void eraseElementFromArchiveFileMap(long operation_id); - void erasePrivData(long handle); - long addPrivData(ArchiveFilePtr archive_file_ptr); - common::PlatformResult getPrivData(long handle, ArchiveFilePtr* archive_file); - common::PlatformResult open(OpenCallbackData* callback); - GThreadPool* getThreadPool(); + void abort(long operation_id); + void eraseElementFromArchiveFileMap(long operation_id); + void erasePrivData(long handle); + long addPrivData(ArchiveFilePtr archive_file_ptr); + common::PlatformResult getPrivData(long handle, ArchiveFilePtr* archive_file); + common::PlatformResult open(OpenCallbackData* callback); + GThreadPool* getThreadPool(); -private: - ArchiveManager(); - ArchiveManager(ArchiveManager const&); - void operator=(ArchiveManager const&); + private: + ArchiveManager(); + ArchiveManager(ArchiveManager const&); + void operator=(ArchiveManager const&); - ArchiveFileMap m_archive_file_map; - ArchiveFileMap m_priv_map; + ArchiveFileMap m_archive_file_map; + ArchiveFileMap m_priv_map; - long m_next_unique_id; + long m_next_unique_id; - //! Handler for thread pool - GThreadPool* m_pool; + //! Handler for thread pool + GThreadPool* m_pool; }; -} // archive -} // extension +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ */ diff --git a/src/archive/archive_utils.cc b/src/archive/archive_utils.cc old mode 100755 new mode 100644 index 3961149..6976722 --- a/src/archive/archive_utils.cc +++ b/src/archive/archive_utils.cc @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "archive_utils.h" -#include #include +#include #include "common/logger.h" using namespace common; @@ -26,160 +26,147 @@ namespace archive { using namespace filesystem; -std::string bytesToReadableString(const size_t num_bytes) -{ - LoggerD("Enter"); - std::stringstream ss; - static const size_t one_mb = 1024 * 1024; - static const size_t one_kb = 1024; - ss << std::setprecision(2) << std::fixed; - - if(num_bytes >= one_mb) { - ss << (float)num_bytes / one_mb << " MB"; - } else if(num_bytes >= one_kb) { - ss << (float)num_bytes / one_kb << " KB"; - } else { - ss << num_bytes << " B"; - } - - return ss.str(); +std::string bytesToReadableString(const size_t num_bytes) { + LoggerD("Enter"); + std::stringstream ss; + static const size_t one_mb = 1024 * 1024; + static const size_t one_kb = 1024; + ss << std::setprecision(2) << std::fixed; + + if (num_bytes >= one_mb) { + ss << (float)num_bytes / one_mb << " MB"; + } else if (num_bytes >= one_kb) { + ss << (float)num_bytes / one_kb << " KB"; + } else { + ss << num_bytes << " B"; + } + + return ss.str(); } -PlatformResult fileModeToString(FileMode fm, std::string* fm_str) -{ - LoggerD("Enter"); - switch(fm) { - case FileMode::READ: - *fm_str = "r"; - break; - case FileMode::WRITE: - *fm_str = "w"; - break; - case FileMode::READ_WRITE: - *fm_str = "rw"; - break; - case FileMode::ADD: - *fm_str = "a"; - break; - default: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown file mode"); - } - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult fileModeToString(FileMode fm, std::string* fm_str) { + LoggerD("Enter"); + switch (fm) { + case FileMode::READ: + *fm_str = "r"; + break; + case FileMode::WRITE: + *fm_str = "w"; + break; + case FileMode::READ_WRITE: + *fm_str = "rw"; + break; + case FileMode::ADD: + *fm_str = "a"; + break; + default: + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown file mode"); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult stringToFileMode(std::string fmString, FileMode* fm) -{ - LoggerD("Enter"); - if (!fmString.compare("r")) { - *fm = FileMode::READ; - return PlatformResult(ErrorCode::NO_ERROR); - } - else if (!fmString.compare("w")) { - *fm = FileMode::WRITE; - return PlatformResult(ErrorCode::NO_ERROR); - } - else if(!fmString.compare("rw")) { - *fm = FileMode::READ_WRITE; - return PlatformResult(ErrorCode::NO_ERROR); - } - else if(!fmString.compare("a")) { - *fm = FileMode::ADD; - return PlatformResult(ErrorCode::NO_ERROR); - } - // In widl it's "TypeMismatchError" so this exception used - // instead of InvalidValues - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid FileMode"); +PlatformResult stringToFileMode(std::string fmString, FileMode* fm) { + LoggerD("Enter"); + if (!fmString.compare("r")) { + *fm = FileMode::READ; + return PlatformResult(ErrorCode::NO_ERROR); + } else if (!fmString.compare("w")) { + *fm = FileMode::WRITE; + return PlatformResult(ErrorCode::NO_ERROR); + } else if (!fmString.compare("rw")) { + *fm = FileMode::READ_WRITE; + return PlatformResult(ErrorCode::NO_ERROR); + } else if (!fmString.compare("a")) { + *fm = FileMode::ADD; + return PlatformResult(ErrorCode::NO_ERROR); + } + // In widl it's "TypeMismatchError" so this exception used + // instead of InvalidValues + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid FileMode"); } -void getBasePathAndName(const std::string& filepath, - std::string& out_basepath, - std::string& out_name) -{ - LoggerD("Enter"); - const size_t filepath_len = filepath.length(); - - size_t name_end_index = filepath_len; - size_t name_start_index = 0; - - for(int i = static_cast(filepath_len) - 1; i >= 0; --i) { - const char& cur = filepath[i]; - if(cur == '/' || cur == '\\') { - if((static_cast(filepath_len)-1) == i) { - name_end_index = static_cast(i); - } else { - name_start_index = static_cast(i) + 1; - out_name = filepath.substr(name_start_index, - name_end_index - name_start_index); - - out_basepath = filepath.substr(0, name_start_index); - return; - } - } +void getBasePathAndName(const std::string& filepath, std::string& out_basepath, + std::string& out_name) { + LoggerD("Enter"); + const size_t filepath_len = filepath.length(); + + size_t name_end_index = filepath_len; + size_t name_start_index = 0; + + for (int i = static_cast(filepath_len) - 1; i >= 0; --i) { + const char& cur = filepath[i]; + if (cur == '/' || cur == '\\') { + if ((static_cast(filepath_len) - 1) == i) { + name_end_index = static_cast(i); + } else { + name_start_index = static_cast(i) + 1; + out_name = filepath.substr(name_start_index, name_end_index - name_start_index); + + out_basepath = filepath.substr(0, name_start_index); + return; + } } + } - // \ / is not found - out_basepath = ""; - out_name = filepath.substr(0, name_end_index); + // \ / is not found + out_basepath = ""; + out_name = filepath.substr(0, name_end_index); } -std::string removeDuplicatedSlashesFromPath(const std::string& path) -{ - LoggerD("Enter"); - const size_t path_len = path.length(); - - std::string out; - out.reserve(path_len); - - bool prev_is_dir = false; - for(size_t i = 0; i < path_len; ++i) { - const char& cur = path[i]; - if(cur == '/' || cur == '\\') { - if(!prev_is_dir) { - out += cur; - } - prev_is_dir = true; - } else { - prev_is_dir = false; - out += cur; - } +std::string removeDuplicatedSlashesFromPath(const std::string& path) { + LoggerD("Enter"); + const size_t path_len = path.length(); + + std::string out; + out.reserve(path_len); + + bool prev_is_dir = false; + for (size_t i = 0; i < path_len; ++i) { + const char& cur = path[i]; + if (cur == '/' || cur == '\\') { + if (!prev_is_dir) { + out += cur; + } + prev_is_dir = true; + } else { + prev_is_dir = false; + out += cur; } + } - return out; + return out; } -bool isDirectoryPath(const std::string& path) -{ - LoggerD("Enter"); - if(path.empty()) { - return false; - } +bool isDirectoryPath(const std::string& path) { + LoggerD("Enter"); + if (path.empty()) { + return false; + } - const char last_char = path[path.length() - 1]; - return last_char == '\\' || last_char == '/'; + const char last_char = path[path.length() - 1]; + return last_char == '\\' || last_char == '/'; } -std::string removeTrailingDirectorySlashFromPath(const std::string& path) -{ - LoggerD("Enter"); - if(!isDirectoryPath(path)) { - return path; - } +std::string removeTrailingDirectorySlashFromPath(const std::string& path) { + LoggerD("Enter"); + if (!isDirectoryPath(path)) { + return path; + } - return path.substr(0, path.length() - 1); + return path.substr(0, path.length() - 1); } -std::string stripBasePathFromPath(const std::string& fullpath) -{ - LoggerD("Enter"); - const size_t location = fullpath.find_last_of("/\\"); - if(std::string::npos == location) { - return fullpath; - } +std::string stripBasePathFromPath(const std::string& fullpath) { + LoggerD("Enter"); + const size_t location = fullpath.find_last_of("/\\"); + if (std::string::npos == location) { + return fullpath; + } - return fullpath.substr(location + 1); + return fullpath.substr(location + 1); } -namespace{ +namespace { static std::string errErrno = "ERRNO"; static std::string errEndOfListOfFile = "End list of file"; static std::string errParamater = "Invalid parameter"; @@ -188,57 +175,54 @@ static std::string errInternal = "Internal error"; static std::string errCRC = "CRC error"; static std::string errUnknown = "Unknown error"; -const std::string& getArchiveErrorMessage(int errorCode) -{ - LoggerD("Enter"); - /** - * All errors are defined in minizip library in files: - * zip.h and unzip.h - */ - switch (errorCode) { - // ZIP_ERRNO & UNZ_ERRNO both value Z_ERRNO - case ZIP_ERRNO: - return errErrno; - // UNZ_END_OF_LIST_OF_FILE both value -100 - case UNZ_END_OF_LIST_OF_FILE: - return errEndOfListOfFile; - // ZIP_PARAMERROR & UNZ_PARAMERROR both value -102 - case ZIP_PARAMERROR: - return errParamater; - // ZIP_BADZIPFILE & UNZ_BADZIPFILE both value -103 - case ZIP_BADZIPFILE: - return errBadFile; - // ZIP_INTERNALERROR & UNZ_INTERNALERROR bot value -104 - case ZIP_INTERNALERROR: - return errInternal; - // UNZ_CRCERROR -105 - case UNZ_CRCERROR: - return errCRC; - default: - return errUnknown; - } +const std::string& getArchiveErrorMessage(int errorCode) { + LoggerD("Enter"); + /** + * All errors are defined in minizip library in files: + * zip.h and unzip.h + */ + switch (errorCode) { + // ZIP_ERRNO & UNZ_ERRNO both value Z_ERRNO + case ZIP_ERRNO: + return errErrno; + // UNZ_END_OF_LIST_OF_FILE both value -100 + case UNZ_END_OF_LIST_OF_FILE: + return errEndOfListOfFile; + // ZIP_PARAMERROR & UNZ_PARAMERROR both value -102 + case ZIP_PARAMERROR: + return errParamater; + // ZIP_BADZIPFILE & UNZ_BADZIPFILE both value -103 + case ZIP_BADZIPFILE: + return errBadFile; + // ZIP_INTERNALERROR & UNZ_INTERNALERROR bot value -104 + case ZIP_INTERNALERROR: + return errInternal; + // UNZ_CRCERROR -105 + case UNZ_CRCERROR: + return errCRC; + default: + return errUnknown; + } } } -std::string getBasePathFromPath(const std::string& fullpath) -{ - LoggerD("Enter"); - const std::string tmp_path = removeTrailingDirectorySlashFromPath(fullpath); - const size_t location = tmp_path.find_last_of("/\\"); - if(std::string::npos == location) { - return std::string(); - } +std::string getBasePathFromPath(const std::string& fullpath) { + LoggerD("Enter"); + const std::string tmp_path = removeTrailingDirectorySlashFromPath(fullpath); + const size_t location = tmp_path.find_last_of("/\\"); + if (std::string::npos == location) { + return std::string(); + } - return tmp_path.substr(0, location + 1); + return tmp_path.substr(0, location + 1); } -std::string getArchiveLogMessage(const int errorCode, const std::string &hint) -{ - LoggerD("Enter"); - std::stringstream ss; - ss << "Failed " << hint << " : " << getArchiveErrorMessage(errorCode) << ", " << errorCode; - return std::string(ss.str()); +std::string getArchiveLogMessage(const int errorCode, const std::string& hint) { + LoggerD("Enter"); + std::stringstream ss; + ss << "Failed " << hint << " : " << getArchiveErrorMessage(errorCode) << ", " << errorCode; + return std::string(ss.str()); } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/archive_utils.h b/src/archive/archive_utils.h old mode 100755 new mode 100644 index 1b9dcb3..74e7aa5 --- a/src/archive/archive_utils.h +++ b/src/archive/archive_utils.h @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ #define __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ #include +#include "archive_file.h" #include "common/platform_result.h" #include "filesystem_file.h" -#include "archive_file.h" namespace extension { namespace archive { @@ -43,9 +43,8 @@ common::PlatformResult stringToFileMode(std::string fmString, FileMode* fm); * "TEST/" | "" | "TEST" * "/TEST/" | "/" | "TEST" */ -void getBasePathAndName(const std::string& filepath, - std::string& out_basepath, - std::string& out_name); +void getBasePathAndName(const std::string& filepath, std::string& out_basepath, + std::string& out_name); /** * If path contains duplicated slashes they will be removed @@ -104,9 +103,9 @@ std::string stripBasePathFromPath(const std::string& fullpath); */ std::string getBasePathFromPath(const std::string& fullpath); -std::string getArchiveLogMessage(const int errorCode, const std::string &hint); +std::string getArchiveLogMessage(const int errorCode, const std::string& hint); -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension -#endif // __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ +#endif // __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ diff --git a/src/archive/defs.h b/src/archive/defs.h old mode 100755 new mode 100644 index f8dbf3d..0f6607a --- a/src/archive/defs.h +++ b/src/archive/defs.h @@ -17,44 +17,44 @@ #ifndef _ARCHIVE_PLUGIN_DEFS_H_ #define _ARCHIVE_PLUGIN_DEFS_H_ -#define TIZEN_ARCHIVE_ARCHIVE_CLASS "archive" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_ABORT "abort" -#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN "open" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD "add" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL "extractAll" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES "getEntries" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME "getEntryByName" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_CLOSE "close" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT "extract" - -#define JSON_ACTION "action" -#define JSON_CALLBACK_ID "callbackId" -#define JSON_LISTENER_ID "listenerId" -#define JSON_CALLBACK_PROGRESS "onprogress" -#define JSON_ONPROGRESS_CALLBACK "ArchiveOnprogressCallback" - -#define PARAM_FILE "file" -#define PARAM_MODE "mode" -#define PARAM_OPTIONS "options" -#define PARAM_SOURCE_FILE "sourceFile" -#define PARAM_DESTINATION_DIR "destinationDirectory" -#define PARAM_OVERWRITE "overwrite" -#define PARAM_NAME "name" -#define PARAM_STRIP_NAME "stripName" -#define PARAM_OPERATION_ID "opId" -#define PARAM_VALUE "value" -#define PARAM_FILENAME "filename" - -#define ARCHIVE_FILE_ATTR_MODE "mode" -#define ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE "decompressedSize" -#define ARCHIVE_FILE_HANDLE "handle" - -#define ARCHIVE_FILE_ENTRY_ATTR_NAME "name" -#define ARCHIVE_FILE_ENTRY_ATTR_SIZE "size" -#define ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE "compressedSize" -#define ARCHIVE_FILE_ENTRY_ATTR_MODIFIED "modified" - -#endif // _ARCHIVE_PLUGIN_DEFS_H_ +#define TIZEN_ARCHIVE_ARCHIVE_CLASS "archive" + +#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_ABORT "abort" +#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN "open" + +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD "add" +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL "extractAll" +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES "getEntries" +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME "getEntryByName" +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_CLOSE "close" + +#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT "extract" + +#define JSON_ACTION "action" +#define JSON_CALLBACK_ID "callbackId" +#define JSON_LISTENER_ID "listenerId" +#define JSON_CALLBACK_PROGRESS "onprogress" +#define JSON_ONPROGRESS_CALLBACK "ArchiveOnprogressCallback" + +#define PARAM_FILE "file" +#define PARAM_MODE "mode" +#define PARAM_OPTIONS "options" +#define PARAM_SOURCE_FILE "sourceFile" +#define PARAM_DESTINATION_DIR "destinationDirectory" +#define PARAM_OVERWRITE "overwrite" +#define PARAM_NAME "name" +#define PARAM_STRIP_NAME "stripName" +#define PARAM_OPERATION_ID "opId" +#define PARAM_VALUE "value" +#define PARAM_FILENAME "filename" + +#define ARCHIVE_FILE_ATTR_MODE "mode" +#define ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE "decompressedSize" +#define ARCHIVE_FILE_HANDLE "handle" + +#define ARCHIVE_FILE_ENTRY_ATTR_NAME "name" +#define ARCHIVE_FILE_ENTRY_ATTR_SIZE "size" +#define ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE "compressedSize" +#define ARCHIVE_FILE_ENTRY_ATTR_MODIFIED "modified" + +#endif // _ARCHIVE_PLUGIN_DEFS_H_ diff --git a/src/archive/filesystem_file.cc b/src/archive/filesystem_file.cc index ef6071e..9356a91 100644 --- a/src/archive/filesystem_file.cc +++ b/src/archive/filesystem_file.cc @@ -21,49 +21,40 @@ using namespace common; namespace extension { namespace filesystem { -File::File(NodePtr node, const File::PermissionList &parentPermissions, - const std::string& original_location) : - m_node(node), - m_parentPerms(parentPermissions) -{ - LoggerD("original_location is fullPath: %s", original_location.c_str()); - m_original_fullpath = original_location; +File::File(NodePtr node, const File::PermissionList& parentPermissions, + const std::string& original_location) + : m_node(node), m_parentPerms(parentPermissions) { + LoggerD("original_location is fullPath: %s", original_location.c_str()); + m_original_fullpath = original_location; } -File::~File() -{ - LoggerD("Enter"); +File::~File() { + LoggerD("Enter"); } -NodePtr File::getNode() const -{ - return m_node; +NodePtr File::getNode() const { + return m_node; } -File::PermissionList File::getParentPermissions() const -{ - return m_parentPerms; +File::PermissionList File::getParentPermissions() const { + return m_parentPerms; } -void File::setParentPermissions(const PermissionList &permissions) -{ - m_parentPerms = permissions; +void File::setParentPermissions(const PermissionList& permissions) { + m_parentPerms = permissions; } -void File::pushParentPermissions(int permissions) -{ - m_parentPerms.push_back(permissions); +void File::pushParentPermissions(int permissions) { + m_parentPerms.push_back(permissions); } -const std::string& File::getOriginalURI() const -{ - return m_original_URI; +const std::string& File::getOriginalURI() const { + return m_original_URI; } -const std::string& File::getOriginalFullPath() const -{ - return m_original_fullpath; +const std::string& File::getOriginalFullPath() const { + return m_original_fullpath; } -} // filesystem -} // extension +} // filesystem +} // extension diff --git a/src/archive/filesystem_file.h b/src/archive/filesystem_file.h index 752f6a1..6d97487 100644 --- a/src/archive/filesystem_file.h +++ b/src/archive/filesystem_file.h @@ -17,8 +17,8 @@ #ifndef _TIZEN_FILESYSTEM_FILE_H_ #define _TIZEN_FILESYSTEM_FILE_H_ -#include #include +#include #include #include "common/logger.h" @@ -31,32 +31,31 @@ namespace filesystem { class File; typedef std::shared_ptr FilePtr; -class File : public std::enable_shared_from_this -{ -public: - typedef std::vector PermissionList; - - File(NodePtr node, - const PermissionList &parentPermissions, - const std::string& original_location = std::string()); - virtual ~File(); - - NodePtr getNode() const; - PermissionList getParentPermissions() const; - void setParentPermissions(const PermissionList &permissions); - void pushParentPermissions(int permissions); - - const std::string& getOriginalURI() const; - const std::string& getOriginalFullPath() const; -private: - NodePtr m_node; - PermissionList m_parentPerms; - - std::string m_original_URI; - std::string m_original_fullpath; +class File : public std::enable_shared_from_this { + public: + typedef std::vector PermissionList; + + File(NodePtr node, const PermissionList& parentPermissions, + const std::string& original_location = std::string()); + virtual ~File(); + + NodePtr getNode() const; + PermissionList getParentPermissions() const; + void setParentPermissions(const PermissionList& permissions); + void pushParentPermissions(int permissions); + + const std::string& getOriginalURI() const; + const std::string& getOriginalFullPath() const; + + private: + NodePtr m_node; + PermissionList m_parentPerms; + + std::string m_original_URI; + std::string m_original_fullpath; }; -} // filesystem -} // extension +} // filesystem +} // extension #endif /* _TIZEN_FILESYSTEM_FILE_H_ */ diff --git a/src/archive/filesystem_node.cc b/src/archive/filesystem_node.cc index ef6683e..ee78266 100644 --- a/src/archive/filesystem_node.cc +++ b/src/archive/filesystem_node.cc @@ -15,21 +15,21 @@ */ #include "filesystem_node.h" -#include -#include -#include -#include -#include -#include #include #include #include -#include +#include +#include +#include +#include #include +#include +#include +#include -#include "filesystem_path.h" -#include "filesystem_node.h" #include "common/logger.h" +#include "filesystem_node.h" +#include "filesystem_path.h" namespace extension { namespace filesystem { @@ -37,591 +37,555 @@ namespace filesystem { using namespace common; #define MAX_NODE_LENGTH 256 -PlatformResult Node::checkPermission(const PathPtr &path, const std::string &mode, NodeType type, bool* granted) -{ - LoggerD("Enter"); - *granted = false; - - switch (type) - { - case NT_DIRECTORY: - { - DIR* dir = opendir(path->getFullPath().c_str()); - - if (!dir) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Node has been deleted from platform."); - } - - if (closedir(dir) != 0) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Could not close platform node."); - } - - if (mode == "r") { - *granted = true; - return PlatformResult(ErrorCode::NO_ERROR); - } - - std::stringstream ss; - time_t now; - time(&now); - ss << now; - PathPtr tempFilePath = Path::create(path->getFullPath()); - tempFilePath->append(ss.str()); - - PlatformResult result = createAsFileInternal(tempFilePath); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } - - result = removeAsFile(tempFilePath); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } - - if (mode == "rw" || mode == "w" || mode == "a") { - *granted = true; - return PlatformResult(ErrorCode::NO_ERROR); - } - - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); - } - break; - case NT_FILE: - { - std::fstream stream; - std::ios_base::openmode modeBit = std::fstream::binary; - - if (mode == "r") - { - modeBit |= std::fstream::in; - } - else if (mode == "rw" || mode == "w" || mode == "a") - { - modeBit |= std::fstream::app; - } - else - { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); - } - - stream.open(path->getFullPath().c_str(), modeBit); - - if (stream.is_open()) - { - stream.close(); - *granted = true; - } - return PlatformResult(ErrorCode::NO_ERROR); - } - break; - } - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Node::checkPermission(const PathPtr& path, const std::string& mode, NodeType type, + bool* granted) { + LoggerD("Enter"); + *granted = false; + + switch (type) { + case NT_DIRECTORY: { + DIR* dir = opendir(path->getFullPath().c_str()); + + if (!dir) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Node has been deleted from platform."); + } + + if (closedir(dir) != 0) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Could not close platform node."); + } + + if (mode == "r") { + *granted = true; + return PlatformResult(ErrorCode::NO_ERROR); + } + + std::stringstream ss; + time_t now; + time(&now); + ss << now; + PathPtr tempFilePath = Path::create(path->getFullPath()); + tempFilePath->append(ss.str()); + + PlatformResult result = createAsFileInternal(tempFilePath); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + + result = removeAsFile(tempFilePath); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + + if (mode == "rw" || mode == "w" || mode == "a") { + *granted = true; + return PlatformResult(ErrorCode::NO_ERROR); + } + + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); + } break; + case NT_FILE: { + std::fstream stream; + std::ios_base::openmode modeBit = std::fstream::binary; + + if (mode == "r") { + modeBit |= std::fstream::in; + } else if (mode == "rw" || mode == "w" || mode == "a") { + modeBit |= std::fstream::app; + } else { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); + } + + stream.open(path->getFullPath().c_str(), modeBit); + + if (stream.is_open()) { + stream.close(); + *granted = true; + } + return PlatformResult(ErrorCode::NO_ERROR); + } break; + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::resolve(const PathPtr& path, NodePtr* node) -{ - LoggerD("Entered path:[%s]", path->getFullPath().c_str()); - - struct stat info; - struct stat syminfo; - - if (lstat(path->getFullPath().c_str(), &info) != 0) { - LoggerE("File:[%s] error no:%d", path->getFullPath().c_str(), errno); - - switch (errno) - { - case EACCES: - SLoggerE("File: [%s]", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Node access denied"); - break; - case ENOENT: - SLoggerE("File: [%s]", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "NotFoundError"); - break; - default: - SLoggerE("File: [%s]", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Platform exception fail"); - } - } +PlatformResult Node::resolve(const PathPtr& path, NodePtr* node) { + LoggerD("Entered path:[%s]", path->getFullPath().c_str()); + + struct stat info; + struct stat syminfo; - if ((!S_ISDIR(info.st_mode)) & (!S_ISREG(info.st_mode)) && !S_ISLNK(info.st_mode)) { + if (lstat(path->getFullPath().c_str(), &info) != 0) { + LoggerE("File:[%s] error no:%d", path->getFullPath().c_str(), errno); + + switch (errno) { + case EACCES: SLoggerE("File: [%s]", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node is of unsupported type."); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Node access denied"); + break; + case ENOENT: + SLoggerE("File: [%s]", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "NotFoundError"); + break; + default: + SLoggerE("File: [%s]", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Platform exception fail"); } + } - NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; + if ((!S_ISDIR(info.st_mode)) & (!S_ISREG(info.st_mode)) && !S_ISLNK(info.st_mode)) { + SLoggerE("File: [%s]", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node is of unsupported type."); + } - if (S_ISLNK(info.st_mode)) { - PlatformResult result = stat(path, &syminfo); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } + NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; - type = S_ISDIR(syminfo.st_mode) ? NT_DIRECTORY : NT_FILE; - LoggerD("%x", type); + if (S_ISLNK(info.st_mode)) { + PlatformResult result = stat(path, &syminfo); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; } - *node = std::shared_ptr(new Node(path, type)); + type = S_ISDIR(syminfo.st_mode) ? NT_DIRECTORY : NT_FILE; + LoggerD("%x", type); + } - LoggerD("Finished execution for file:[%s] type:%s", path->getFullPath().c_str(), - type == NT_DIRECTORY ? "directory" : "file"); + *node = std::shared_ptr(new Node(path, type)); - return PlatformResult(ErrorCode::NO_ERROR); + LoggerD("Finished execution for file:[%s] type:%s", path->getFullPath().c_str(), + type == NT_DIRECTORY ? "directory" : "file"); + + return PlatformResult(ErrorCode::NO_ERROR); } -PathPtr Node::getPath() const -{ - return Path::create(m_path->getFullPath()); +PathPtr Node::getPath() const { + return Path::create(m_path->getFullPath()); } -PlatformResult Node::getChild(const PathPtr& path, NodePtr* node) -{ - LoggerD("Enter"); - if (m_type != NT_DIRECTORY) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory."); - } - return Node::resolve(*m_path + *path, node); +PlatformResult Node::getChild(const PathPtr& path, NodePtr* node) { + LoggerD("Enter"); + if (m_type != NT_DIRECTORY) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory."); + } + return Node::resolve(*m_path + *path, node); } -NodeType Node::getType() const -{ - return m_type; +NodeType Node::getType() const { + return m_type; } -int Node::getPermissions() const -{ - return m_perms; +int Node::getPermissions() const { + return m_perms; } -void Node::setPermissions(int perms) -{ - m_perms = perms; +void Node::setPermissions(int perms) { + m_perms = perms; } -PlatformResult Node::getChildNames(Node::NameList* out_name_list) const -{ - LoggerD("Enter"); - if (m_type != NT_DIRECTORY) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Node is not directory."); - } +PlatformResult Node::getChildNames(Node::NameList* out_name_list) const { + LoggerD("Enter"); + if (m_type != NT_DIRECTORY) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Node is not directory."); + } + + if ((m_perms & PERM_READ) == 0) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); + } + + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); + } + + errno = 0; + struct dirent* entry = nullptr; + NameList name_list; + while (nullptr != (entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + name_list.push_back(entry->d_name); + } + + if (closedir(dir) != 0) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Could not close platform node."); + } + + if (0 != errno) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Error while reading directory."); + } + + *out_name_list = name_list; + return PlatformResult(ErrorCode::NO_ERROR); +} - if ((m_perms & PERM_READ) == 0) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); - } +PlatformResult Node::getChildNodes(NodeList* out_node_list) const { + LoggerD("Enter"); - DIR* dir = opendir(m_path->getFullPath().c_str()); - if (!dir) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); - } + if (m_type != NT_DIRECTORY) { + SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return LogAndCreateResult(ErrorCode::IO_ERR, "Node is not directory."); + } - errno = 0; - struct dirent* entry = nullptr; - NameList name_list; - while (nullptr != (entry = readdir(dir))) { - if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { - continue; - } - name_list.push_back(entry->d_name); - } + if ((m_perms & PERM_READ) == 0) { + SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); + } - if (closedir(dir) != 0) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Could not close platform node."); - } + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return LogAndCreateResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); + } - if (0 != errno) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Error while reading directory."); + errno = 0; + struct dirent* entry = nullptr; + NodeList node_list; + while (nullptr != (entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; } - *out_name_list = name_list; - return PlatformResult(ErrorCode::NO_ERROR); -} + NodePtr node; + Node::resolve(*m_path + entry->d_name, &node); + node->setPermissions(getPermissions()); // inherit access rights + node_list.push_back(node); + } -PlatformResult Node::getChildNodes(NodeList* out_node_list) const -{ - LoggerD("Enter"); + if (closedir(dir) != 0) { + SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return LogAndCreateResult(ErrorCode::IO_ERR, "Could not close platform node."); + } - if (m_type != NT_DIRECTORY) { - SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); - return LogAndCreateResult(ErrorCode::IO_ERR, "Node is not directory."); - } - - if ((m_perms & PERM_READ) == 0) { - SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); - } + if (0 != errno) { + SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return LogAndCreateResult(ErrorCode::IO_ERR, "Error while reading directory."); + } - DIR* dir = opendir(m_path->getFullPath().c_str()); - if (!dir) { - SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); - return LogAndCreateResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); - } - - errno = 0; - struct dirent* entry = nullptr; - NodeList node_list; - while (nullptr != (entry = readdir(dir))) { - if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { - continue; - } + *out_node_list = node_list; - NodePtr node; - Node::resolve(*m_path + entry->d_name, &node); - node->setPermissions(getPermissions()); // inherit access rights - node_list.push_back(node); - } + return PlatformResult(ErrorCode::NO_ERROR); +} - if (closedir(dir) != 0) { - SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); - return LogAndCreateResult(ErrorCode::IO_ERR, "Could not close platform node."); - } +PlatformResult Node::createChild(const PathPtr& path, NodeType type, NodePtr* node, int options) { + LoggerD("Enter"); + if (m_type != NT_DIRECTORY) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Parent node is not a directory."); + } + + if ((m_perms & PERM_WRITE) == 0) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Not enough permissions."); + } + + PathPtr childPath = *m_path + *path; + bool existed; + PlatformResult result = exists(childPath, &existed); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: exists()"); + return result; + } + if (existed) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Node already exists."); + } + + switch (type) { + case NT_FILE: + result = createAsFile(childPath, node, options); + break; + case NT_DIRECTORY: + result = createAsDirectory(childPath, node, options); + break; + default: + return LogAndCreateResult(ErrorCode::IO_ERR, "Unsupported node type."); + } + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail CreateAs...()"); + return result; + } - if (0 != errno) { - SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); - return LogAndCreateResult(ErrorCode::IO_ERR, "Error while reading directory."); - } + if (!!(*node)) { + (*node)->m_perms = m_perms; + } else { + return LogAndCreateResult(ErrorCode::IO_ERR, "Node creation error"); + } - *out_node_list = node_list; + return PlatformResult(ErrorCode::NO_ERROR); +} - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Node::remove(int options) { + LoggerD("Enter"); + PlatformResult result(ErrorCode::NO_ERROR); + switch (m_type) { + case NT_FILE: + result = removeAsFile(m_path); + break; + case NT_DIRECTORY: + result = removeAsDirectory(m_path, (options & OPT_RECURSIVE)); + break; + default: + result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Not supported value of m_type"); + } + return result; } -PlatformResult Node::createChild( - const PathPtr& path, - NodeType type, - NodePtr* node, - int options) -{ - LoggerD("Enter"); - if (m_type != NT_DIRECTORY) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Parent node is not a directory."); - } +PlatformResult Node::getSize(unsigned long long* size) const { + LoggerD("Enter"); + if (m_type == NT_DIRECTORY) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Getting size for directories is not supported."); + } - if ((m_perms & PERM_WRITE) == 0) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Not enough permissions."); - } + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: stat()"); + return result; + } - PathPtr childPath = *m_path + *path; - bool existed; - PlatformResult result = exists(childPath, &existed); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: exists()"); - return result; - } - if (existed) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Node already exists."); - } + if (!S_ISREG(info.st_mode)) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Specified node is not a regular file."); + } - switch (type) { - case NT_FILE: - result = createAsFile(childPath, node, options); - break; - case NT_DIRECTORY: - result = createAsDirectory(childPath, node, options); - break; - default: - return LogAndCreateResult(ErrorCode::IO_ERR, "Unsupported node type."); - } - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail CreateAs...()"); - return result; - } + *size = static_cast(info.st_size); - if (!!(*node)) { - (*node)->m_perms = m_perms; - } else { - return LogAndCreateResult(ErrorCode::IO_ERR, "Node creation error"); - } + return PlatformResult(ErrorCode::NO_ERROR); +} - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Node::getCreated(std::time_t* time) const { + LoggerD("Enter"); + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: stat()"); + return result; + } + *time = info.st_ctime; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::remove(int options) -{ - LoggerD("Enter"); - PlatformResult result(ErrorCode::NO_ERROR); - switch (m_type) { - case NT_FILE: - result = removeAsFile(m_path); - break; - case NT_DIRECTORY: - result = removeAsDirectory(m_path, (options & OPT_RECURSIVE)); - break; - default: - result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Not supported value of m_type"); - } +PlatformResult Node::getModified(std::time_t* time) const { + LoggerD("Enter"); + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: stat()"); return result; + } + *time = info.st_mtime; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::getSize(unsigned long long* size) const -{ - LoggerD("Enter"); - if (m_type == NT_DIRECTORY) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Getting size for directories is not supported."); - } +PlatformResult Node::getParent(NodePtr* node) const { + LoggerD("Enter"); + + // LocationPaths roots = Manager::getInstance().getLocationPaths(); + // for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { + // if (*(*it) == *m_path) { + // return NodePtr(); + // } + // } + PlatformResult result = Node::resolve(Path::create(m_path->getPath()), node); + if (result.error_code() == ErrorCode::NO_ERROR) { + (*node)->setPermissions(getPermissions()); + } + + return result; +} - struct stat info; - PlatformResult result = stat(m_path, &info); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: stat()"); - return result; - } +PlatformResult Node::getMode(int* mode) const { + LoggerD("Enter"); - if (!S_ISREG(info.st_mode)) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Specified node is not a regular file."); + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() == ErrorCode::NO_ERROR) { + *mode = 0; + if (info.st_mode & S_IRUSR) { + *mode |= PM_USER_READ; } - - *size = static_cast(info.st_size); - - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Node::getCreated(std::time_t* time) const -{ - LoggerD("Enter"); - struct stat info; - PlatformResult result = stat(m_path, &info); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: stat()"); - return result; + if (info.st_mode & S_IWUSR) { + *mode |= PM_USER_WRITE; } - *time = info.st_ctime; - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Node::getModified(std::time_t* time) const -{ - LoggerD("Enter"); - struct stat info; - PlatformResult result = stat(m_path, &info); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: stat()"); - return result; + if (info.st_mode & S_IXUSR) { + *mode |= PM_USER_EXEC; } - *time = info.st_mtime; - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Node::getParent(NodePtr* node) const -{ - LoggerD("Enter"); - -// LocationPaths roots = Manager::getInstance().getLocationPaths(); -// for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { -// if (*(*it) == *m_path) { -// return NodePtr(); -// } -// } - PlatformResult result = Node::resolve(Path::create(m_path->getPath()), node); - if (result.error_code() == ErrorCode::NO_ERROR) { - (*node)->setPermissions(getPermissions()); + if (info.st_mode & S_IRGRP) { + *mode |= PM_GROUP_READ; } - - return result; -} - -PlatformResult Node::getMode(int* mode) const -{ - LoggerD("Enter"); - - struct stat info; - PlatformResult result = stat(m_path, &info); - if (result.error_code() == ErrorCode::NO_ERROR) { - *mode = 0; - if (info.st_mode & S_IRUSR) { *mode |= PM_USER_READ; } - if (info.st_mode & S_IWUSR) { *mode |= PM_USER_WRITE; } - if (info.st_mode & S_IXUSR) { *mode |= PM_USER_EXEC; } - if (info.st_mode & S_IRGRP) { *mode |= PM_GROUP_READ; } - if (info.st_mode & S_IWGRP) { *mode |= PM_GROUP_WRITE; } - if (info.st_mode & S_IXGRP) { *mode |= PM_GROUP_EXEC; } - if (info.st_mode & S_IROTH) { *mode |= PM_OTHER_READ; } - if (info.st_mode & S_IWOTH) { *mode |= PM_OTHER_WRITE; } - if (info.st_mode & S_IXOTH) { *mode |= PM_OTHER_EXEC; } + if (info.st_mode & S_IWGRP) { + *mode |= PM_GROUP_WRITE; } - return result; + if (info.st_mode & S_IXGRP) { + *mode |= PM_GROUP_EXEC; + } + if (info.st_mode & S_IROTH) { + *mode |= PM_OTHER_READ; + } + if (info.st_mode & S_IWOTH) { + *mode |= PM_OTHER_WRITE; + } + if (info.st_mode & S_IXOTH) { + *mode |= PM_OTHER_EXEC; + } + } + return result; } -PlatformResult Node::exists(const PathPtr& path, bool* existed) -{ - LoggerD("Enter"); +PlatformResult Node::exists(const PathPtr& path, bool* existed) { + LoggerD("Enter"); - struct stat info; - memset(&info, 0, sizeof(struct stat)); - int status = lstat(path->getFullPath().c_str(), &info); + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(path->getFullPath().c_str(), &info); - *existed = false; + *existed = false; - if (0 == status) - { - *existed = true; - return PlatformResult(ErrorCode::NO_ERROR); - } - else if (ENAMETOOLONG == errno) - { - return LogAndCreateResult(ErrorCode::IO_ERR, "file name is too long"); - } - else if (errno != ENOENT) - { - *existed = true; - return PlatformResult(ErrorCode::NO_ERROR); - } + if (0 == status) { + *existed = true; + return PlatformResult(ErrorCode::NO_ERROR); + } else if (ENAMETOOLONG == errno) { + return LogAndCreateResult(ErrorCode::IO_ERR, "file name is too long"); + } else if (errno != ENOENT) { + *existed = true; return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::stat(const PathPtr& path, struct stat* out_info) -{ - LoggerD("Enter"); - struct stat info; - memset(&info, 0, sizeof(struct stat)); - - if (::stat(path->getFullPath().c_str(), &info) != 0) - { - SLoggerE("File: %s", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Node does not exist or no access"); - } - *out_info = info; - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Node::stat(const PathPtr& path, struct stat* out_info) { + LoggerD("Enter"); + struct stat info; + memset(&info, 0, sizeof(struct stat)); + + if (::stat(path->getFullPath().c_str(), &info) != 0) { + SLoggerE("File: %s", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Node does not exist or no access"); + } + *out_info = info; + return PlatformResult(ErrorCode::NO_ERROR); } -Node::Node(const PathPtr& path, NodeType type): - m_path(path), - m_type(type), - m_perms(PERM_NONE) -{ - LoggerD("Enter"); +Node::Node(const PathPtr& path, NodeType type) : m_path(path), m_type(type), m_perms(PERM_NONE) { + LoggerD("Enter"); } -PlatformResult Node::createAsFile(const PathPtr& path, NodePtr* node, int /* options */) -{ - LoggerD("Enter"); +PlatformResult Node::createAsFile(const PathPtr& path, NodePtr* node, int /* options */) { + LoggerD("Enter"); - PlatformResult result = createAsFileInternal(path); - if (result.error_code() == ErrorCode::NO_ERROR) { - node->reset(new Node(path, NT_FILE)); - } - return result; + PlatformResult result = createAsFileInternal(path); + if (result.error_code() == ErrorCode::NO_ERROR) { + node->reset(new Node(path, NT_FILE)); + } + return result; } -PlatformResult Node::createAsFileInternal(const PathPtr& path) -{ - LoggerD("Enter"); +PlatformResult Node::createAsFileInternal(const PathPtr& path) { + LoggerD("Enter"); - FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); - if (!file) { - SLoggerE("fopen fails IOException throw for path [%s]", - path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node could not be created."); - } - std::fclose(file); - return PlatformResult(ErrorCode::NO_ERROR); + FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); + if (!file) { + SLoggerE("fopen fails IOException throw for path [%s]", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node could not be created."); + } + std::fclose(file); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::createAsDirectory(const PathPtr& path, NodePtr* node, int options) -{ - LoggerD("Enter"); - -// if (options & OPT_RECURSIVE) { -// auto parts = Utils::getParts(path); -// for (auto it = parts.begin(); it != parts.end(); ++it) { -// if (!exists(*it)) { createAsDirectoryInternal(*it); } -// } -// } - PlatformResult result = createAsDirectoryInternal(path); - if (result.error_code() == ErrorCode::NO_ERROR) { - node->reset(new Node(path, NT_DIRECTORY)); - } - return result; +PlatformResult Node::createAsDirectory(const PathPtr& path, NodePtr* node, int options) { + LoggerD("Enter"); + + // if (options & OPT_RECURSIVE) { + // auto parts = Utils::getParts(path); + // for (auto it = parts.begin(); it != parts.end(); ++it) { + // if (!exists(*it)) { createAsDirectoryInternal(*it); } + // } + // } + PlatformResult result = createAsDirectoryInternal(path); + if (result.error_code() == ErrorCode::NO_ERROR) { + node->reset(new Node(path, NT_DIRECTORY)); + } + return result; } -PlatformResult Node::createAsDirectoryInternal(const PathPtr& path) -{ - LoggerD("Enter"); +PlatformResult Node::createAsDirectoryInternal(const PathPtr& path) { + LoggerD("Enter"); - if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | - S_IXOTH) != 0) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node could not be created."); - } - return PlatformResult(ErrorCode::NO_ERROR); + if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node could not be created."); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::removeAsFile(const PathPtr& path) -{ - LoggerD("Enter"); +PlatformResult Node::removeAsFile(const PathPtr& path) { + LoggerD("Enter"); - auto fullPath = path->getFullPath(); - if (unlink(fullPath.c_str()) != 0) { - SLoggerE("remove [%s]", fullPath.c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Error while removing platform node."); - } - return PlatformResult(ErrorCode::NO_ERROR); + auto fullPath = path->getFullPath(); + if (unlink(fullPath.c_str()) != 0) { + SLoggerE("remove [%s]", fullPath.c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Error while removing platform node."); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Node::removeAsDirectory(const PathPtr& path, bool recursive) -{ - LoggerD("Enter"); +PlatformResult Node::removeAsDirectory(const PathPtr& path, bool recursive) { + LoggerD("Enter"); - if (recursive) { - DIR* dir = opendir(path->getFullPath().c_str()); - if (!dir) { - SLoggerE("File %s", path->getFullPath().c_str()); - return LogAndCreateResult(ErrorCode::IO_ERR, "Node does not exist or access denied."); + if (recursive) { + DIR* dir = opendir(path->getFullPath().c_str()); + if (!dir) { + SLoggerE("File %s", path->getFullPath().c_str()); + return LogAndCreateResult(ErrorCode::IO_ERR, "Node does not exist or access denied."); + } + struct dirent* entry = nullptr; + PlatformResult platform_result(ErrorCode::NO_ERROR); + while (nullptr != (entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + PathPtr subPath = *path + entry->d_name; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + if (lstat(subPath->getFullPath().c_str(), &info) == 0) { + if (S_ISDIR(info.st_mode)) { + platform_result = removeAsDirectory(subPath, true); + } else if (S_ISREG(info.st_mode)) { + platform_result = removeAsFile(subPath); } - struct dirent* entry = nullptr; - PlatformResult platform_result(ErrorCode::NO_ERROR); - while (nullptr != (entry = readdir(dir))) { - if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { - continue; - } - PathPtr subPath = *path + entry->d_name; - struct stat info; - memset(&info, 0, sizeof(struct stat)); - if (lstat(subPath->getFullPath().c_str(), &info) == 0) { - if (S_ISDIR(info.st_mode)) { - platform_result = removeAsDirectory(subPath, true); - } else if (S_ISREG(info.st_mode)) { - platform_result = removeAsFile(subPath); - } - if (platform_result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: getFullPath() (%d)",platform_result.error_code()); - closedir(dir); - return platform_result; - } - } + if (platform_result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: getFullPath() (%d)", platform_result.error_code()); + closedir(dir); + return platform_result; } - closedir(dir); + } } + closedir(dir); + } - errno = 0; - if (rmdir(path->getFullPath().c_str()) != 0) { - if (errno == EEXIST) { - return LogAndCreateResult(ErrorCode::IO_ERR, "Node has child nodes."); - } - return LogAndCreateResult(ErrorCode::IO_ERR, "Error while removing platform node."); + errno = 0; + if (rmdir(path->getFullPath().c_str()) != 0) { + if (errno == EEXIST) { + return LogAndCreateResult(ErrorCode::IO_ERR, "Node has child nodes."); } + return LogAndCreateResult(ErrorCode::IO_ERR, "Error while removing platform node."); + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -bool Node::isSubPath(std::string aDirPath, PathPtr aFilePath) -{ - LoggerD("Enter"); - auto myPath = aDirPath; - if(!myPath.empty() && myPath[myPath.length()-1] != Path::getSeparator()) { - myPath += Path::getSeparator(); - LoggerD("updated aDirPath to:%s", aDirPath.c_str()); - } +bool Node::isSubPath(std::string aDirPath, PathPtr aFilePath) { + LoggerD("Enter"); + auto myPath = aDirPath; + if (!myPath.empty() && myPath[myPath.length() - 1] != Path::getSeparator()) { + myPath += Path::getSeparator(); + LoggerD("updated aDirPath to:%s", aDirPath.c_str()); + } - auto childPath = aFilePath->getFullPath(); - bool isSubP = strncmp(myPath.c_str(), childPath.c_str(), myPath.size()) == 0; + auto childPath = aFilePath->getFullPath(); + bool isSubP = strncmp(myPath.c_str(), childPath.c_str(), myPath.size()) == 0; - LoggerD("aDirPath:%s myPath:%s aFilePath:%s isSubP:%d", - aDirPath.c_str(), - myPath.c_str(), - aFilePath->getFullPath().c_str(), - isSubP); + LoggerD("aDirPath:%s myPath:%s aFilePath:%s isSubP:%d", aDirPath.c_str(), myPath.c_str(), + aFilePath->getFullPath().c_str(), isSubP); - return isSubP; + return isSubP; } -} // filesystem -} // extension +} // filesystem +} // extension diff --git a/src/archive/filesystem_node.h b/src/archive/filesystem_node.h index a8b5299..f213057 100644 --- a/src/archive/filesystem_node.h +++ b/src/archive/filesystem_node.h @@ -17,103 +17,74 @@ #ifndef _FILESYSTEM_NODE_H_ #define _FILESYSTEM_NODE_H_ -#include -#include #include -#include +#include +#include +#include +#include #include #include +#include #include #include -#include -#include #include "common/platform_result.h" namespace extension { namespace filesystem { -enum LocationType -{ - LT_APPS, - LT_DOCUMENTS, - LT_DOWNLOADS, - LT_GAMES, - LT_IMAGES, - LT_OTHERS, - LT_ROOT, - LT_SDCARD, - LT_USBHOST, - LT_SOUNDS, - LT_TEMP, - LT_VIDEOS, - LT_RINGTONES, - LT_WGTPKG, - LT_WGTPRV, - LT_WGTPRVTMP, - LT_CAMERA +enum LocationType { + LT_APPS, + LT_DOCUMENTS, + LT_DOWNLOADS, + LT_GAMES, + LT_IMAGES, + LT_OTHERS, + LT_ROOT, + LT_SDCARD, + LT_USBHOST, + LT_SOUNDS, + LT_TEMP, + LT_VIDEOS, + LT_RINGTONES, + LT_WGTPKG, + LT_WGTPRV, + LT_WGTPRVTMP, + LT_CAMERA }; -enum NodeType -{ - NT_DIRECTORY, - NT_FILE -}; +enum NodeType { NT_DIRECTORY, NT_FILE }; -enum AccessMode -{ - AM_READ = 0x0001, - AM_WRITE = 0x0002, - AM_READ_WRITE = 0x0003, - AM_APPEND = 0x0004 -}; +enum AccessMode { AM_READ = 0x0001, AM_WRITE = 0x0002, AM_READ_WRITE = 0x0003, AM_APPEND = 0x0004 }; /** * Used in @see Manager::access(). */ -enum AccessType -{ - AT_EXISTS = 0x0000, //!< AT_EXISTS - checks for existence - AT_READ = 0x0001, //!< AT_READ - checks for read access - AT_WRITE = 0x0002, //!< AT_WRITE - checks for write access - AT_EXEC = 0x0004 //!< AT_EXEC - checks for execution access -}; - -enum Permissions -{ - PERM_NONE = 0x0000, - PERM_READ = 0x0001, - PERM_WRITE = 0x0002 +enum AccessType { + AT_EXISTS = 0x0000, //!< AT_EXISTS - checks for existence + AT_READ = 0x0001, //!< AT_READ - checks for read access + AT_WRITE = 0x0002, //!< AT_WRITE - checks for write access + AT_EXEC = 0x0004 //!< AT_EXEC - checks for execution access }; -enum PlatformMode -{ - PM_USER_READ = 0x0100, - PM_USER_WRITE = 0x0080, - PM_USER_EXEC = 0x0040, - PM_GROUP_READ = 0x0020, - PM_GROUP_WRITE = 0x0010, - PM_GROUP_EXEC = 0x0008, - PM_OTHER_READ = 0x0004, - PM_OTHER_WRITE = 0x0002, - PM_OTHER_EXEC = 0x0001, - PM_NONE = 0x0000 +enum Permissions { PERM_NONE = 0x0000, PERM_READ = 0x0001, PERM_WRITE = 0x0002 }; + +enum PlatformMode { + PM_USER_READ = 0x0100, + PM_USER_WRITE = 0x0080, + PM_USER_EXEC = 0x0040, + PM_GROUP_READ = 0x0020, + PM_GROUP_WRITE = 0x0010, + PM_GROUP_EXEC = 0x0008, + PM_OTHER_READ = 0x0004, + PM_OTHER_WRITE = 0x0002, + PM_OTHER_EXEC = 0x0001, + PM_NONE = 0x0000 }; -enum Options -{ - OPT_NONE = 0x0000, - OPT_OVERWRITE = 0x0001, - OPT_RECURSIVE = 0x0002 -}; +enum Options { OPT_NONE = 0x0000, OPT_OVERWRITE = 0x0001, OPT_RECURSIVE = 0x0002 }; -enum FindFilter -{ - FF_NAME, - FF_CREATED, - FF_MODIFIED, - FF_SIZE -}; +enum FindFilter { FF_NAME, FF_CREATED, FF_MODIFIED, FF_SIZE }; typedef std::map FiltersMap; class Node; @@ -124,133 +95,125 @@ typedef NodeList::iterator NodeListIterator; class Path; typedef std::shared_ptr PathPtr; -class Node : public std::enable_shared_from_this -{ -public: - typedef std::vector NameList; - typedef NameList::iterator NameListIterator; - - //! \brief Resolves Path into Node - //! - //! This function creates Node wich represent folder or file - //! in file system. - //! @param path virtual path in filesystem - //! @param node output pointer - //! @return a platform result - static common::PlatformResult resolve(const PathPtr& path, NodePtr* node); - //! \brief Checks if path can be accessed - //! - //! Function opens path and base at reqested mode and type verifies access - //! priviliges. If type is NT_DIRECTORY, then functions open directory. - //! If mode is readonly, then function returns true. If mode is other than - //! "r", then function checksm, if write is possible. If type is NT_FILE, - //! then function open file for read mode for "r" mode! and for R/W - //! for other mode. - //! - //! @param path virtual path in filesystem - //! @param mode access mode: "r", "rw" - //! @param type folder or file - //! @param granted true if access is granted, false if not - //! @return a platform result - common::PlatformResult checkPermission(const PathPtr& path, - const std::string& mode, - NodeType type, - bool* granted); - //! \brief Gets path of current node. - //! @return Node's path. - PathPtr getPath() const; - //! \brief Gets type of current node. - //! @return Node's type. - NodeType getType() const; - //! \brief Gets permissions of the virtual node (not real filesystem node). - //! @return Node's permissions. - int getPermissions() const; - //! \brief Sets permissions on the virtual node (not real filesystem node). - //! @param perms Node's permissions @see Api::Filesystem::Permissions. - void setPermissions(int perms); - //! \brief Gets size of this node. - //! @param size output size of a file. - //! @return a platform result. - common::PlatformResult getSize(unsigned long long* size) const; - //! \brief Gets creation date of this node. - //! @param time output date. - //! @return a platform result. - common::PlatformResult getCreated(std::time_t* time) const; - //! \brief Gets last modification date of this node. - //! @param time output date. - //! @return a platform result. - common::PlatformResult getModified(std::time_t* time) const; - //! \brief Gets parent of this node. - //! @param node the output node pointer or NULL if no parent (e.g. in case of a root node). - //! @return a platform result - common::PlatformResult getParent(NodePtr* node) const; - //! \brief Gets platform permissions. - //! @param mode output Platform permissions (set of flags from @see Permissions enum). - //! @return a platform result - common::PlatformResult getMode(int* mode) const; - //! \brief Gets direct child of this node. - //! @param path Path to the child node. - //! @param output Ptr to the child node. - //! @return a platform result - //! @remarks Ownership passed to the caller. - common::PlatformResult getChild(const PathPtr& path, NodePtr* node); - //! \brief Gets list of names of direct child nodes. - //! @param out_name_list the pointer to the list of nodes - //! @return a platform result - common::PlatformResult getChildNames(NameList* out_name_list) const; - //! \brief Gets list of direct child nodes. - //! @param out_node_list the pointer to the list of nodes - //! @return a platform result - //! @remarks Ownership passed to the caller. - //! @deprecated - common::PlatformResult getChildNodes(NodeList* out_node_list) const; - //! \brief Creates child of current node. - //! @param path Path to the node to create. - //! @param type Type of the node @see Api::Filesystem::NodeType. - //! @param node of the created file or directory - //! @param options Additional options see remarks (no options by default). - //! @return Ptr to newly created node. - //! @remarks - //! Valid options: - //! - OPT_RECURSIVE - attempt to create all necessary sub-directories - common::PlatformResult createChild( - const PathPtr& path, - NodeType, - NodePtr* node, - int options = OPT_NONE); - //! \brief Removes underlying filesystem node. - //! @param options Removal options (by default removal is recursive). - //! @return a platform result - //! @remarks Synchronous. - //! Valid options: - //! - OPT_RECURSIVE - remove node recursively. - common::PlatformResult remove(int options); - - static bool isSubPath(std::string aDirPath, PathPtr aFilePath); - -private: - static common::PlatformResult exists(const PathPtr& path, bool* existed); - static common::PlatformResult stat(const PathPtr& path, struct stat* out_info); - - Node(const PathPtr& path, NodeType type); - - common::PlatformResult createAsFile(const PathPtr& path, NodePtr* node, int options); - common::PlatformResult createAsFileInternal(const PathPtr& path); - - common::PlatformResult createAsDirectory(const PathPtr& path, NodePtr* node, int options); - common::PlatformResult createAsDirectoryInternal(const PathPtr& path); - - common::PlatformResult removeAsFile(const PathPtr& path); - common::PlatformResult removeAsDirectory(const PathPtr& path, bool recursive); - - PathPtr m_path; - NodeType m_type; - int m_perms; - +class Node : public std::enable_shared_from_this { + public: + typedef std::vector NameList; + typedef NameList::iterator NameListIterator; + + //! \brief Resolves Path into Node + //! + //! This function creates Node wich represent folder or file + //! in file system. + //! @param path virtual path in filesystem + //! @param node output pointer + //! @return a platform result + static common::PlatformResult resolve(const PathPtr& path, NodePtr* node); + //! \brief Checks if path can be accessed + //! + //! Function opens path and base at reqested mode and type verifies access + //! priviliges. If type is NT_DIRECTORY, then functions open directory. + //! If mode is readonly, then function returns true. If mode is other than + //! "r", then function checksm, if write is possible. If type is NT_FILE, + //! then function open file for read mode for "r" mode! and for R/W + //! for other mode. + //! + //! @param path virtual path in filesystem + //! @param mode access mode: "r", "rw" + //! @param type folder or file + //! @param granted true if access is granted, false if not + //! @return a platform result + common::PlatformResult checkPermission(const PathPtr& path, const std::string& mode, + NodeType type, bool* granted); + //! \brief Gets path of current node. + //! @return Node's path. + PathPtr getPath() const; + //! \brief Gets type of current node. + //! @return Node's type. + NodeType getType() const; + //! \brief Gets permissions of the virtual node (not real filesystem node). + //! @return Node's permissions. + int getPermissions() const; + //! \brief Sets permissions on the virtual node (not real filesystem node). + //! @param perms Node's permissions @see Api::Filesystem::Permissions. + void setPermissions(int perms); + //! \brief Gets size of this node. + //! @param size output size of a file. + //! @return a platform result. + common::PlatformResult getSize(unsigned long long* size) const; + //! \brief Gets creation date of this node. + //! @param time output date. + //! @return a platform result. + common::PlatformResult getCreated(std::time_t* time) const; + //! \brief Gets last modification date of this node. + //! @param time output date. + //! @return a platform result. + common::PlatformResult getModified(std::time_t* time) const; + //! \brief Gets parent of this node. + //! @param node the output node pointer or NULL if no parent (e.g. in case of a root node). + //! @return a platform result + common::PlatformResult getParent(NodePtr* node) const; + //! \brief Gets platform permissions. + //! @param mode output Platform permissions (set of flags from @see Permissions enum). + //! @return a platform result + common::PlatformResult getMode(int* mode) const; + //! \brief Gets direct child of this node. + //! @param path Path to the child node. + //! @param output Ptr to the child node. + //! @return a platform result + //! @remarks Ownership passed to the caller. + common::PlatformResult getChild(const PathPtr& path, NodePtr* node); + //! \brief Gets list of names of direct child nodes. + //! @param out_name_list the pointer to the list of nodes + //! @return a platform result + common::PlatformResult getChildNames(NameList* out_name_list) const; + //! \brief Gets list of direct child nodes. + //! @param out_node_list the pointer to the list of nodes + //! @return a platform result + //! @remarks Ownership passed to the caller. + //! @deprecated + common::PlatformResult getChildNodes(NodeList* out_node_list) const; + //! \brief Creates child of current node. + //! @param path Path to the node to create. + //! @param type Type of the node @see Api::Filesystem::NodeType. + //! @param node of the created file or directory + //! @param options Additional options see remarks (no options by default). + //! @return Ptr to newly created node. + //! @remarks + //! Valid options: + //! - OPT_RECURSIVE - attempt to create all necessary sub-directories + common::PlatformResult createChild(const PathPtr& path, NodeType, NodePtr* node, + int options = OPT_NONE); + //! \brief Removes underlying filesystem node. + //! @param options Removal options (by default removal is recursive). + //! @return a platform result + //! @remarks Synchronous. + //! Valid options: + //! - OPT_RECURSIVE - remove node recursively. + common::PlatformResult remove(int options); + + static bool isSubPath(std::string aDirPath, PathPtr aFilePath); + + private: + static common::PlatformResult exists(const PathPtr& path, bool* existed); + static common::PlatformResult stat(const PathPtr& path, struct stat* out_info); + + Node(const PathPtr& path, NodeType type); + + common::PlatformResult createAsFile(const PathPtr& path, NodePtr* node, int options); + common::PlatformResult createAsFileInternal(const PathPtr& path); + + common::PlatformResult createAsDirectory(const PathPtr& path, NodePtr* node, int options); + common::PlatformResult createAsDirectoryInternal(const PathPtr& path); + + common::PlatformResult removeAsFile(const PathPtr& path); + common::PlatformResult removeAsDirectory(const PathPtr& path, bool recursive); + + PathPtr m_path; + NodeType m_type; + int m_perms; }; -} // extension -} // filesystem +} // extension +} // filesystem #endif /* _FILESYSTEM_NODE_H_ */ - diff --git a/src/archive/filesystem_path.cc b/src/archive/filesystem_path.cc old mode 100755 new mode 100644 index 0b9a902..8bf7ab4 --- a/src/archive/filesystem_path.cc +++ b/src/archive/filesystem_path.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include -#include "filesystem_path.h" #include "common/logger.h" +#include "filesystem_path.h" namespace extension { namespace filesystem { @@ -33,158 +33,139 @@ namespace filesystem { const Path::SeparatorType Path::m_pathSeparator = '/'; std::string Path::replaceVirtualRootPath(const char* path) { - LoggerD("Enter"); + LoggerD("Enter"); - const char* old_path = "/opt/usr/media"; - char replace_path[MAX_PATH_SIZE] = {0, }; + const char* old_path = "/opt/usr/media"; + char replace_path[MAX_PATH_SIZE] = { + 0, + }; - if (strncmp(path, old_path, strlen(old_path)) == 0) { - snprintf(replace_path, MAX_PATH_SIZE, "%s%s", tzplatform_getenv(TZ_USER_CONTENT), - path + strlen(old_path)); - } else { - snprintf(replace_path, MAX_PATH_SIZE, "%s", path); - } + if (strncmp(path, old_path, strlen(old_path)) == 0) { + snprintf(replace_path, MAX_PATH_SIZE, "%s%s", tzplatform_getenv(TZ_USER_CONTENT), + path + strlen(old_path)); + } else { + snprintf(replace_path, MAX_PATH_SIZE, "%s", path); + } - return std::string(replace_path); + return std::string(replace_path); } -PathPtr Path::create(const std::string& path) -{ - LoggerD("Enter"); - auto result = std::shared_ptr(new Path()); - result->reset(replaceVirtualRootPath(path.c_str())); - return result; +PathPtr Path::create(const std::string& path) { + LoggerD("Enter"); + auto result = std::shared_ptr(new Path()); + result->reset(replaceVirtualRootPath(path.c_str())); + return result; } -std::string Path::getFullPath() const -{ - return m_fullPath; +std::string Path::getFullPath() const { + return m_fullPath; } -std::string Path::getPath() const -{ - return m_path; +std::string Path::getPath() const { + return m_path; } -std::string Path::getName() const -{ - return m_name; +std::string Path::getName() const { + return m_name; } -PathPtr Path::append(const std::string& path) -{ - reset(m_fullPath + m_pathSeparator + path); - return shared_from_this(); +PathPtr Path::append(const std::string& path) { + reset(m_fullPath + m_pathSeparator + path); + return shared_from_this(); } -PathPtr Path::append(const PathPtr& path) -{ - reset(m_fullPath + m_pathSeparator + path->getFullPath()); - return shared_from_this(); +PathPtr Path::append(const PathPtr& path) { + reset(m_fullPath + m_pathSeparator + path->getFullPath()); + return shared_from_this(); } -bool Path::isAbsolute() const -{ - return (!m_fullPath.empty() && (m_fullPath[0] == m_pathSeparator)); +bool Path::isAbsolute() const { + return (!m_fullPath.empty() && (m_fullPath[0] == m_pathSeparator)); } -Path::SeparatorType Path::getSeparator() -{ - return m_pathSeparator; +Path::SeparatorType Path::getSeparator() { + return m_pathSeparator; } -bool Path::isValid(const std::string& str) -{ - return !str.empty(); +bool Path::isValid(const std::string& str) { + return !str.empty(); } -PathPtr Path::clone() const -{ - return Path::create(m_fullPath); +PathPtr Path::clone() const { + return Path::create(m_fullPath); } -Path::Path() -{ +Path::Path() { } -void Path::reset(const std::string& str) -{ - LoggerD("Enter"); - if (!isValid(str)) { - LoggerD("Invalid string %s", str.c_str()); - LoggerW("throw NotFoundException"); - // The only way to remove throw statement from here is to just return, because - // this function is used in the operator functions and they're not able - // to handle a PlatformResult value; - return; - } -// std::string tmp = Commons::String::unique(/*Commons::String::trim*/( -// str), m_pathSeparator); - std::string tmp = str; +void Path::reset(const std::string& str) { + LoggerD("Enter"); + if (!isValid(str)) { + LoggerD("Invalid string %s", str.c_str()); + LoggerW("throw NotFoundException"); + // The only way to remove throw statement from here is to just return, because + // this function is used in the operator functions and they're not able + // to handle a PlatformResult value; + return; + } + // std::string tmp = Commons::String::unique(/*Commons::String::trim*/( + // str), m_pathSeparator); + std::string tmp = str; - if (m_pathSeparator == tmp.back()) { - tmp.erase(tmp.end() - 1, tmp.end()); - } - std::string::size_type pos = tmp.find_last_of(m_pathSeparator); - if (std::string::npos == pos) { - m_fullPath = m_name = tmp; - m_path.clear(); + if (m_pathSeparator == tmp.back()) { + tmp.erase(tmp.end() - 1, tmp.end()); + } + std::string::size_type pos = tmp.find_last_of(m_pathSeparator); + if (std::string::npos == pos) { + m_fullPath = m_name = tmp; + m_path.clear(); + } else { + if (0 == pos) { + m_fullPath = m_path = m_pathSeparator; } else { - if (0 == pos) { - m_fullPath = m_path = m_pathSeparator; - } else { - m_fullPath = m_path = tmp.substr(0, pos); - m_fullPath += m_pathSeparator; - } - m_name = tmp.substr(pos + 1); - m_fullPath += m_name; + m_fullPath = m_path = tmp.substr(0, pos); + m_fullPath += m_pathSeparator; } + m_name = tmp.substr(pos + 1); + m_fullPath += m_name; + } } -PathPtr operator+(const Path& lhs, const Path& rhs) -{ - return Path::create(lhs.getFullPath())->append(rhs.getFullPath()); +PathPtr operator+(const Path& lhs, const Path& rhs) { + return Path::create(lhs.getFullPath())->append(rhs.getFullPath()); } -PathPtr operator+(const Path& lhs, const std::string& rhs) -{ - return Path::create(lhs.getFullPath())->append(rhs); +PathPtr operator+(const Path& lhs, const std::string& rhs) { + return Path::create(lhs.getFullPath())->append(rhs); } -PathPtr operator+(const std::string& lhs, const Path& rhs) -{ - return Path::create(lhs)->append(rhs.getFullPath()); +PathPtr operator+(const std::string& lhs, const Path& rhs) { + return Path::create(lhs)->append(rhs.getFullPath()); } -bool operator==(const Path& lhs, const Path& rhs) -{ - return (lhs.getFullPath() == rhs.getFullPath()); +bool operator==(const Path& lhs, const Path& rhs) { + return (lhs.getFullPath() == rhs.getFullPath()); } -bool operator==(const Path& lhs, const std::string& rhs) -{ - return (lhs.getFullPath() == rhs); +bool operator==(const Path& lhs, const std::string& rhs) { + return (lhs.getFullPath() == rhs); } -bool operator==(const std::string& lhs, const Path& rhs) -{ - return (lhs == rhs.getFullPath()); +bool operator==(const std::string& lhs, const Path& rhs) { + return (lhs == rhs.getFullPath()); } -bool operator!=(const Path& lhs, const Path& rhs) -{ - return (lhs.getFullPath() != rhs.getFullPath()); +bool operator!=(const Path& lhs, const Path& rhs) { + return (lhs.getFullPath() != rhs.getFullPath()); } -bool operator!=(const Path& lhs, const std::string& rhs) -{ - return (lhs.getFullPath() != rhs); +bool operator!=(const Path& lhs, const std::string& rhs) { + return (lhs.getFullPath() != rhs); } -bool operator!=(const std::string& lhs, const Path& rhs) -{ - return (lhs != rhs.getFullPath()); +bool operator!=(const std::string& lhs, const Path& rhs) { + return (lhs != rhs.getFullPath()); } -} // filesystem -} // extension +} // filesystem +} // extension diff --git a/src/archive/filesystem_path.h b/src/archive/filesystem_path.h index 25ec731..8f77739 100644 --- a/src/archive/filesystem_path.h +++ b/src/archive/filesystem_path.h @@ -17,9 +17,9 @@ #ifndef _FILESYSTEM_PATH_H_ #define _FILESYSTEM_PATH_H_ +#include #include #include -#include namespace extension { namespace filesystem { @@ -27,34 +27,33 @@ namespace filesystem { class Path; typedef std::shared_ptr PathPtr; -class Path : public std::enable_shared_from_this -{ -public: - typedef char SeparatorType; - static PathPtr create(const std::string& path); - static Path::SeparatorType getSeparator(); - std::string getFullPath() const; - std::string getPath() const; - std::string getName() const; - PathPtr append(const std::string& path); - PathPtr append(const PathPtr& path); - bool isAbsolute() const; - PathPtr clone() const; - -private: - /** - * Checks whether specified string is a valid path. - * @param path String to verify. - * @return True when string is a valid path, false otherwise. - */ - static std::string replaceVirtualRootPath(const char* path); - static bool isValid(const std::string& str); - Path(); - void reset(const std::string& str); - static const SeparatorType m_pathSeparator; ///< Path separator. - std::string m_fullPath; ///< Full path. - std::string m_path; ///< Base path. - std::string m_name; ///< Last part of the path. +class Path : public std::enable_shared_from_this { + public: + typedef char SeparatorType; + static PathPtr create(const std::string& path); + static Path::SeparatorType getSeparator(); + std::string getFullPath() const; + std::string getPath() const; + std::string getName() const; + PathPtr append(const std::string& path); + PathPtr append(const PathPtr& path); + bool isAbsolute() const; + PathPtr clone() const; + + private: + /** + * Checks whether specified string is a valid path. + * @param path String to verify. + * @return True when string is a valid path, false otherwise. + */ + static std::string replaceVirtualRootPath(const char* path); + static bool isValid(const std::string& str); + Path(); + void reset(const std::string& str); + static const SeparatorType m_pathSeparator; ///< Path separator. + std::string m_fullPath; ///< Full path. + std::string m_path; ///< Base path. + std::string m_name; ///< Last part of the path. }; PathPtr operator+(const Path& lhs, const Path& rhs); @@ -75,8 +74,7 @@ bool operator!=(const Path& lhs, const std::string& rhs); bool operator!=(const std::string& lhs, const Path& rhs); - -} // filesystem -} // extension +} // filesystem +} // extension #endif /* _FILESYSTEM_PATH_H_ */ diff --git a/src/archive/un_zip.cc b/src/archive/un_zip.cc index 757992e..de34b5f 100644 --- a/src/archive/un_zip.cc +++ b/src/archive/un_zip.cc @@ -16,13 +16,13 @@ #include "un_zip.h" -#include #include +#include +#include +#include #include #include #include -#include -#include #include "common/logger.h" #include "common/platform_exception.h" @@ -39,425 +39,416 @@ namespace archive { using namespace common; using common::tools::GetErrorString; -UnZip::UnZip(const std::string& filename) : - m_zipfile_name(filename), - m_unzip(NULL), - m_default_buffer_size(1024 * 1024), - m_is_open(false) -{ - LoggerD("Entered"); - m_unzip = unzOpen(filename.c_str()); +UnZip::UnZip(const std::string& filename) + : m_zipfile_name(filename), + m_unzip(NULL), + m_default_buffer_size(1024 * 1024), + m_is_open(false) { + LoggerD("Entered"); + m_unzip = unzOpen(filename.c_str()); } -UnZip::~UnZip() -{ - LoggerD("Enter"); - for (auto& x: path_access_map) { - LoggerD("Setting permission for path: %s [%d] ", x.first.c_str(), x.second); - if(chmod(x.first.c_str(), x.second) == -1) { - LoggerE("Couldn't set permissions for: [%s] errno: %s", x.first.c_str(), - GetErrorString(errno).c_str()); - } +UnZip::~UnZip() { + LoggerD("Enter"); + for (auto& x : path_access_map) { + LoggerD("Setting permission for path: %s [%d] ", x.first.c_str(), x.second); + if (chmod(x.first.c_str(), x.second) == -1) { + LoggerE("Couldn't set permissions for: [%s] errno: %s", x.first.c_str(), + GetErrorString(errno).c_str()); } - close(); + } + close(); } -PlatformResult UnZip::close() -{ - LoggerD("Entered"); - if(!m_is_open) { - LoggerD("Unzip already closed - exiting"); - return PlatformResult(ErrorCode::NO_ERROR); - } - - int errclose = unzClose(m_unzip); - m_unzip = NULL; - - if (errclose != UNZ_OK) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "unzClose()"), ("ret: %d", errclose)); - } - m_is_open = false; +PlatformResult UnZip::close() { + LoggerD("Entered"); + if (!m_is_open) { + LoggerD("Unzip already closed - exiting"); return PlatformResult(ErrorCode::NO_ERROR); -} + } -PlatformResult UnZip::open(const std::string& filename, UnZipPtr* out_unzip) -{ - LoggerD("Entered"); - UnZipPtr unzip = UnZipPtr(new UnZip(filename)); + int errclose = unzClose(m_unzip); + m_unzip = NULL; - if(!unzip->m_unzip) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Failed to open zip file", ("unzOpen returned NULL : It means the file is invalid.")); - } - unzip->m_is_open = true; - *out_unzip = unzip; - return PlatformResult(ErrorCode::NO_ERROR); + if (errclose != UNZ_OK) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "unzClose()"), + ("ret: %d", errclose)); + } + m_is_open = false; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UnZip::listEntries(unsigned long *decompressedSize, ArchiveFileEntryPtrMapPtr* out_map) -{ - LoggerD("Enter"); - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get list of files in zip archive"); - } - unz_global_info gi; - int err = unzGetGlobalInfo (m_unzip, &gi); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetGlobalInfo()"), ("ret: %d", err)); - } - - char filename_inzip[512]; - unz_file_info file_info; - - ArchiveFileEntryPtrMapPtr map = ArchiveFileEntryPtrMapPtr(new ArchiveFileEntryPtrMap()); - - unsigned long totalDecompressed = 0; +PlatformResult UnZip::open(const std::string& filename, UnZipPtr* out_unzip) { + LoggerD("Entered"); + UnZipPtr unzip = UnZipPtr(new UnZip(filename)); + + if (!unzip->m_unzip) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Failed to open zip file", + ("unzOpen returned NULL : It means the file is invalid.")); + } + unzip->m_is_open = true; + *out_unzip = unzip; + return PlatformResult(ErrorCode::NO_ERROR); +} - err = unzGoToFirstFile(m_unzip); +PlatformResult UnZip::listEntries(unsigned long* decompressedSize, + ArchiveFileEntryPtrMapPtr* out_map) { + LoggerD("Enter"); + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get list of files in zip archive"); + } + unz_global_info gi; + int err = unzGetGlobalInfo(m_unzip, &gi); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGetGlobalInfo()"), ("ret: %d", err)); + } + + char filename_inzip[512]; + unz_file_info file_info; + + ArchiveFileEntryPtrMapPtr map = ArchiveFileEntryPtrMapPtr(new ArchiveFileEntryPtrMap()); + + unsigned long totalDecompressed = 0; + + err = unzGoToFirstFile(m_unzip); + if (err != UNZ_OK) { + LoggerW("%s", getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + } + + for (uLong i = 0; i < gi.number_entry; i++) { + err = unzGetCurrentFileInfo(m_unzip, &file_info, filename_inzip, sizeof(filename_inzip), NULL, + 0, NULL, 0); if (err != UNZ_OK) { - LoggerW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), + ("ret: %d", err)); } - for (uLong i = 0; i < gi.number_entry; i++) { - - err = unzGetCurrentFileInfo(m_unzip, &file_info, - filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); - if (err != UNZ_OK) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), ("ret: %d", err)); - } - - LoggerD("file: %s | unc size: %d | comp size: %d", filename_inzip, - file_info.uncompressed_size, file_info.compressed_size); - - ArchiveFileEntryPtr entry = ArchiveFileEntryPtr(new ArchiveFileEntry()); - entry->setName(filename_inzip); - entry->setSize(file_info.uncompressed_size); - entry->setCompressedSize(file_info.compressed_size); - - totalDecompressed += file_info.uncompressed_size; - - tm date;// = file_info.tmu_date; - date.tm_sec = file_info.tmu_date.tm_sec; - date.tm_min = file_info.tmu_date.tm_min; - date.tm_hour = file_info.tmu_date.tm_hour; - date.tm_mday = file_info.tmu_date.tm_mday; - date.tm_mon = file_info.tmu_date.tm_mon; - date.tm_year = file_info.tmu_date.tm_year - 1900; - date.tm_wday = 0; - date.tm_yday = 0; - date.tm_isdst = 0; - LoggerD("%d, %d, %d, %d, %d, %d", date.tm_hour, date.tm_min, date.tm_sec, date.tm_mday, date.tm_mon, date.tm_year); - entry->setModified(mktime(&date)); - - map->insert(std::make_pair(filename_inzip, entry)); - - if ( (i+1) < gi.number_entry) { - - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); - } - } + LoggerD("file: %s | unc size: %d | comp size: %d", filename_inzip, file_info.uncompressed_size, + file_info.compressed_size); + + ArchiveFileEntryPtr entry = ArchiveFileEntryPtr(new ArchiveFileEntry()); + entry->setName(filename_inzip); + entry->setSize(file_info.uncompressed_size); + entry->setCompressedSize(file_info.compressed_size); + + totalDecompressed += file_info.uncompressed_size; + + tm date; // = file_info.tmu_date; + date.tm_sec = file_info.tmu_date.tm_sec; + date.tm_min = file_info.tmu_date.tm_min; + date.tm_hour = file_info.tmu_date.tm_hour; + date.tm_mday = file_info.tmu_date.tm_mday; + date.tm_mon = file_info.tmu_date.tm_mon; + date.tm_year = file_info.tmu_date.tm_year - 1900; + date.tm_wday = 0; + date.tm_yday = 0; + date.tm_isdst = 0; + LoggerD("%d, %d, %d, %d, %d, %d", date.tm_hour, date.tm_min, date.tm_sec, date.tm_mday, + date.tm_mon, date.tm_year); + entry->setModified(mktime(&date)); + + map->insert(std::make_pair(filename_inzip, entry)); + + if ((i + 1) < gi.number_entry) { + err = unzGoToNextFile(m_unzip); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); + } } + } - (*decompressedSize) = totalDecompressed; + (*decompressedSize) = totalDecompressed; - *out_map = map; + *out_map = map; - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult UnZip::extractAllFilesTo(const std::string& extract_path, - ExtractAllProgressCallback* callback) -{ - LoggerD("Enter"); - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract zip archive"); - } - - // - // Calculate number of entries to extract and total number of bytes - // - unz_global_info gi; - PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; + ExtractAllProgressCallback* callback) { + LoggerD("Enter"); + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract zip archive"); + } + + // + // Calculate number of entries to extract and total number of bytes + // + unz_global_info gi; + PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; + } + + // + // Begin extracting entries + // + int err = unzGoToFirstFile(m_unzip); + if (err != UNZ_OK) { + LoggerE("%s", getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + } + + for (uLong i = 0; i < gi.number_entry; i++) { + if (callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); } - // - // Begin extracting entries - // - int err = unzGoToFirstFile(m_unzip); - if (err != UNZ_OK) { - LoggerE("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + result = extractCurrentFile(extract_path, std::string(), callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: extractCurrentFile()"); + return result; } - for (uLong i = 0; i < gi.number_entry; i++) { - - if (callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } - - result = extractCurrentFile(extract_path, std::string(), callback); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: extractCurrentFile()"); - return result; - } - - if ((i + 1) < gi.number_entry) { - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); - } - } + if ((i + 1) < gi.number_entry) { + err = unzGoToNextFile(m_unzip); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); + } } + } - callback->callSuccessCallbackOnMainThread(); + callback->callSuccessCallbackOnMainThread(); - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -struct ExtractDataHolder -{ - UnZip* unzip; - ExtractEntryProgressCallback* callback; - std::string root_output_path; +struct ExtractDataHolder { + UnZip* unzip; + ExtractEntryProgressCallback* callback; + std::string root_output_path; }; -PlatformResult UnZip::extractTo(ExtractEntryProgressCallback* callback) -{ - LoggerD("Enter"); - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); - } - - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed", ("callback is NULL")); - } +PlatformResult UnZip::extractTo(ExtractEntryProgressCallback* callback) { + LoggerD("Enter"); + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); + } + + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed", + ("callback is NULL")); + } + + if (!callback->getArchiveFileEntry()) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed", + ("callback->getArchiveFileEntry() is NULL")); + } + + filesystem::FilePtr out_dir = callback->getDirectory(); + if (!out_dir) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); + } + + NodePtr out_node = out_dir->getNode(); + if (!out_node) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); + } + + PathPtr out_path = out_node->getPath(); + if (!out_path) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); + } + + auto entry_name_in_zip = callback->getArchiveFileEntry()->getName(); + auto root_output_path = out_dir->getNode()->getPath()->getFullPath(); + LoggerD("Extract: [%s] to root output directory: [%s] (stripBasePath: [%s])", + entry_name_in_zip.c_str(), root_output_path.c_str(), + callback->getStripBasePath().c_str()); + + // + // Calculate number of entries to extract and total number of bytes + // + unz_global_info gi; + PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi, entry_name_in_zip); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: updateCallbackWithArchiveStatistics()"); + return result; + } + + // + // Begin extracting entries + // + + ExtractDataHolder h; + h.unzip = this; + h.callback = callback; + h.root_output_path = root_output_path; + + // this loop call internally progress callbacks + unsigned int matched; + result = IterateFilesInZip(gi, entry_name_in_zip, callback, extractItFunction, matched, &h); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Fail: IterateFilesInZip()"); + return result; + } + + // after finish extracting success callback will be called + callback->callSuccessCallbackOnMainThread(); + + return PlatformResult(ErrorCode::NO_ERROR); +} - if(!callback->getArchiveFileEntry()) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed", ("callback->getArchiveFileEntry() is NULL")); - } +PlatformResult UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, + void* user_data) { + LoggerD("Enter"); + ExtractDataHolder* h = static_cast(user_data); + if (!h) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not list content of zip archive", + ("ExtractDataHolder is NULL!")); + } + + PlatformResult result = h->unzip->extractCurrentFile( + h->root_output_path, h->callback->getStripBasePath(), h->callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; + } + return PlatformResult(ErrorCode::NO_ERROR); +} - filesystem::FilePtr out_dir = callback->getDirectory(); - if(!out_dir) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); - } +PlatformResult UnZip::IterateFilesInZip(unz_global_info& gi, const std::string& entry_name_in_zip, + OperationCallbackData* callback, + UnZip::IterateFunction itfunc, + unsigned int& num_file_or_folder_matched, void* user_data) { + LoggerD("Enter"); + int err = unzGoToFirstFile(m_unzip); + if (UNZ_OK != err) { + LoggerW("%s", getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + } - NodePtr out_node = out_dir->getNode(); - if(!out_node) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); - } + num_file_or_folder_matched = 0; + const bool is_directory = isDirectoryPath(entry_name_in_zip); - PathPtr out_path = out_node->getPath(); - if(!out_path) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); - } + unz_file_info cur_file_info; + char tmp_fname[512]; - auto entry_name_in_zip = callback->getArchiveFileEntry()->getName(); - auto root_output_path = out_dir->getNode()->getPath()->getFullPath(); - LoggerD("Extract: [%s] to root output directory: [%s] (stripBasePath: [%s])", - entry_name_in_zip.c_str(), - root_output_path.c_str(), - callback->getStripBasePath().c_str()); - - - // - // Calculate number of entries to extract and total number of bytes - // - unz_global_info gi; - PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi, entry_name_in_zip); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: updateCallbackWithArchiveStatistics()"); - return result; + for (uLong i = 0; i < gi.number_entry; i++) { + if (callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); } - // - // Begin extracting entries - // - - ExtractDataHolder h; - h.unzip = this; - h.callback = callback; - h.root_output_path = root_output_path; - - // this loop call internally progress callbacks - unsigned int matched; - result = IterateFilesInZip(gi, entry_name_in_zip, callback, extractItFunction, matched, &h); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Fail: IterateFilesInZip()"); - return result; + err = unzGetCurrentFileInfo(m_unzip, &cur_file_info, tmp_fname, sizeof(tmp_fname), NULL, 0, + NULL, 0); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), + ("ret: %d", err)); } - // after finish extracting success callback will be called - callback->callSuccessCallbackOnMainThread(); - - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, - void* user_data) -{ - LoggerD("Enter"); - ExtractDataHolder* h = static_cast(user_data); - if(!h) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not list content of zip archive", ("ExtractDataHolder is NULL!")); + const std::string cur_filename_in_zip(tmp_fname); + bool match = true; + + if (!entry_name_in_zip.empty()) { + if (is_directory) { + // If entry_name_in_zip is pointing at directory we need to check each entry in + // zip if its path starts with entry_name_in_zip + match = (0 == cur_filename_in_zip.find(entry_name_in_zip)); + } else { + // If entry name points to file we only extract entry with matching name + match = (cur_filename_in_zip == entry_name_in_zip); + } } - PlatformResult result = h->unzip->extractCurrentFile(h->root_output_path, - h->callback->getStripBasePath(), - h->callback); - if ( result.error_code() != ErrorCode::NO_ERROR) { + if (match) { + PlatformResult result = itfunc(cur_filename_in_zip, cur_file_info, user_data); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Error: %s", result.message().c_str()); return result; - } - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult UnZip::IterateFilesInZip(unz_global_info& gi, - const std::string& entry_name_in_zip, - OperationCallbackData* callback, - UnZip::IterateFunction itfunc, - unsigned int& num_file_or_folder_matched, - void* user_data) -{ - LoggerD("Enter"); - int err = unzGoToFirstFile(m_unzip); - if (UNZ_OK != err) { - LoggerW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); + } + ++num_file_or_folder_matched; } - num_file_or_folder_matched = 0; - const bool is_directory = isDirectoryPath(entry_name_in_zip); - - unz_file_info cur_file_info; - char tmp_fname[512]; - - for (uLong i = 0; i < gi.number_entry; i++) { - - if (callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } - - err = unzGetCurrentFileInfo(m_unzip, &cur_file_info, - tmp_fname, sizeof(tmp_fname), NULL, 0, NULL, 0); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), ("ret: %d", err)); - } - - const std::string cur_filename_in_zip(tmp_fname); - bool match = true; - - if(!entry_name_in_zip.empty()) { - if(is_directory) { - //If entry_name_in_zip is pointing at directory we need to check each entry in - //zip if its path starts with entry_name_in_zip - match = (0 == cur_filename_in_zip.find(entry_name_in_zip)); - } else { - //If entry name points to file we only extract entry with matching name - match = (cur_filename_in_zip == entry_name_in_zip); - } - } - - if(match) { - PlatformResult result = itfunc(cur_filename_in_zip, cur_file_info, user_data); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } - ++num_file_or_folder_matched; - } - - if ((i + 1) < gi.number_entry) { - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); - } - } + if ((i + 1) < gi.number_entry) { + err = unzGoToNextFile(m_unzip); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGoToNextFile()"), ("ret: %d", err)); + } } + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult UnZip::extractCurrentFile(const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) -{ - LoggerD("Entered"); + const std::string& base_strip_path, + BaseProgressCallback* callback) { + LoggerD("Entered"); - if (callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } + if (callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } - LoggerD("extract_path: [%s] base_strip_path: [%s] ", extract_path.c_str(), - base_strip_path.c_str()); - return UnZipExtractRequest::execute(*this, extract_path, base_strip_path, callback); + LoggerD("extract_path: [%s] base_strip_path: [%s] ", extract_path.c_str(), + base_strip_path.c_str()); + return UnZipExtractRequest::execute(*this, extract_path, base_strip_path, callback); } -struct ArchiveStatistics -{ - ArchiveStatistics() : uncompressed_size(0), - number_of_files(0), - number_of_folders(0) {} +struct ArchiveStatistics { + ArchiveStatistics() : uncompressed_size(0), number_of_files(0), number_of_folders(0) { + } - unsigned long uncompressed_size; - unsigned long number_of_files; - unsigned long number_of_folders; + unsigned long uncompressed_size; + unsigned long number_of_files; + unsigned long number_of_folders; }; PlatformResult generateArchiveStatistics(const std::string& file_name, unz_file_info& file_info, - void* user_data) -{ - LoggerD("Enter"); - if(user_data) { - ArchiveStatistics* astats = static_cast(user_data); - astats->uncompressed_size += file_info.uncompressed_size; - - if(isDirectoryPath(file_name)) { - astats->number_of_folders += 1; - } - else { - astats->number_of_files += 1; - } + void* user_data) { + LoggerD("Enter"); + if (user_data) { + ArchiveStatistics* astats = static_cast(user_data); + astats->uncompressed_size += file_info.uncompressed_size; + + if (isDirectoryPath(file_name)) { + astats->number_of_folders += 1; + } else { + astats->number_of_files += 1; } - return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, - unz_global_info& out_global_info, - const std::string& optional_filter) -{ - LoggerD("Enter"); - int err = unzGetGlobalInfo(m_unzip, &out_global_info); - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetGlobalInfo()"), ("ret: %d", err)); - } - - ArchiveStatistics astats; - unsigned int num_matched; - - PlatformResult result = IterateFilesInZip(out_global_info, optional_filter, - callback, generateArchiveStatistics, num_matched, &astats); - if ( result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } - if(0 == num_matched) { - SLoggerE("No matching file/directory: [%s] has been found in zip archive", - optional_filter.c_str()); - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Could not extract file from archive"); - } - - callback->setExpectedDecompressedSize(astats.uncompressed_size); - LoggerD("Expected uncompressed size: %s", - bytesToReadableString(astats.uncompressed_size).c_str()); - - callback->setNumberOfFilesToExtract(astats.number_of_files); - LoggerD("Number entries to extract: files: %d folders: %d", astats.number_of_files, - astats.number_of_folders); - - return PlatformResult(ErrorCode::NO_ERROR); + unz_global_info& out_global_info, + const std::string& optional_filter) { + LoggerD("Enter"); + int err = unzGetGlobalInfo(m_unzip, &out_global_info); + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGetGlobalInfo()"), ("ret: %d", err)); + } + + ArchiveStatistics astats; + unsigned int num_matched; + + PlatformResult result = IterateFilesInZip(out_global_info, optional_filter, callback, + generateArchiveStatistics, num_matched, &astats); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; + } + if (0 == num_matched) { + SLoggerE("No matching file/directory: [%s] has been found in zip archive", + optional_filter.c_str()); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Could not extract file from archive"); + } + + callback->setExpectedDecompressedSize(astats.uncompressed_size); + LoggerD("Expected uncompressed size: %s", + bytesToReadableString(astats.uncompressed_size).c_str()); + + callback->setNumberOfFilesToExtract(astats.number_of_files); + LoggerD("Number entries to extract: files: %d folders: %d", astats.number_of_files, + astats.number_of_folders); + + return PlatformResult(ErrorCode::NO_ERROR); } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/un_zip.h b/src/archive/un_zip.h index 68a3027..06ae1fa 100644 --- a/src/archive/un_zip.h +++ b/src/archive/un_zip.h @@ -17,14 +17,14 @@ #ifndef __TIZEN_ARCHIVE_UNZIP_H__ #define __TIZEN_ARCHIVE_UNZIP_H__ +#include #include -#include #include -#include +#include -#include "common/platform_result.h" #include "archive_callback_data.h" #include "archive_file_entry.h" +#include "common/platform_result.h" namespace extension { namespace archive { @@ -36,71 +36,65 @@ typedef std::shared_ptr> CharVectorPtr; class UnZip; typedef std::shared_ptr UnZipPtr; -class UnZip -{ -public: - static PlatformResult open(const std::string& filename, UnZipPtr* out_unzip); - ~UnZip(); - - PlatformResult listEntries(unsigned long *decompressedSize, ArchiveFileEntryPtrMapPtr* out_map); - - /** - * \brief Extract all files to output directory - * \param callback which keep pointer to ArchiveFile. - */ - PlatformResult extractAllFilesTo(const std::string& extract_path, - ExtractAllProgressCallback* callback); - - PlatformResult extractTo(ExtractEntryProgressCallback* callback); - - PlatformResult close(); - -private: - UnZip(const std::string& filename); - - /** - * \brief Extract current file (iterated with minizip library) - * \param callback which keep pointer to ArchiveFile. - */ - PlatformResult extractCurrentFile(const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - - static PlatformResult extractItFunction(const std::string& file_name, - unz_file_info& file_info, - void* user_data); - - typedef PlatformResult (*IterateFunction) (const std::string& file_name, - unz_file_info& file_info, - void* user_data); - - PlatformResult IterateFilesInZip(unz_global_info& gi, - const std::string& entry_name_in_zip, - OperationCallbackData* callback, - IterateFunction itfunc, - unsigned int& num_file_or_folder_matched, - void* user_data); - - PlatformResult updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, - unz_global_info& out_global_info, - const std::string& optional_filter = std::string()); - - std::string m_zipfile_name; - unzFile m_unzip; - size_t m_default_buffer_size; - bool m_is_open; - - struct ComparePaths : public std::binary_function { - bool operator() (const std::string& lhs, const std::string& rhs) { - return lhs.length() > rhs.length(); - } - }; - std::map path_access_map; - - friend class UnZipExtractRequest; +class UnZip { + public: + static PlatformResult open(const std::string& filename, UnZipPtr* out_unzip); + ~UnZip(); + + PlatformResult listEntries(unsigned long* decompressedSize, ArchiveFileEntryPtrMapPtr* out_map); + + /** + * \brief Extract all files to output directory + * \param callback which keep pointer to ArchiveFile. + */ + PlatformResult extractAllFilesTo(const std::string& extract_path, + ExtractAllProgressCallback* callback); + + PlatformResult extractTo(ExtractEntryProgressCallback* callback); + + PlatformResult close(); + + private: + UnZip(const std::string& filename); + + /** + * \brief Extract current file (iterated with minizip library) + * \param callback which keep pointer to ArchiveFile. + */ + PlatformResult extractCurrentFile(const std::string& extract_path, + const std::string& base_strip_path, + BaseProgressCallback* callback); + + static PlatformResult extractItFunction(const std::string& file_name, unz_file_info& file_info, + void* user_data); + + typedef PlatformResult (*IterateFunction)(const std::string& file_name, unz_file_info& file_info, + void* user_data); + + PlatformResult IterateFilesInZip(unz_global_info& gi, const std::string& entry_name_in_zip, + OperationCallbackData* callback, IterateFunction itfunc, + unsigned int& num_file_or_folder_matched, void* user_data); + + PlatformResult updateCallbackWithArchiveStatistics( + ExtractAllProgressCallback* callback, unz_global_info& out_global_info, + const std::string& optional_filter = std::string()); + + std::string m_zipfile_name; + unzFile m_unzip; + size_t m_default_buffer_size; + bool m_is_open; + + struct ComparePaths : public std::binary_function { + bool operator()(const std::string& lhs, const std::string& rhs) { + return lhs.length() > rhs.length(); + } + }; + std::map path_access_map; + + friend class UnZipExtractRequest; }; -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension -#endif // __TIZEN_ARCHIVE_ZIP_H__ +#endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/un_zip_extract_request.cc b/src/archive/un_zip_extract_request.cc index 12ca6de..e3b7adb 100644 --- a/src/archive/un_zip_extract_request.cc +++ b/src/archive/un_zip_extract_request.cc @@ -16,21 +16,21 @@ #include "un_zip_extract_request.h" -#include #include -#include -#include -#include #include #include #include +#include +#include +#include +#include #include "common/logger.h" #include "common/tools.h" -#include "filesystem_file.h" #include "archive_file.h" #include "archive_utils.h" +#include "filesystem_file.h" #include "un_zip.h" namespace extension { @@ -39,75 +39,70 @@ namespace archive { using namespace common; using common::tools::GetErrorString; -FilePathStatus getPathStatus(const std::string& path) -{ - LoggerD("Enter"); - if(path.empty()) { - return FPS_NOT_EXIST; - } +FilePathStatus getPathStatus(const std::string& path) { + LoggerD("Enter"); + if (path.empty()) { + return FPS_NOT_EXIST; + } - std::string npath = removeTrailingDirectorySlashFromPath(path); + std::string npath = removeTrailingDirectorySlashFromPath(path); - struct stat sb; - if (stat(npath.c_str(), &sb) == -1) { - return FPS_NOT_EXIST; - } - if(sb.st_mode & S_IFDIR) { - return FPS_DIRECTORY; - } else { - return FPS_FILE; - } + struct stat sb; + if (stat(npath.c_str(), &sb) == -1) { + return FPS_NOT_EXIST; + } + if (sb.st_mode & S_IFDIR) { + return FPS_DIRECTORY; + } else { + return FPS_FILE; + } } void divideToPathAndName(const std::string& filepath, std::string& out_path, - std::string& out_name) -{ - LoggerD("Enter"); - size_t pos_last_dir = filepath.find_last_of("/\\"); - if(pos_last_dir == std::string::npos) { - out_path = ""; - out_name = filepath; - } else { - out_path = filepath.substr(0, pos_last_dir+1); - out_name = filepath.substr(pos_last_dir+1); - } + std::string& out_name) { + LoggerD("Enter"); + size_t pos_last_dir = filepath.find_last_of("/\\"); + if (pos_last_dir == std::string::npos) { + out_path = ""; + out_name = filepath; + } else { + out_path = filepath.substr(0, pos_last_dir + 1); + out_name = filepath.substr(pos_last_dir + 1); + } } -void createMissingDirectories(const std::string& path, bool check_first = true) -{ - LoggerD("Enter"); - if(check_first) { - const FilePathStatus path_status = getPathStatus(path); - //LoggerD("[%s] status: %d", path.c_str(), path_status); - if(FPS_DIRECTORY == path_status) { - return; - } +void createMissingDirectories(const std::string& path, bool check_first = true) { + LoggerD("Enter"); + if (check_first) { + const FilePathStatus path_status = getPathStatus(path); + // LoggerD("[%s] status: %d", path.c_str(), path_status); + if (FPS_DIRECTORY == path_status) { + return; } + } + + const size_t extract_path_len = path.length(); + for (size_t i = 0; i < extract_path_len; ++i) { + const char& cur = path[i]; + if ((('\\' == cur || '/' == cur) && i > 0) || // handle left side from current / + (extract_path_len - 1 == i)) { // handle last subdirectory path + const std::string left_part = path.substr(0, i + 1); + const FilePathStatus status = getPathStatus(left_part); + // LoggerD("left_part: [%s] status:%d", left_part.c_str(), status); - const size_t extract_path_len = path.length(); - for(size_t i = 0; i < extract_path_len; ++i) { - const char& cur = path[i]; - if((('\\' == cur || '/' == cur) && i > 0) || //handle left side from current / - (extract_path_len-1 == i) ) { //handle last subdirectory path - - const std::string left_part = path.substr(0,i+1); - const FilePathStatus status = getPathStatus(left_part); - //LoggerD("left_part: [%s] status:%d", left_part.c_str(), status); - - if(FPS_DIRECTORY != status) { - // permissions would be changed after extract process would be finished, - // for now using default 0775 - if(mkdir(left_part.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { - LoggerE("Couldn't create new directory: %s errno: %s", - left_part.c_str(), GetErrorString(errno).c_str()); - } - } + if (FPS_DIRECTORY != status) { + // permissions would be changed after extract process would be finished, + // for now using default 0775 + if (mkdir(left_part.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { + LoggerE("Couldn't create new directory: %s errno: %s", left_part.c_str(), + GetErrorString(errno).c_str()); } + } } + } } -void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) -{ +void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) { LoggerD("Enter"); struct utimbuf ut; struct tm newdate; @@ -118,393 +113,384 @@ void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) newdate.tm_mon = tmu_date.tm_mon; if (tmu_date.tm_year > 1900) { - newdate.tm_year = tmu_date.tm_year - 1900; + newdate.tm_year = tmu_date.tm_year - 1900; } else { - newdate.tm_year = tmu_date.tm_year ; + newdate.tm_year = tmu_date.tm_year; } newdate.tm_isdst = -1; ut.actime = ut.modtime = mktime(&newdate); - if(utime(filepath.c_str(), &ut) == -1) { - LoggerE("Couldn't set time for: [%s] errno: %s", filepath.c_str(), GetErrorString(errno).c_str()); + if (utime(filepath.c_str(), &ut) == -1) { + LoggerE("Couldn't set time for: [%s] errno: %s", filepath.c_str(), + GetErrorString(errno).c_str()); } } PlatformResult UnZipExtractRequest::execute(UnZip& owner, const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) -{ - LoggerD("Enter"); - UnZipExtractRequest req(owner, extract_path, base_strip_path, callback); - if(!req.m_callback){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Problem with callback functionality", ("Callback is null")); - } - return req.run(); + const std::string& base_strip_path, + BaseProgressCallback* callback) { + LoggerD("Enter"); + UnZipExtractRequest req(owner, extract_path, base_strip_path, callback); + if (!req.m_callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Problem with callback functionality", + ("Callback is null")); + } + return req.run(); } -UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) : - - m_owner(owner), - m_extract_path(extract_path), - m_base_strip_path(base_strip_path), - m_callback(callback), - - m_output_file(NULL), - m_buffer(NULL), - m_delete_output_file(false), - m_close_unz_current_file(false), - m_file_info(), - m_new_dir_status(FPS_NOT_EXIST), - - m_is_directory_entry(false) -{ - LoggerD("Enter"); - m_filename_inzip[0] = '\0'; -} +UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, const std::string& extract_path, + const std::string& base_strip_path, + BaseProgressCallback* callback) + : -PlatformResult UnZipExtractRequest::run() -{ - LoggerD("Entered"); + m_owner(owner), + m_extract_path(extract_path), + m_base_strip_path(base_strip_path), + m_callback(callback), - PlatformResult result = getCurrentFileInfo(); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } + m_output_file(NULL), + m_buffer(NULL), + m_delete_output_file(false), + m_close_unz_current_file(false), + m_file_info(), + m_new_dir_status(FPS_NOT_EXIST), - if(m_is_directory_entry) { - result = handleDirectoryEntry(); - } else { - result = handleFileEntry(); - } + m_is_directory_entry(false) { + LoggerD("Enter"); + m_filename_inzip[0] = '\0'; +} + +PlatformResult UnZipExtractRequest::run() { + LoggerD("Entered"); + PlatformResult result = getCurrentFileInfo(); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); return result; + } + + if (m_is_directory_entry) { + result = handleDirectoryEntry(); + } else { + result = handleFileEntry(); + } + + return result; } -UnZipExtractRequest::~UnZipExtractRequest() -{ - LoggerD("Enter"); +UnZipExtractRequest::~UnZipExtractRequest() { + LoggerD("Enter"); - if(m_output_file) { - fclose(m_output_file); - m_output_file = NULL; - } + if (m_output_file) { + fclose(m_output_file); + m_output_file = NULL; + } - if(m_delete_output_file && !m_is_directory_entry) { - if(std::remove(m_output_filepath.c_str()) != 0) { - LoggerE("Couldn't remove partial file! " - "std::remove(\"%s\") failed with errno: %s", - m_output_filepath.c_str(), GetErrorString(errno).c_str()); - } + if (m_delete_output_file && !m_is_directory_entry) { + if (std::remove(m_output_filepath.c_str()) != 0) { + LoggerE( + "Couldn't remove partial file! " + "std::remove(\"%s\") failed with errno: %s", + m_output_filepath.c_str(), GetErrorString(errno).c_str()); } + } - delete [] m_buffer; - m_buffer = NULL; + delete[] m_buffer; + m_buffer = NULL; - if(m_close_unz_current_file) { - int err = unzCloseCurrentFile (m_owner.m_unzip); - if(UNZ_OK != err) { - LoggerW("%s",getArchiveLogMessage(err, "unzCloseCurrentFile()").c_str()); - } + if (m_close_unz_current_file) { + int err = unzCloseCurrentFile(m_owner.m_unzip); + if (UNZ_OK != err) { + LoggerW("%s", getArchiveLogMessage(err, "unzCloseCurrentFile()").c_str()); } + } } -PlatformResult UnZipExtractRequest::getCurrentFileInfo() -{ - LoggerD("Entered"); - int err = unzGetCurrentFileInfo(m_owner.m_unzip, &m_file_info, - m_filename_inzip, sizeof(m_filename_inzip), NULL, 0, NULL, 0); - if (err != UNZ_OK) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), ("ret: %d", err)); - } +PlatformResult UnZipExtractRequest::getCurrentFileInfo() { + LoggerD("Entered"); + int err = unzGetCurrentFileInfo(m_owner.m_unzip, &m_file_info, m_filename_inzip, + sizeof(m_filename_inzip), NULL, 0, NULL, 0); + if (err != UNZ_OK) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzGetCurrentFileInfo()"), + ("ret: %d", err)); + } - LoggerD("Input from ZIP: m_filename_inzip: [%s]", m_filename_inzip); - LoggerD("m_base_strip_path: [%s]", m_base_strip_path.c_str()); + LoggerD("Input from ZIP: m_filename_inzip: [%s]", m_filename_inzip); + LoggerD("m_base_strip_path: [%s]", m_base_strip_path.c_str()); - std::string file_path = m_filename_inzip; - if(!m_base_strip_path.empty()) { - if(file_path.find(m_base_strip_path) != 0) { - LoggerW("m_base_strip_path: [%s] is not begin of m_filename_inzip: [%s]!", - m_base_strip_path.c_str(), - m_filename_inzip); - } - else { - file_path = file_path.substr(m_base_strip_path.length()); - LoggerD("Stripped file name: [%s]", file_path.c_str()); - } - } - else { - LoggerD("Not stripped file name: [%s]", file_path.c_str()); + std::string file_path = m_filename_inzip; + if (!m_base_strip_path.empty()) { + if (file_path.find(m_base_strip_path) != 0) { + LoggerW("m_base_strip_path: [%s] is not begin of m_filename_inzip: [%s]!", + m_base_strip_path.c_str(), m_filename_inzip); + } else { + file_path = file_path.substr(m_base_strip_path.length()); + LoggerD("Stripped file name: [%s]", file_path.c_str()); } + } else { + LoggerD("Not stripped file name: [%s]", file_path.c_str()); + } - m_output_filepath = removeDuplicatedSlashesFromPath(m_extract_path + "/" + file_path); - - LoggerD("Packed: [%s], uncompressed_size: %d, will extract to: [%s]", - m_filename_inzip, m_file_info.uncompressed_size, - m_output_filepath.c_str()); - - std::string path, name; - divideToPathAndName(file_path, path, name); - m_new_dir_path = removeDuplicatedSlashesFromPath(m_extract_path + "/" + path); - m_new_dir_status = getPathStatus(m_new_dir_path); - m_is_directory_entry = name.empty(); - - LoggerD("New output dir: [%s] status: %d m_is_directory_entry: %d", - m_new_dir_path.c_str(), m_new_dir_status, m_is_directory_entry); + m_output_filepath = removeDuplicatedSlashesFromPath(m_extract_path + "/" + file_path); - if(FPS_DIRECTORY != m_new_dir_status) { + LoggerD("Packed: [%s], uncompressed_size: %d, will extract to: [%s]", m_filename_inzip, + m_file_info.uncompressed_size, m_output_filepath.c_str()); - if(m_is_directory_entry) { + std::string path, name; + divideToPathAndName(file_path, path, name); + m_new_dir_path = removeDuplicatedSlashesFromPath(m_extract_path + "/" + path); + m_new_dir_status = getPathStatus(m_new_dir_path); + m_is_directory_entry = name.empty(); - std::string base_directories; - const size_t len = m_new_dir_path.length(); + LoggerD("New output dir: [%s] status: %d m_is_directory_entry: %d", m_new_dir_path.c_str(), + m_new_dir_status, m_is_directory_entry); - for(int i = static_cast(len) - 2; i >= 0; i--) { //skip last \, / - const char& cur = m_new_dir_path[i]; - if('\\' == cur || '/' == cur) { - base_directories = m_new_dir_path.substr(0, static_cast(i)); - break; - } - } + if (FPS_DIRECTORY != m_new_dir_status) { + if (m_is_directory_entry) { + std::string base_directories; + const size_t len = m_new_dir_path.length(); - LoggerD("Type: DIRECTORY checking base output directories: [%s]", - base_directories.c_str()); - createMissingDirectories(base_directories, false); - } else { - LoggerD("Type: FILE checking output dir: [%s]", m_new_dir_path.c_str()); - createMissingDirectories(m_new_dir_path, false); + for (int i = static_cast(len) - 2; i >= 0; i--) { // skip last \, / + const char& cur = m_new_dir_path[i]; + if ('\\' == cur || '/' == cur) { + base_directories = m_new_dir_path.substr(0, static_cast(i)); + break; } + } + + LoggerD("Type: DIRECTORY checking base output directories: [%s]", base_directories.c_str()); + createMissingDirectories(base_directories, false); + } else { + LoggerD("Type: FILE checking output dir: [%s]", m_new_dir_path.c_str()); + createMissingDirectories(m_new_dir_path, false); } - return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UnZipExtractRequest::handleDirectoryEntry() -{ - LoggerD("Entered"); - if(FPS_DIRECTORY != m_new_dir_status) { - - if(FPS_FILE == m_new_dir_status) { - if(m_callback->getOverwrite()) { //Is a file & overwrite is set: - std::string fn = removeTrailingDirectorySlashFromPath(m_new_dir_path); - if(std::remove(fn.c_str()) != 0) { - SLoggerE("std::remove(\"%s\") failed with errno: %s", - m_new_dir_path.c_str(), GetErrorString(errno).c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not overwrite file in output directory"); - } - } else { //Is a file & overwrite is not set: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract directory, " - "file with the same name exists in output directory"); - } +PlatformResult UnZipExtractRequest::handleDirectoryEntry() { + LoggerD("Entered"); + if (FPS_DIRECTORY != m_new_dir_status) { + if (FPS_FILE == m_new_dir_status) { + if (m_callback->getOverwrite()) { // Is a file & overwrite is set: + std::string fn = removeTrailingDirectorySlashFromPath(m_new_dir_path); + if (std::remove(fn.c_str()) != 0) { + SLoggerE("std::remove(\"%s\") failed with errno: %s", m_new_dir_path.c_str(), + GetErrorString(errno).c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Could not overwrite file in output directory"); } + } else { // Is a file & overwrite is not set: + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Failed to extract directory, " + "file with the same name exists in output directory"); + } + } - //Try to create new directory in output directory - if(mkdir(m_new_dir_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { - SLoggerE("Couldn't create new directory: %s errno: %s", - m_new_dir_path.c_str(), GetErrorString(errno).c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create new directory in extract output directory"); - } + // Try to create new directory in output directory + if (mkdir(m_new_dir_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { + SLoggerE("Couldn't create new directory: %s errno: %s", m_new_dir_path.c_str(), + GetErrorString(errno).c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Could not create new directory in extract output directory"); } + } - LoggerD("Set dir: [%s] access and modify to: %4d-%2d-%2d %2d:%2d:%2d", m_new_dir_path.c_str(), - m_file_info.tmu_date.tm_year, - m_file_info.tmu_date.tm_mon, - m_file_info.tmu_date.tm_mday, - m_file_info.tmu_date.tm_hour, - m_file_info.tmu_date.tm_min, - m_file_info.tmu_date.tm_sec); + LoggerD("Set dir: [%s] access and modify to: %4d-%2d-%2d %2d:%2d:%2d", m_new_dir_path.c_str(), + m_file_info.tmu_date.tm_year, m_file_info.tmu_date.tm_mon, m_file_info.tmu_date.tm_mday, + m_file_info.tmu_date.tm_hour, m_file_info.tmu_date.tm_min, m_file_info.tmu_date.tm_sec); - // change modify date and store permission for later update - storePermissions(); - // Directory already exists we only need to update time - changeFileAccessAndModifyDate(m_new_dir_path, m_file_info.tmu_date); + // change modify date and store permission for later update + storePermissions(); + // Directory already exists we only need to update time + changeFileAccessAndModifyDate(m_new_dir_path, m_file_info.tmu_date); - LoggerD("Extracted directory entry: [%s]", m_new_dir_path.c_str()); + LoggerD("Extracted directory entry: [%s]", m_new_dir_path.c_str()); - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UnZipExtractRequest::prepareOutputSubdirectory() -{ - LoggerD("Entered"); - //This zip entry points to file - verify that parent directory in output dir exists - if(FPS_DIRECTORY != m_new_dir_status) { - if(FPS_FILE == m_new_dir_status) { - SLoggerE("Path: %s is pointing to file not directory!", - m_new_dir_path.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract file from zip archive, " - "output path is invalid"); - } - - // permissions would be changed after extract process would be finished, - // for now using default 0775 - if(mkdir(m_new_dir_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { - LoggerW("couldn't create new directory: %s errno: %s", - m_new_dir_path.c_str(), GetErrorString(errno).c_str()); - } +PlatformResult UnZipExtractRequest::prepareOutputSubdirectory() { + LoggerD("Entered"); + // This zip entry points to file - verify that parent directory in output dir exists + if (FPS_DIRECTORY != m_new_dir_status) { + if (FPS_FILE == m_new_dir_status) { + SLoggerE("Path: %s is pointing to file not directory!", m_new_dir_path.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Failed to extract file from zip archive, " + "output path is invalid"); } - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + // permissions would be changed after extract process would be finished, + // for now using default 0775 + if (mkdir(m_new_dir_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { + LoggerW("couldn't create new directory: %s errno: %s", m_new_dir_path.c_str(), + GetErrorString(errno).c_str()); } + } + + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } - const FilePathStatus output_fstatus = getPathStatus(m_output_filepath); - if(FPS_NOT_EXIST != output_fstatus) { - if(!m_callback->getOverwrite()) { - SLoggerE("%s exists at output path: [%s], overwrite is set to FALSE", - (FPS_DIRECTORY == output_fstatus ? "Directory" : "File"), - m_output_filepath.c_str()); - return LogAndCreateResult(ErrorCode::INVALID_MODIFICATION_ERR, "File already exists."); - } else { - if(FPS_DIRECTORY == output_fstatus) { - filesystem::PathPtr path = filesystem::Path::create(m_output_filepath); - filesystem::NodePtr node; - PlatformResult result = filesystem::Node::resolve(path, &node); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } - result = node->remove(filesystem::OPT_RECURSIVE); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("Error: %s", result.message().c_str()); - return result; - } - } + const FilePathStatus output_fstatus = getPathStatus(m_output_filepath); + if (FPS_NOT_EXIST != output_fstatus) { + if (!m_callback->getOverwrite()) { + SLoggerE("%s exists at output path: [%s], overwrite is set to FALSE", + (FPS_DIRECTORY == output_fstatus ? "Directory" : "File"), m_output_filepath.c_str()); + return LogAndCreateResult(ErrorCode::INVALID_MODIFICATION_ERR, "File already exists."); + } else { + if (FPS_DIRECTORY == output_fstatus) { + filesystem::PathPtr path = filesystem::Path::create(m_output_filepath); + filesystem::NodePtr node; + PlatformResult result = filesystem::Node::resolve(path, &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; + } + result = node->remove(filesystem::OPT_RECURSIVE); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Error: %s", result.message().c_str()); + return result; } + } } + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UnZipExtractRequest::handleFileEntry() -{ - LoggerD("Entered"); +PlatformResult UnZipExtractRequest::handleFileEntry() { + LoggerD("Entered"); - PlatformResult result = prepareOutputSubdirectory(); - if (result.error_code() != ErrorCode::NO_ERROR) { - LoggerE("File exists but overwrite is false"); - return result; - } - - int err = unzOpenCurrentFilePassword(m_owner.m_unzip, - NULL); //password is not supported yet therefore passing NULL - if (UNZ_OK != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzOpenCurrentFilePassword()"), ("ret: %d", err)); - } + PlatformResult result = prepareOutputSubdirectory(); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("File exists but overwrite is false"); + return result; + } - //We have successfully opened curent file, therefore we should close it later - m_close_unz_current_file = true; + int err = + unzOpenCurrentFilePassword(m_owner.m_unzip, + NULL); // password is not supported yet therefore passing NULL + if (UNZ_OK != err) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "unzOpenCurrentFilePassword()"), + ("ret: %d", err)); + } - const size_t buffer_size = m_owner.m_default_buffer_size; - m_buffer = new(std::nothrow) char[buffer_size]; - if(!m_buffer) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed", ("Couldn't allocate buffer with size: %s", - bytesToReadableString(buffer_size).c_str())); - } + // We have successfully opened curent file, therefore we should close it later + m_close_unz_current_file = true; - m_output_file = fopen(m_output_filepath.c_str(), "wb"); - if(!m_output_file) { - SLoggerE("Couldn't open output file: %s", m_output_filepath.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create extracted file"); - } - m_delete_output_file = true; + const size_t buffer_size = m_owner.m_default_buffer_size; + m_buffer = new (std::nothrow) char[buffer_size]; + if (!m_buffer) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Memory allocation failed", + ("Couldn't allocate buffer with size: %s", bytesToReadableString(buffer_size).c_str())); + } - bool marked_as_finished = false; + m_output_file = fopen(m_output_filepath.c_str(), "wb"); + if (!m_output_file) { + SLoggerE("Couldn't open output file: %s", m_output_filepath.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create extracted file"); + } + m_delete_output_file = true; - LoggerD("Started extracting: [%s] uncompressed size: %d - %s", m_filename_inzip, - m_file_info.uncompressed_size, - bytesToReadableString(m_file_info.uncompressed_size).c_str()); + bool marked_as_finished = false; - ExtractAllProgressCallback* extract_callback = NULL; - if(m_callback->getCallbackType() == EXTRACT_ALL_PROGRESS_CALLBACK || - m_callback->getCallbackType() == EXTRACT_ENTRY_PROGRESS_CALLBACK) { - extract_callback = dynamic_cast(m_callback); - if( NULL == extract_callback) { - SLoggerE("extract_callback is null"); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create extracted file"); - } - extract_callback->startedExtractingFile(m_file_info.uncompressed_size); - } + LoggerD("Started extracting: [%s] uncompressed size: %d - %s", m_filename_inzip, + m_file_info.uncompressed_size, + bytesToReadableString(m_file_info.uncompressed_size).c_str()); - ArchiveFileEntryPtrMapPtr entries = m_callback->getArchiveFile()->getEntryMap(); - auto it = entries->find(m_filename_inzip); - if (it == entries->end()) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); + ExtractAllProgressCallback* extract_callback = NULL; + if (m_callback->getCallbackType() == EXTRACT_ALL_PROGRESS_CALLBACK || + m_callback->getCallbackType() == EXTRACT_ENTRY_PROGRESS_CALLBACK) { + extract_callback = dynamic_cast(m_callback); + if (NULL == extract_callback) { + SLoggerE("extract_callback is null"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create extracted file"); } + extract_callback->startedExtractingFile(m_file_info.uncompressed_size); + } - while(true) { - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } - - int read_size = unzReadCurrentFile(m_owner.m_unzip, m_buffer, buffer_size); - if (read_size < 0) { - SLoggerE("unzReadCurrentFile failed with error code: %d for file: %s", read_size, - m_filename_inzip); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract file from zip archive"); - } - else if(0 == read_size) { - - if(extract_callback) { - if(!marked_as_finished) { - LoggerD("NOT marked_as_finished -> increment extracted files counter"); - extract_callback->finishedExtractingFile(); - - //Call progress callback only if we expected empty file - if(m_file_info.uncompressed_size == 0) { - LoggerD("Calling progress callback(%f, %s)", - extract_callback->getOverallProgress(), m_filename_inzip); - extract_callback->callProgressCallbackOnMainThread( - extract_callback->getOverallProgress(), it->second); - } - } - } - //Finished writing file, we should not delete extracted file - m_delete_output_file = false; - break; - } + ArchiveFileEntryPtrMapPtr entries = m_callback->getArchiveFile()->getEntryMap(); + auto it = entries->find(m_filename_inzip); + if (it == entries->end()) { + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); + } - if (fwrite(m_buffer, read_size, 1, m_output_file) != 1) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not write extract file into output file"); - } + while (true) { + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } - if(extract_callback) { - extract_callback->extractedPartOfFile(read_size); - LoggerD("File: [%s] extracted: %s - %f%%; total progress %f%%", m_filename_inzip, - bytesToReadableString(read_size).c_str(), - 100.0f * extract_callback->getCurrentFileProgress(), - 100.0f * extract_callback->getOverallProgress()); - - // It is better to update number of extracted entries so we will have - // overal progres: 1.0 if all files are extracted - // - if(extract_callback->getCurrentFileProgress() >= 1.0) { - LoggerD("Current file: [%s] progress: %f >= 1.0 -> " - "marked_as_finished = true and increment extracted files counter", - m_filename_inzip, extract_callback->getCurrentFileProgress()); - marked_as_finished = true; - extract_callback->finishedExtractingFile(); - } - - LoggerD("Calling progress callback(%f, %s)", - extract_callback->getOverallProgress(), m_filename_inzip); + int read_size = unzReadCurrentFile(m_owner.m_unzip, m_buffer, buffer_size); + if (read_size < 0) { + SLoggerE("unzReadCurrentFile failed with error code: %d for file: %s", read_size, + m_filename_inzip); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract file from zip archive"); + } else if (0 == read_size) { + if (extract_callback) { + if (!marked_as_finished) { + LoggerD("NOT marked_as_finished -> increment extracted files counter"); + extract_callback->finishedExtractingFile(); + + // Call progress callback only if we expected empty file + if (m_file_info.uncompressed_size == 0) { + LoggerD("Calling progress callback(%f, %s)", extract_callback->getOverallProgress(), + m_filename_inzip); extract_callback->callProgressCallbackOnMainThread( - extract_callback->getOverallProgress(), it->second); + extract_callback->getOverallProgress(), it->second); + } } + } + // Finished writing file, we should not delete extracted file + m_delete_output_file = false; + break; + } + + if (fwrite(m_buffer, read_size, 1, m_output_file) != 1) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Could not write extract file into output file"); } - if(m_output_file) { - fclose(m_output_file); - m_output_file = NULL; + if (extract_callback) { + extract_callback->extractedPartOfFile(read_size); + LoggerD("File: [%s] extracted: %s - %f%%; total progress %f%%", m_filename_inzip, + bytesToReadableString(read_size).c_str(), + 100.0f * extract_callback->getCurrentFileProgress(), + 100.0f * extract_callback->getOverallProgress()); + + // It is better to update number of extracted entries so we will have + // overal progres: 1.0 if all files are extracted + // + if (extract_callback->getCurrentFileProgress() >= 1.0) { + LoggerD( + "Current file: [%s] progress: %f >= 1.0 -> " + "marked_as_finished = true and increment extracted files counter", + m_filename_inzip, extract_callback->getCurrentFileProgress()); + marked_as_finished = true; + extract_callback->finishedExtractingFile(); + } + + LoggerD("Calling progress callback(%f, %s)", extract_callback->getOverallProgress(), + m_filename_inzip); + extract_callback->callProgressCallbackOnMainThread(extract_callback->getOverallProgress(), + it->second); } + } + + if (m_output_file) { + fclose(m_output_file); + m_output_file = NULL; + } - // change modify date and store permission for later update - storePermissions(); - changeFileAccessAndModifyDate(m_output_filepath, m_file_info.tmu_date); + // change modify date and store permission for later update + storePermissions(); + changeFileAccessAndModifyDate(m_output_filepath, m_file_info.tmu_date); - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } void UnZipExtractRequest::storePermissions() { @@ -518,5 +504,5 @@ void UnZipExtractRequest::storePermissions() { m_owner.path_access_map[m_output_filepath.c_str()] = mode; } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/un_zip_extract_request.h b/src/archive/un_zip_extract_request.h old mode 100755 new mode 100644 index 04d7391..622b9a8 --- a/src/archive/un_zip_extract_request.h +++ b/src/archive/un_zip_extract_request.h @@ -24,64 +24,55 @@ namespace extension { namespace archive { -enum FilePathStatus { - FPS_NOT_EXIST = 0, - FPS_FILE = 1, - FPS_DIRECTORY = 2 +enum FilePathStatus { FPS_NOT_EXIST = 0, FPS_FILE = 1, FPS_DIRECTORY = 2 }; + +class UnZipExtractRequest { + public: + static PlatformResult execute(UnZip& owner, const std::string& extract_path, + const std::string& base_strip_path, BaseProgressCallback* callback); + + ~UnZipExtractRequest(); + + private: + UnZipExtractRequest(UnZip& owner, const std::string& extract_path, + const std::string& base_strip_path, BaseProgressCallback* callback); + + // Not copyable, assignable + UnZipExtractRequest(UnZipExtractRequest const&) = delete; + UnZipExtractRequest& operator=(UnZipExtractRequest const&) = delete; + + PlatformResult run(); + PlatformResult getCurrentFileInfo(); + PlatformResult handleDirectoryEntry(); + PlatformResult handleFileEntry(); + PlatformResult prepareOutputSubdirectory(); + void storePermissions(); + + //----------------------------------------------------------------------------- + // Input request variables + UnZip& m_owner; + const std::string m_extract_path; + const std::string m_base_strip_path; + BaseProgressCallback* m_callback; + + //----------------------------------------------------------------------------- + // Working variables + FILE* m_output_file; // Used to write extracted file into output directory + char* m_buffer; // Memory buffer passed between Minizip lib and fwrite function + + bool m_delete_output_file; + bool m_close_unz_current_file; + + unz_file_info m_file_info; // Informations about current archive entry (from minizip) + char m_filename_inzip[512]; // Name of archive file entry (from minizip) + std::string m_output_filepath; // Extracted output file name with full path + + FilePathStatus m_new_dir_status; + bool m_is_directory_entry; // Is this request for directory + std::string m_new_dir_path; }; -class UnZipExtractRequest -{ -public: - static PlatformResult execute(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - - ~UnZipExtractRequest(); - -private: - UnZipExtractRequest(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - - //Not copyable, assignable - UnZipExtractRequest(UnZipExtractRequest const&) = delete; - UnZipExtractRequest& operator=(UnZipExtractRequest const&) = delete; - - PlatformResult run(); - PlatformResult getCurrentFileInfo(); - PlatformResult handleDirectoryEntry(); - PlatformResult handleFileEntry(); - PlatformResult prepareOutputSubdirectory(); - void storePermissions(); - - //----------------------------------------------------------------------------- - //Input request variables - UnZip& m_owner; - const std::string m_extract_path; - const std::string m_base_strip_path; - BaseProgressCallback* m_callback; - - //----------------------------------------------------------------------------- - //Working variables - FILE* m_output_file; //Used to write extracted file into output directory - char* m_buffer; //Memory buffer passed between Minizip lib and fwrite function - - bool m_delete_output_file; - bool m_close_unz_current_file; - - unz_file_info m_file_info; //Informations about current archive entry (from minizip) - char m_filename_inzip[512]; //Name of archive file entry (from minizip) - std::string m_output_filepath; //Extracted output file name with full path - - FilePathStatus m_new_dir_status; - bool m_is_directory_entry; //Is this request for directory - std::string m_new_dir_path; -}; - -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension -#endif // __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ +#endif // __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ diff --git a/src/archive/zip.cc b/src/archive/zip.cc old mode 100755 new mode 100644 index 3517beb..aefd6c9 --- a/src/archive/zip.cc +++ b/src/archive/zip.cc @@ -16,17 +16,17 @@ #include "zip.h" +#include +#include #include #include #include -#include -#include +#include "archive_file.h" +#include "archive_utils.h" #include "common/logger.h" #include "common/platform_result.h" #include "filesystem_file.h" -#include "archive_file.h" -#include "archive_utils.h" #include "zip_add_request.h" namespace extension { @@ -34,118 +34,113 @@ namespace archive { using namespace common; -void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) -{ - LoggerD("Enter"); - - memset(&out_zi, 0, sizeof(zip_fileinfo)); +void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) { + LoggerD("Enter"); - time_t tm_t = 0; - if (filename != "-") { - std::string name = filename; - if (name[name.length() - 1] == '/') { - name[name.length() - 1] = '\0'; - } + memset(&out_zi, 0, sizeof(zip_fileinfo)); - struct stat s; - // not all systems allow stat'ing a file with / appended - if (stat(name.c_str(), &s) == 0) { - tm_t = s.st_mtime; - } + time_t tm_t = 0; + if (filename != "-") { + std::string name = filename; + if (name[name.length() - 1] == '/') { + name[name.length() - 1] = '\0'; } - struct tm filedate = {0}; - tzset(); - if (nullptr != localtime_r(&tm_t, &filedate)) { - out_zi.tmz_date.tm_sec = filedate.tm_sec; - out_zi.tmz_date.tm_min = filedate.tm_min; - out_zi.tmz_date.tm_hour = filedate.tm_hour; - out_zi.tmz_date.tm_mday = filedate.tm_mday; - out_zi.tmz_date.tm_mon = filedate.tm_mon ; - out_zi.tmz_date.tm_year = filedate.tm_year; + struct stat s; + // not all systems allow stat'ing a file with / appended + if (stat(name.c_str(), &s) == 0) { + tm_t = s.st_mtime; } + } + + struct tm filedate = {0}; + tzset(); + if (nullptr != localtime_r(&tm_t, &filedate)) { + out_zi.tmz_date.tm_sec = filedate.tm_sec; + out_zi.tmz_date.tm_min = filedate.tm_min; + out_zi.tmz_date.tm_hour = filedate.tm_hour; + out_zi.tmz_date.tm_mday = filedate.tm_mday; + out_zi.tmz_date.tm_mon = filedate.tm_mon; + out_zi.tmz_date.tm_year = filedate.tm_year; + } } -Zip::Zip(const std::string& filename, ZipOpenMode open_mode) : - m_zipfile_name(filename), - m_zip(NULL), - m_default_buffer_size(1024 * 1024), - m_is_open(false) -{ - LoggerD("Entered"); - - int append_mode = APPEND_STATUS_CREATE; - if(ZOM_CREATEAFTER == open_mode) { - append_mode = APPEND_STATUS_CREATEAFTER; - } else if(ZOM_ADDINZIP == open_mode) { - append_mode = APPEND_STATUS_ADDINZIP; - } - LoggerD("append_mode: %d", append_mode); +Zip::Zip(const std::string& filename, ZipOpenMode open_mode) + : m_zipfile_name(filename), m_zip(NULL), m_default_buffer_size(1024 * 1024), m_is_open(false) { + LoggerD("Entered"); + + int append_mode = APPEND_STATUS_CREATE; + if (ZOM_CREATEAFTER == open_mode) { + append_mode = APPEND_STATUS_CREATEAFTER; + } else if (ZOM_ADDINZIP == open_mode) { + append_mode = APPEND_STATUS_ADDINZIP; + } + LoggerD("append_mode: %d", append_mode); - m_zip = zipOpen(filename.c_str(), append_mode); + m_zip = zipOpen(filename.c_str(), append_mode); } -Zip::~Zip() -{ - LoggerD("Enter"); +Zip::~Zip() { + LoggerD("Enter"); - close(); + close(); } -PlatformResult Zip::close() -{ - LoggerD("Entered"); - if(!m_is_open) { - LoggerD("Already closed - exiting."); - return PlatformResult(ErrorCode::NO_ERROR); - } +PlatformResult Zip::close() { + LoggerD("Entered"); + if (!m_is_open) { + LoggerD("Already closed - exiting."); + return PlatformResult(ErrorCode::NO_ERROR); + } - int errclose = zipClose(m_zip, NULL); - m_zip = NULL; + int errclose = zipClose(m_zip, NULL); + m_zip = NULL; - if (errclose != ZIP_OK) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "zipClose()"), ("ret: %d", errclose)); - } - m_is_open = false; - return PlatformResult(ErrorCode::NO_ERROR); + if (errclose != ZIP_OK) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "zipClose()"), + ("ret: %d", errclose)); + } + m_is_open = false; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Zip::createNew(const std::string& filename, ZipPtr* out_zip) -{ - LoggerD("Entered"); - ZipPtr zip = ZipPtr(new Zip(filename, ZOM_CREATE)); - if(!zip->m_zip) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", ("zipOpen returned NULL!")); - } - zip->m_is_open = true; - *out_zip = zip; - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Zip::createNew(const std::string& filename, ZipPtr* out_zip) { + LoggerD("Entered"); + ZipPtr zip = ZipPtr(new Zip(filename, ZOM_CREATE)); + if (!zip->m_zip) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", + ("zipOpen returned NULL!")); + } + zip->m_is_open = true; + *out_zip = zip; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Zip::open(const std::string& filename, ZipPtr* out_zip) -{ - LoggerD("Entered"); - ZipPtr zip = ZipPtr(new Zip(filename, ZOM_ADDINZIP)); - if(!zip->m_zip) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", ("zipOpen returned NULL!")); - } - zip->m_is_open = true; - *out_zip = zip; - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Zip::open(const std::string& filename, ZipPtr* out_zip) { + LoggerD("Entered"); + ZipPtr zip = ZipPtr(new Zip(filename, ZOM_ADDINZIP)); + if (!zip->m_zip) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", + ("zipOpen returned NULL!")); + } + zip->m_is_open = true; + *out_zip = zip; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Zip::addFile(AddProgressCallback*& callback) -{ - LoggerD("Entered"); - if(!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", ("callback is NULL!")); - } - if(!m_is_open) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive - zip file closed"); - } - - return ZipAddRequest::execute(*this, callback); +PlatformResult Zip::addFile(AddProgressCallback*& callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", + ("callback is NULL!")); + } + if (!m_is_open) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Could not add file(-s) to archive - zip file closed"); + } + + return ZipAddRequest::execute(*this, callback); } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/zip.h b/src/archive/zip.h old mode 100755 new mode 100644 index 47108bf..1066b2a --- a/src/archive/zip.h +++ b/src/archive/zip.h @@ -27,49 +27,42 @@ namespace extension { namespace archive { - class ZipAddRequest; class Zip; typedef std::shared_ptr ZipPtr; -class Zip -{ -public: - static PlatformResult createNew(const std::string& filename, ZipPtr* out_zip); - static PlatformResult open(const std::string& filename, ZipPtr* out_zip); - ~Zip(); - - /** - * When request has finished callback is set to NULL and is - * deleted on main thread after calling all progress callbacks. - * If exception is thrown please delete callback. - */ - PlatformResult addFile(AddProgressCallback*& callback); +class Zip { + public: + static PlatformResult createNew(const std::string& filename, ZipPtr* out_zip); + static PlatformResult open(const std::string& filename, ZipPtr* out_zip); + ~Zip(); - PlatformResult close(); + /** + * When request has finished callback is set to NULL and is + * deleted on main thread after calling all progress callbacks. + * If exception is thrown please delete callback. + */ + PlatformResult addFile(AddProgressCallback*& callback); -private: - enum ZipOpenMode { - ZOM_CREATE, - ZOM_CREATEAFTER, - ZOM_ADDINZIP - }; + PlatformResult close(); - Zip(const std::string& filename, ZipOpenMode open_mode); + private: + enum ZipOpenMode { ZOM_CREATE, ZOM_CREATEAFTER, ZOM_ADDINZIP }; - static void generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi); + Zip(const std::string& filename, ZipOpenMode open_mode); - std::string m_zipfile_name; - zipFile m_zip; - size_t m_default_buffer_size; - bool m_is_open; + static void generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi); + std::string m_zipfile_name; + zipFile m_zip; + size_t m_default_buffer_size; + bool m_is_open; - friend class ZipAddRequest; + friend class ZipAddRequest; }; -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension -#endif // __TIZEN_ARCHIVE_ZIP_H__ +#endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/zip_add_request.cc b/src/archive/zip_add_request.cc old mode 100755 new mode 100644 index 543bdac..d376d7a --- a/src/archive/zip_add_request.cc +++ b/src/archive/zip_add_request.cc @@ -15,533 +15,507 @@ */ #include "zip_add_request.h" -#include "common/logger.h" #include "archive_file.h" #include "archive_file_entry.h" #include "archive_utils.h" +#include "common/logger.h" using namespace common; namespace extension { namespace archive { -ZipAddRequest::ZipAddRequest(Zip& owner, AddProgressCallback*& callback) : - m_owner(owner), - m_callback(callback), - m_input_file(NULL), - m_buffer(NULL), - m_buffer_size(m_owner.m_default_buffer_size), - m_files_to_compress(0), - m_bytes_to_compress(0), - m_files_compressed(0), - m_bytes_compressed(0), - m_compression_level(0), - m_new_file_in_zip_opened(false) -{ - LoggerD("Enter"); - +ZipAddRequest::ZipAddRequest(Zip& owner, AddProgressCallback*& callback) + : m_owner(owner), + m_callback(callback), + m_input_file(NULL), + m_buffer(NULL), + m_buffer_size(m_owner.m_default_buffer_size), + m_files_to_compress(0), + m_bytes_to_compress(0), + m_files_compressed(0), + m_bytes_compressed(0), + m_compression_level(0), + m_new_file_in_zip_opened(false) { + LoggerD("Enter"); } -ZipAddRequest::~ZipAddRequest() -{ - LoggerD("Enter"); - if(m_input_file) { - fclose(m_input_file); - m_input_file = NULL; - } - - delete [] m_buffer; - m_buffer = NULL; +ZipAddRequest::~ZipAddRequest() { + LoggerD("Enter"); + if (m_input_file) { + fclose(m_input_file); + m_input_file = NULL; + } + delete[] m_buffer; + m_buffer = NULL; - if(m_new_file_in_zip_opened) { - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LoggerE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } + if (m_new_file_in_zip_opened) { + int err = zipCloseFileInZip(m_owner.m_zip); + if (ZIP_OK != err) { + LoggerE("%s", getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); } + } } -PlatformResult ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) -{ - LoggerD("Enter"); - ZipAddRequest req(owner, callback); - return req.run(); +PlatformResult ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) { + LoggerD("Enter"); + ZipAddRequest req(owner, callback); + return req.run(); } -PlatformResult ZipAddRequest::run() -{ - LoggerD("Enter"); - if(!m_callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", ("m_callback is NULL")); - } +PlatformResult ZipAddRequest::run() { + LoggerD("Enter"); + if (!m_callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", + ("m_callback is NULL")); + } - if(!m_callback->getFileEntry()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Provided ArchiveFileEntry is not correct", ("m_callback->getFileEntry() is NULL")); - } - - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } + if (!m_callback->getFileEntry()) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Provided ArchiveFileEntry is not correct", + ("m_callback->getFileEntry() is NULL")); + } - m_compression_level = m_callback->getFileEntry()->getCompressionLevel(); - m_root_src_file = m_callback->getFileEntry()->getFile(); - m_root_src_file_node = m_root_src_file->getNode(); + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } - // We just need read permission to list files in subdirectories - m_root_src_file_node->setPermissions(filesystem::PERM_READ); + m_compression_level = m_callback->getFileEntry()->getCompressionLevel(); + m_root_src_file = m_callback->getFileEntry()->getFile(); + m_root_src_file_node = m_root_src_file->getNode(); - std::string src_basepath, src_name; - getBasePathAndName(m_root_src_file_node->getPath()->getFullPath(), src_basepath, - src_name); + // We just need read permission to list files in subdirectories + m_root_src_file_node->setPermissions(filesystem::PERM_READ); - m_absoulte_path_to_extract = src_basepath; - LoggerD("m_absoulte_path_to_extract: [%s]", m_absoulte_path_to_extract.c_str()); + std::string src_basepath, src_name; + getBasePathAndName(m_root_src_file_node->getPath()->getFullPath(), src_basepath, src_name); - m_destination_path_in_zip = removeDuplicatedSlashesFromPath( - m_callback->getFileEntry()->getDestination()); + m_absoulte_path_to_extract = src_basepath; + LoggerD("m_absoulte_path_to_extract: [%s]", m_absoulte_path_to_extract.c_str()); - // If we have destination set then we need to create all folders and sub folders - // inside this zip archive. - // - PlatformResult result(ErrorCode::NO_ERROR); - if(m_destination_path_in_zip.length() > 0) { - LoggerD("destination is: [%s]", m_destination_path_in_zip.c_str()); + m_destination_path_in_zip = + removeDuplicatedSlashesFromPath(m_callback->getFileEntry()->getDestination()); - for(size_t i = 0; i < m_destination_path_in_zip.length(); ++i) { - const char cur_char = m_destination_path_in_zip[i]; + // If we have destination set then we need to create all folders and sub folders + // inside this zip archive. + // + PlatformResult result(ErrorCode::NO_ERROR); + if (m_destination_path_in_zip.length() > 0) { + LoggerD("destination is: [%s]", m_destination_path_in_zip.c_str()); - if(((cur_char == '/' || cur_char == '\\') && i > 0 ) || - (i == m_destination_path_in_zip.length() - 1)) { + for (size_t i = 0; i < m_destination_path_in_zip.length(); ++i) { + const char cur_char = m_destination_path_in_zip[i]; - //Extract left side with '/': - const std::string new_dir = m_destination_path_in_zip.substr(0, i + 1); + if (((cur_char == '/' || cur_char == '\\') && i > 0) || + (i == m_destination_path_in_zip.length() - 1)) { + // Extract left side with '/': + const std::string new_dir = m_destination_path_in_zip.substr(0, i + 1); - LoggerD("Adding empty directory: [%s] to archive", new_dir.c_str()); - result = addEmptyDirectoryToZipArchive(new_dir); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } - } + LoggerD("Adding empty directory: [%s] to archive", new_dir.c_str()); + result = addEmptyDirectoryToZipArchive(new_dir); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } + } + } + } + + // Generate list of files and all subdirectories + // + filesystem::NodeList all_sub_nodes; + addNodeAndSubdirsToList(m_root_src_file_node, all_sub_nodes); + + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } + + // Calculate total size to be compressed + // + m_bytes_to_compress = 0; + m_files_to_compress = 0; + + int i = 0; + for (auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { + unsigned long long size = 0; + if ((*it)->getType() == filesystem::NT_FILE) { + result = (*it)->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + m_bytes_to_compress += size; + ++m_files_to_compress; } - // Generate list of files and all subdirectories - // - filesystem::NodeList all_sub_nodes; - addNodeAndSubdirsToList(m_root_src_file_node, all_sub_nodes); - - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } - - // Calculate total size to be compressed - // - m_bytes_to_compress = 0; - m_files_to_compress = 0; - - int i = 0; - for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { - - unsigned long long size = 0; - if((*it)->getType() == filesystem::NT_FILE) { - result = (*it)->getSize(&size); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } - m_bytes_to_compress += size; - ++m_files_to_compress; - } + LoggerD("[%d] : [%s] --zip--> [%s] | size: %s", i, (*it)->getPath()->getFullPath().c_str(), + getNameInZipArchiveFor(*it, m_callback->getFileEntry()->getStriped()).c_str(), + bytesToReadableString(size).c_str()); + } - LoggerD("[%d] : [%s] --zip--> [%s] | size: %s", i, (*it)->getPath()->getFullPath().c_str(), - getNameInZipArchiveFor(*it, m_callback->getFileEntry()->getStriped()).c_str(), - bytesToReadableString(size).c_str()); - } + LoggerD("m_files_to_compress: %d", m_files_to_compress); + LoggerD("m_bytes_to_compress: %llu (%s)", m_bytes_to_compress, + bytesToReadableString(m_bytes_to_compress).c_str()); - LoggerD("m_files_to_compress: %d", m_files_to_compress); - LoggerD("m_bytes_to_compress: %llu (%s)", m_bytes_to_compress, - bytesToReadableString(m_bytes_to_compress).c_str()); + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } - - // Begin files compression - // - for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { - result = addToZipArchive(*it); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } + // Begin files compression + // + for (auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { + result = addToZipArchive(*it); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } + } - m_callback->callSuccessCallbackOnMainThread(); - m_callback = NULL; + m_callback->callSuccessCallbackOnMainThread(); + m_callback = NULL; - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, - filesystem::NodeList& out_list_of_child_nodes) -{ - LoggerD("Enter"); - out_list_of_child_nodes.push_back(src_node); - - if(filesystem::NT_DIRECTORY == src_node->getType()) { - LoggerD("Generating recursive list of files in directory"); - NodeList child_nodes; - auto result = src_node->getChildNodes(&child_nodes); - if (result) { - for(const auto& it : child_nodes) { - addNodeAndSubdirsToList(it, out_list_of_child_nodes); - } - } - } + filesystem::NodeList& out_list_of_child_nodes) { + LoggerD("Enter"); + out_list_of_child_nodes.push_back(src_node); + + if (filesystem::NT_DIRECTORY == src_node->getType()) { + LoggerD("Generating recursive list of files in directory"); + NodeList child_nodes; + auto result = src_node->getChildNodes(&child_nodes); + if (result) { + for (const auto& it : child_nodes) { + addNodeAndSubdirsToList(it, out_list_of_child_nodes); + } + } + } } -PlatformResult ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) -{ - LoggerD("Entered name_in_zip:%s", name_in_zip.c_str()); - - if(name_in_zip.length() == 0) { - LoggerW("Trying to create directory with empty name - \"\""); - return PlatformResult(ErrorCode::NO_ERROR); - } - - const char last_char = name_in_zip[name_in_zip.length()-1]; - if(last_char != '/' && last_char != '\\') { - name_in_zip += "/"; - LoggerD("Corrected name_in_zip: [%s]", name_in_zip.c_str()); - } - - if(m_new_file_in_zip_opened) { - LoggerE("WARNING: Previous new file in zip archive is opened!"); - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LoggerE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - } - - bool is_directory = false; - std::string conflicting_name; - - if(m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, - &is_directory, &conflicting_name)) { - - if(!is_directory) { - SLoggerE("Entry: [%s] exists and is NOT directory!", conflicting_name.c_str()); - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "File with the same name exists"); - } - - LoggerD("Directory: [%s] already exists -> nothing to do", name_in_zip.c_str()); - return PlatformResult(ErrorCode::NO_ERROR); - } - - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } +PlatformResult ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) { + LoggerD("Entered name_in_zip:%s", name_in_zip.c_str()); - zip_fileinfo new_dir_info; - memset(&new_dir_info, 0, sizeof(zip_fileinfo)); - - // - // Since this directory does not exist we will set current time - // - time_t current_time = time(NULL); - struct tm current_time_tm = {0}; - tzset(); - if (nullptr != localtime_r(¤t_time, ¤t_time_tm)) { - new_dir_info.tmz_date.tm_sec = current_time_tm.tm_sec; - new_dir_info.tmz_date.tm_min = current_time_tm.tm_min; - new_dir_info.tmz_date.tm_hour = current_time_tm.tm_hour; - new_dir_info.tmz_date.tm_mday = current_time_tm.tm_mday; - new_dir_info.tmz_date.tm_mon = current_time_tm.tm_mon ; - new_dir_info.tmz_date.tm_year = current_time_tm.tm_year; - } + if (name_in_zip.length() == 0) { + LoggerW("Trying to create directory with empty name - \"\""); + return PlatformResult(ErrorCode::NO_ERROR); + } - int err = zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_dir_info, - NULL, 0, NULL, 0, NULL, - (m_compression_level != 0) ? Z_DEFLATED : 0, - m_compression_level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0); + const char last_char = name_in_zip[name_in_zip.length() - 1]; + if (last_char != '/' && last_char != '\\') { + name_in_zip += "/"; + LoggerD("Corrected name_in_zip: [%s]", name_in_zip.c_str()); + } - if (err != ZIP_OK) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "zipOpenNewFileInZip3()"), ("ret: %d", err)); + if (m_new_file_in_zip_opened) { + LoggerE("WARNING: Previous new file in zip archive is opened!"); + int err = zipCloseFileInZip(m_owner.m_zip); + if (ZIP_OK != err) { + LoggerE("%s", getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); } + } - m_new_file_in_zip_opened = true; + bool is_directory = false; + std::string conflicting_name; - err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LoggerE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); + if (m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, &is_directory, + &conflicting_name)) { + if (!is_directory) { + SLoggerE("Entry: [%s] exists and is NOT directory!", conflicting_name.c_str()); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "File with the same name exists"); } - LoggerD("Added new empty directory to archive: [%s]", name_in_zip.c_str()); - m_new_file_in_zip_opened = false; - + LoggerD("Directory: [%s] already exists -> nothing to do", name_in_zip.c_str()); return PlatformResult(ErrorCode::NO_ERROR); + } + + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } + + zip_fileinfo new_dir_info; + memset(&new_dir_info, 0, sizeof(zip_fileinfo)); + + // + // Since this directory does not exist we will set current time + // + time_t current_time = time(NULL); + struct tm current_time_tm = {0}; + tzset(); + if (nullptr != localtime_r(¤t_time, ¤t_time_tm)) { + new_dir_info.tmz_date.tm_sec = current_time_tm.tm_sec; + new_dir_info.tmz_date.tm_min = current_time_tm.tm_min; + new_dir_info.tmz_date.tm_hour = current_time_tm.tm_hour; + new_dir_info.tmz_date.tm_mday = current_time_tm.tm_mday; + new_dir_info.tmz_date.tm_mon = current_time_tm.tm_mon; + new_dir_info.tmz_date.tm_year = current_time_tm.tm_year; + } + + int err = + zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_dir_info, NULL, 0, NULL, 0, + NULL, (m_compression_level != 0) ? Z_DEFLATED : 0, m_compression_level, + 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0); + + if (err != ZIP_OK) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + getArchiveLogMessage(err, "zipOpenNewFileInZip3()"), + ("ret: %d", err)); + } + + m_new_file_in_zip_opened = true; + + err = zipCloseFileInZip(m_owner.m_zip); + if (ZIP_OK != err) { + LoggerE("%s", getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); + } + + LoggerD("Added new empty directory to archive: [%s]", name_in_zip.c_str()); + m_new_file_in_zip_opened = false; + + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) -{ - LoggerD("Enter"); - const std::string name_in_zip = getNameInZipArchiveFor(src_file_node, - m_callback->getFileEntry()->getStriped()); - const std::string src_file_path = src_file_node->getPath()->getFullPath(); +PlatformResult ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) { + LoggerD("Enter"); + const std::string name_in_zip = + getNameInZipArchiveFor(src_file_node, m_callback->getFileEntry()->getStriped()); + const std::string src_file_path = src_file_node->getPath()->getFullPath(); - LoggerD("Compress: [%s] to zip archive as: [%s]", src_file_path.c_str(), - name_in_zip.c_str()); + LoggerD("Compress: [%s] to zip archive as: [%s]", src_file_path.c_str(), name_in_zip.c_str()); - zip_fileinfo new_file_info; - Zip::generateZipFileInfo(src_file_path, new_file_info); + zip_fileinfo new_file_info; + Zip::generateZipFileInfo(src_file_path, new_file_info); - if(m_new_file_in_zip_opened) { - LoggerE("WARNING: Previous new file in zip archive is opened!"); - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LoggerE("zipCloseFileInZip failed with error: %d", err); + if (m_new_file_in_zip_opened) { + LoggerE("WARNING: Previous new file in zip archive is opened!"); + int err = zipCloseFileInZip(m_owner.m_zip); + if (ZIP_OK != err) { + LoggerE("zipCloseFileInZip failed with error: %d", err); + } + } + + if (m_callback->isCanceled()) { + return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); + } + + std::string conflicting_name; + if (m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, NULL, + &conflicting_name)) { + SLoggerE( + "Cannot add new entry with name name: [%s] " + "it would conflict with existing entry: [%s]", + name_in_zip.c_str(), conflicting_name.c_str()); + + return LogAndCreateResult(ErrorCode::INVALID_MODIFICATION_ERR, "Archive entry name conflicts"); + } + + int err = + zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_file_info, NULL, 0, NULL, 0, + NULL, (m_compression_level != 0) ? Z_DEFLATED : 0, m_compression_level, + 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0); + + if (err != ZIP_OK) { + SLoggerE("Error opening new file: [%s] in zipfile", name_in_zip.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add new file to zip archive"); + } + + m_new_file_in_zip_opened = true; + + if (m_input_file) { + LoggerW("WARNING: Previous m_input_file has not been closed"); + fclose(m_input_file); + m_input_file = NULL; + } + + filesystem::File::PermissionList perm_list; + filesystem::FilePtr cur_file(new filesystem::File(src_file_node, perm_list)); + ArchiveFileEntryPtr cur_afentry(new ArchiveFileEntry(cur_file)); + cur_afentry->setCompressionLevel(m_compression_level); + cur_afentry->setName(name_in_zip); + + std::time_t time; + PlatformResult result = src_file_node->getModified(&time); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + cur_afentry->setModified(time); + + auto entry = m_callback->getFileEntry(); + cur_afentry->setDestination(entry->getDestination()); + cur_afentry->setStriped(entry->getStriped()); + cur_afentry->setSize(0); + + LoggerD("m_bytes_compressed:%llu / m_bytes_to_compress: %llu", m_bytes_compressed, + m_bytes_to_compress); + + LoggerD("m_files_compressed:%d / m_files_to_compress: %d", m_files_compressed, + m_files_to_compress); + + if (src_file_node->getType() == filesystem::NT_FILE) { + m_input_file = fopen(src_file_path.c_str(), "rb"); + if (!m_input_file) { + SLoggerE("Error opening source file: %s", src_file_path.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not open file to be added"); + } + + // Get file length + fseek(m_input_file, 0, SEEK_END); + const size_t in_file_size = ftell(m_input_file); + fseek(m_input_file, 0, SEEK_SET); + LoggerD("Source file: [%s] size: %d - %s", src_file_path.c_str(), in_file_size, + bytesToReadableString(in_file_size).c_str()); + + cur_afentry->setSize(in_file_size); + + if (!m_buffer) { + m_buffer = new (std::nothrow) char[m_buffer_size]; + if (!m_buffer) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); + } + } + + size_t total_bytes_read = 0; + size_t size_read = 0; + + do { + size_read = fread(m_buffer, 1, m_buffer_size, m_input_file); + if (size_read < m_buffer_size && feof(m_input_file) == 0) { + SLoggerE("Error reading source file: %s", src_file_path.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); + } + + LoggerD("Read: %d bytes from input file:[%s]", size_read, src_file_path.c_str()); + total_bytes_read += size_read; + m_bytes_compressed += size_read; + + if (size_read > 0) { + err = zipWriteInFileInZip(m_owner.m_zip, m_buffer, size_read); + if (err < 0) { + SLoggerE("Error during adding file: %s into zip archive", src_file_path.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); } - } + } - if(m_callback->isCanceled()) { - return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); - } + if (total_bytes_read == in_file_size) { + LoggerD("Finished reading and compressing source file: [%s]", src_file_path.c_str()); + ++m_files_compressed; + } - std::string conflicting_name; - if(m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, - NULL, &conflicting_name)) { + LoggerD( + "Callculatting overall progress: %llu/%llu bytes; " + "%d/%d files; current file: [%s] progress: %d/%d bytes; ", + m_bytes_compressed, m_bytes_to_compress, m_files_compressed, m_files_to_compress, + src_file_path.c_str(), total_bytes_read, in_file_size); - SLoggerE("Cannot add new entry with name name: [%s] " - "it would conflict with existing entry: [%s]", - name_in_zip.c_str(), conflicting_name.c_str()); + double progress = 1.0; + if (m_bytes_to_compress > 0 || m_files_to_compress > 0) { + progress = static_cast(m_bytes_compressed + m_files_compressed) / + static_cast(m_bytes_to_compress + m_files_to_compress); + } - return LogAndCreateResult(ErrorCode::INVALID_MODIFICATION_ERR, "Archive entry name conflicts"); - } + LoggerD("Wrote: %s total progress: %.2f%% %d/%d files", + bytesToReadableString(size_read).c_str(), progress * 100.0, m_files_compressed, + m_files_to_compress); - int err = zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_file_info, - NULL, 0, NULL, 0, NULL, - (m_compression_level != 0) ? Z_DEFLATED : 0, - m_compression_level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0); + LoggerD("Calling add onprogress callback(%f, %s)", progress, name_in_zip.c_str()); + m_callback->callProgressCallbackOnMainThread(progress, cur_afentry); + } while (size_read > 0 && total_bytes_read < in_file_size); - if (err != ZIP_OK) { - SLoggerE("Error opening new file: [%s] in zipfile", name_in_zip.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add new file to zip archive"); + if (in_file_size != total_bytes_read) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not add file to archive", + ("in_file_size(%d) != total_bytes_read(%d)", in_file_size, total_bytes_read)); } - m_new_file_in_zip_opened = true; - - if(m_input_file) { - LoggerW("WARNING: Previous m_input_file has not been closed"); - fclose(m_input_file); - m_input_file = NULL; - } + fclose(m_input_file); + m_input_file = NULL; + } - filesystem::File::PermissionList perm_list; - filesystem::FilePtr cur_file(new filesystem::File(src_file_node, perm_list)); - ArchiveFileEntryPtr cur_afentry(new ArchiveFileEntry(cur_file)); - cur_afentry->setCompressionLevel(m_compression_level); - cur_afentry->setName(name_in_zip); + err = zipCloseFileInZip(m_owner.m_zip); + if (ZIP_OK != err) { + LoggerE("Error in closing added file:%s in zipfile", src_file_path.c_str()); + } - std::time_t time; - PlatformResult result = src_file_node->getModified(&time); - if (result.error_code() != ErrorCode::NO_ERROR) { - return result; - } - cur_afentry->setModified(time); - - auto entry = m_callback->getFileEntry(); - cur_afentry->setDestination(entry->getDestination()); - cur_afentry->setStriped(entry->getStriped()); - cur_afentry->setSize(0); - - LoggerD("m_bytes_compressed:%llu / m_bytes_to_compress: %llu", - m_bytes_compressed, m_bytes_to_compress); - - LoggerD("m_files_compressed:%d / m_files_to_compress: %d", - m_files_compressed, m_files_to_compress); - - if(src_file_node->getType() == filesystem::NT_FILE) { - m_input_file = fopen(src_file_path.c_str(), "rb"); - if (!m_input_file) { - SLoggerE("Error opening source file: %s", src_file_path.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not open file to be added"); - } - - //Get file length - fseek(m_input_file, 0, SEEK_END); - const size_t in_file_size = ftell(m_input_file); - fseek(m_input_file, 0, SEEK_SET); - LoggerD("Source file: [%s] size: %d - %s", src_file_path.c_str(), - in_file_size, - bytesToReadableString(in_file_size).c_str()); - - cur_afentry->setSize(in_file_size); - - if(!m_buffer) { - m_buffer = new(std::nothrow) char[m_buffer_size]; - if(!m_buffer) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); - } - } + m_new_file_in_zip_opened = false; - size_t total_bytes_read = 0; - size_t size_read = 0; - - do { - size_read = fread(m_buffer, 1, m_buffer_size, m_input_file); - if (size_read < m_buffer_size && - feof(m_input_file) == 0) { - SLoggerE("Error reading source file: %s", src_file_path.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); - } - - LoggerD("Read: %d bytes from input file:[%s]", size_read, - src_file_path.c_str()); - total_bytes_read += size_read; - m_bytes_compressed += size_read; - - if (size_read > 0) { - err = zipWriteInFileInZip (m_owner.m_zip, m_buffer, size_read); - if (err < 0) { - SLoggerE("Error during adding file: %s into zip archive", - src_file_path.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); - } - } - - if(total_bytes_read == in_file_size) { - LoggerD("Finished reading and compressing source file: [%s]", - src_file_path.c_str()); - ++m_files_compressed; - } - - LoggerD("Callculatting overall progress: %llu/%llu bytes; " - "%d/%d files; current file: [%s] progress: %d/%d bytes; ", - m_bytes_compressed, m_bytes_to_compress, - m_files_compressed, m_files_to_compress, - src_file_path.c_str(), - total_bytes_read, in_file_size); - - double progress = 1.0; - if(m_bytes_to_compress > 0 || m_files_to_compress > 0) { - progress = static_cast(m_bytes_compressed + m_files_compressed) / - static_cast(m_bytes_to_compress + m_files_to_compress); - } - - LoggerD("Wrote: %s total progress: %.2f%% %d/%d files", - bytesToReadableString(size_read).c_str(), progress * 100.0, - m_files_compressed, m_files_to_compress); - - LoggerD("Calling add onprogress callback(%f, %s)", progress, - name_in_zip.c_str()); - m_callback->callProgressCallbackOnMainThread(progress, cur_afentry); - - } while (size_read > 0 && total_bytes_read < in_file_size); - - if(in_file_size != total_bytes_read) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", ("in_file_size(%d) != total_bytes_read(%d)", in_file_size, - total_bytes_read)); - } - - fclose(m_input_file); - m_input_file = NULL; - } - - err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LoggerE("Error in closing added file:%s in zipfile", src_file_path.c_str()); - } - - m_new_file_in_zip_opened = false; - - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -std::string removeDirCharsFromFront(const std::string& path) -{ - LoggerD("Enter"); - for(size_t i = 0; i < path.length(); ++i) { - const char& cur = path[i]; - if(cur != '/' && cur != '\\') { - return path.substr(i); - } +std::string removeDirCharsFromFront(const std::string& path) { + LoggerD("Enter"); + for (size_t i = 0; i < path.length(); ++i) { + const char& cur = path[i]; + if (cur != '/' && cur != '\\') { + return path.substr(i); } + } - return std::string(); //in case path contained only slashes + return std::string(); // in case path contained only slashes } -std::string generateFullPathForZip(const std::string& path) -{ - LoggerD("Enter"); - //Step 1: Remove / from begining - const size_t path_len = path.length(); - - size_t start_i = 0; - for(size_t i = 0; i < path_len; ++i) { - const char& cur = path[i]; - if(cur != '/' && cur != '\\') { - start_i = i; - break; - } - } - - std::string out; - out.reserve(path_len); - - //Step 1: Remove duplicated / characters - bool prev_is_dir = false; - for(size_t i = start_i; i < path_len; ++i) { - const char& cur = path[i]; - if(cur == '/' || cur == '\\') { - if(!prev_is_dir) { - out += cur; - } - prev_is_dir = true; - } else { - prev_is_dir = false; - out += cur; - } - } - - return out; +std::string generateFullPathForZip(const std::string& path) { + LoggerD("Enter"); + // Step 1: Remove / from begining + const size_t path_len = path.length(); + + size_t start_i = 0; + for (size_t i = 0; i < path_len; ++i) { + const char& cur = path[i]; + if (cur != '/' && cur != '\\') { + start_i = i; + break; + } + } + + std::string out; + out.reserve(path_len); + + // Step 1: Remove duplicated / characters + bool prev_is_dir = false; + for (size_t i = start_i; i < path_len; ++i) { + const char& cur = path[i]; + if (cur == '/' || cur == '\\') { + if (!prev_is_dir) { + out += cur; + } + prev_is_dir = true; + } else { + prev_is_dir = false; + out += cur; + } + } + + return out; } -std::string ZipAddRequest::getNameInZipArchiveFor(filesystem::NodePtr node, bool strip) -{ - LoggerD("Enter"); - const std::string node_full_path = node->getPath()->getFullPath(); - std::string cut_path; - - const size_t pos = node_full_path.find(m_absoulte_path_to_extract); - if(std::string::npos == pos) { - LoggerW("node: [%s] is not containing m_absoulte_path_to_extract: [%s]!", - node_full_path.c_str(), - m_absoulte_path_to_extract.c_str()); - } +std::string ZipAddRequest::getNameInZipArchiveFor(filesystem::NodePtr node, bool strip) { + LoggerD("Enter"); + const std::string node_full_path = node->getPath()->getFullPath(); + std::string cut_path; - cut_path = node_full_path.substr(pos+m_absoulte_path_to_extract.length()); - LoggerD("node_full_path:%s cut_path: %s", node_full_path.c_str(), cut_path.c_str()); + const size_t pos = node_full_path.find(m_absoulte_path_to_extract); + if (std::string::npos == pos) { + LoggerW("node: [%s] is not containing m_absoulte_path_to_extract: [%s]!", + node_full_path.c_str(), m_absoulte_path_to_extract.c_str()); + } - if(!strip) { - cut_path = m_callback->getBaseVirtualPath() + "/" + cut_path; - LoggerD("nonstripped cut_path: %s", cut_path.c_str()); - } + cut_path = node_full_path.substr(pos + m_absoulte_path_to_extract.length()); + LoggerD("node_full_path:%s cut_path: %s", node_full_path.c_str(), cut_path.c_str()); - std::string name = generateFullPathForZip(m_destination_path_in_zip + "/" + cut_path); - if(node->getType() == filesystem::NT_DIRECTORY) { - if(name.length() > 0 - && name[name.length()-1] != '/' - && name[name.length()-1] != '\\') { - name += "/"; - LoggerD("Directory: [%s] added \\", name.c_str()); - } + if (!strip) { + cut_path = m_callback->getBaseVirtualPath() + "/" + cut_path; + LoggerD("nonstripped cut_path: %s", cut_path.c_str()); + } + + std::string name = generateFullPathForZip(m_destination_path_in_zip + "/" + cut_path); + if (node->getType() == filesystem::NT_DIRECTORY) { + if (name.length() > 0 && name[name.length() - 1] != '/' && name[name.length() - 1] != '\\') { + name += "/"; + LoggerD("Directory: [%s] added \\", name.c_str()); } + } - return name; + return name; } -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension diff --git a/src/archive/zip_add_request.h b/src/archive/zip_add_request.h old mode 100755 new mode 100644 index 49459d8..5918dfb --- a/src/archive/zip_add_request.h +++ b/src/archive/zip_add_request.h @@ -20,69 +20,65 @@ #include #include +#include "archive_callback_data.h" #include "common/platform_result.h" #include "filesystem_file.h" -#include "archive_callback_data.h" #include "zip.h" namespace extension { namespace archive { -class ZipAddRequest -{ -public: - - /** - * When request has finished callback is set to NULL and is - * deleted on main thread after calling all progress callbacks. - * If exception is thrown please delete callback. - */ - static PlatformResult execute(Zip& owner, AddProgressCallback*& callback); - ~ZipAddRequest(); - -private: - ZipAddRequest(Zip& owner, AddProgressCallback*& callback); - ZipAddRequest(ZipAddRequest const&) = delete; - ZipAddRequest& operator=(ZipAddRequest const&) = delete; - - PlatformResult run(); +class ZipAddRequest { + public: + /** + * When request has finished callback is set to NULL and is + * deleted on main thread after calling all progress callbacks. + * If exception is thrown please delete callback. + */ + static PlatformResult execute(Zip& owner, AddProgressCallback*& callback); + ~ZipAddRequest(); - void addNodeAndSubdirsToList(filesystem::NodePtr src_node, - filesystem::NodeList& out_list_of_child_nodes); + private: + ZipAddRequest(Zip& owner, AddProgressCallback*& callback); + ZipAddRequest(ZipAddRequest const&) = delete; + ZipAddRequest& operator=(ZipAddRequest const&) = delete; - PlatformResult addEmptyDirectoryToZipArchive(std::string name_in_zip); - PlatformResult addToZipArchive(filesystem::NodePtr src_file_node); + PlatformResult run(); - std::string getNameInZipArchiveFor(filesystem::NodePtr node, bool strip); + void addNodeAndSubdirsToList(filesystem::NodePtr src_node, + filesystem::NodeList& out_list_of_child_nodes); - //----------------------------------------------------------------------------- - //Input request variables - Zip& m_owner; - AddProgressCallback* m_callback; + PlatformResult addEmptyDirectoryToZipArchive(std::string name_in_zip); + PlatformResult addToZipArchive(filesystem::NodePtr src_file_node); + std::string getNameInZipArchiveFor(filesystem::NodePtr node, bool strip); - FILE* m_input_file; - char* m_buffer; - size_t m_buffer_size; + //----------------------------------------------------------------------------- + // Input request variables + Zip& m_owner; + AddProgressCallback* m_callback; + FILE* m_input_file; + char* m_buffer; + size_t m_buffer_size; - unsigned long m_files_to_compress; - unsigned long long m_bytes_to_compress; + unsigned long m_files_to_compress; + unsigned long long m_bytes_to_compress; - unsigned long m_files_compressed; - unsigned long long m_bytes_compressed; + unsigned long m_files_compressed; + unsigned long long m_bytes_compressed; - filesystem::FilePtr m_root_src_file; - filesystem::NodePtr m_root_src_file_node; - std::string m_absoulte_path_to_extract; - std::string m_destination_path_in_zip; + filesystem::FilePtr m_root_src_file; + filesystem::NodePtr m_root_src_file_node; + std::string m_absoulte_path_to_extract; + std::string m_destination_path_in_zip; - unsigned int m_compression_level; + unsigned int m_compression_level; - bool m_new_file_in_zip_opened; + bool m_new_file_in_zip_opened; }; -} //namespace archive -} //namespace extension +} // namespace archive +} // namespace extension -#endif // __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__ +#endif // __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__ diff --git a/src/badge/badge_extension.cc b/src/badge/badge_extension.cc old mode 100755 new mode 100644 index 07ac87f..fa88bbc --- a/src/badge/badge_extension.cc +++ b/src/badge/badge_extension.cc @@ -20,14 +20,17 @@ // This will be generated from badge_api.js extern const char kSource_badge_api[]; -common::Extension* CreateExtension() { return new BadgeExtension; } +common::Extension* CreateExtension() { + return new BadgeExtension; +} BadgeExtension::BadgeExtension() { SetExtensionName("tizen.badge"); SetJavaScriptAPI(kSource_badge_api); } -BadgeExtension::~BadgeExtension() {} +BadgeExtension::~BadgeExtension() { +} common::Instance* BadgeExtension::CreateInstance() { return new extension::badge::BadgeInstance(); diff --git a/src/badge/badge_instance.cc b/src/badge/badge_instance.cc old mode 100755 new mode 100644 index b155b61..bcdcb13 --- a/src/badge/badge_instance.cc +++ b/src/badge/badge_instance.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "badge/badge_instance.h" #include "common/converter.h" @@ -36,13 +36,10 @@ BadgeInstance::BadgeInstance() : manager_(*this) { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&BadgeInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&BadgeInstance::x, this, _1, _2)); REGISTER_SYNC("BadgeManager_setBadgeCount", BadgeManagerSetBadgeCount); - REGISTER_SYNC("BadgeManager_addChangeListener", - BadgeManagerAddChangeListener); - REGISTER_SYNC("BadgeManager_removeChangeListener", - BadgeManagerRemoveChangeListener); + REGISTER_SYNC("BadgeManager_addChangeListener", BadgeManagerAddChangeListener); + REGISTER_SYNC("BadgeManager_removeChangeListener", BadgeManagerRemoveChangeListener); REGISTER_SYNC("BadgeManager_getBadgeCount", BadgeManagerGetBadgeCount); #undef REGISTER_SYNC } @@ -51,17 +48,14 @@ BadgeInstance::~BadgeInstance() { LoggerD("Enter"); } -void BadgeInstance::BadgeManagerSetBadgeCount(const JsonValue& args, - JsonObject& out) { +void BadgeInstance::BadgeManagerSetBadgeCount(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - std::string app_id = - common::FromJson(args.get(), "appId"); + std::string app_id = common::FromJson(args.get(), "appId"); const double count = args.get("count").get(); - PlatformResult status = manager_.SetBadgeCount( - app_id, static_cast(count)); + PlatformResult status = manager_.SetBadgeCount(app_id, static_cast(count)); if (status.IsSuccess()) { ReportSuccess(out); } else { @@ -69,17 +63,14 @@ void BadgeInstance::BadgeManagerSetBadgeCount(const JsonValue& args, } } -void BadgeInstance::BadgeManagerGetBadgeCount(const JsonValue& args, - JsonObject& out) { +void BadgeInstance::BadgeManagerGetBadgeCount(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - std::string app_id = - common::FromJson(args.get(), "appId"); + std::string app_id = common::FromJson(args.get(), "appId"); unsigned int count = 0; - PlatformResult status = - manager_.GetBadgeCount(app_id, &count); + PlatformResult status = manager_.GetBadgeCount(app_id, &count); if (status.IsSuccess()) { ReportSuccess(JsonValue(std::to_string(count)), out); } else { @@ -87,13 +78,11 @@ void BadgeInstance::BadgeManagerGetBadgeCount(const JsonValue& args, } } -void BadgeInstance::BadgeManagerAddChangeListener(const JsonValue& args, - JsonObject& out) { +void BadgeInstance::BadgeManagerAddChangeListener(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - PlatformResult status = - manager_.AddChangeListener(args.get()); + PlatformResult status = manager_.AddChangeListener(args.get()); if (status.IsSuccess()) { ReportSuccess(out); @@ -102,13 +91,11 @@ void BadgeInstance::BadgeManagerAddChangeListener(const JsonValue& args, } } -void BadgeInstance::BadgeManagerRemoveChangeListener(const JsonValue& args, - JsonObject& out) { +void BadgeInstance::BadgeManagerRemoveChangeListener(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - PlatformResult status = - manager_.RemoveChangeListener(args.get()); + PlatformResult status = manager_.RemoveChangeListener(args.get()); if (status.IsSuccess()) { ReportSuccess(out); diff --git a/src/badge/badge_instance.h b/src/badge/badge_instance.h old mode 100755 new mode 100644 index 77fc8d1..c0050ed --- a/src/badge/badge_instance.h +++ b/src/badge/badge_instance.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef BADGE_BADGE_INSTANCE_H_ #define BADGE_BADGE_INSTANCE_H_ diff --git a/src/badge/badge_manager.cc b/src/badge/badge_manager.cc old mode 100755 new mode 100644 index 8736e84..54c57b0 --- a/src/badge/badge_manager.cc +++ b/src/badge/badge_manager.cc @@ -25,8 +25,8 @@ #include "badge/badge_instance.h" #include "common/assert.h" -#include "common/logger.h" #include "common/converter.h" +#include "common/logger.h" #include "common/platform_exception.h" using namespace common; @@ -34,9 +34,8 @@ using namespace common; namespace extension { namespace badge { -BadgeManager::BadgeManager(BadgeInstance& instance) - : instance_(instance), - is_cb_registered_(false) { +BadgeManager::BadgeManager(BadgeInstance &instance) + : instance_(instance), is_cb_registered_(false) { } BadgeManager::~BadgeManager() { @@ -51,14 +50,12 @@ BadgeManager::~BadgeManager() { } } -PlatformResult BadgeManager::SetBadgeCount(const std::string& app_id, - unsigned int count) { +PlatformResult BadgeManager::SetBadgeCount(const std::string &app_id, unsigned int count) { LoggerD("Enter"); SLoggerD("app_id : %s ", app_id.c_str()); if (!IsAppInstalled(app_id)) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "InvalidValues error : app_id", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "InvalidValues error : app_id", ("Application is not installed")); } @@ -67,7 +64,8 @@ PlatformResult BadgeManager::SetBadgeCount(const std::string& app_id, int ret = badge_is_existing(app_id_str, &badge_exist); if (ret != BADGE_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("Unknown error: %d, %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", + ("Unknown error: %d, %s", ret, get_error_message(ret))); } LoggerD("badge exist : %d", badge_exist); @@ -83,8 +81,7 @@ PlatformResult BadgeManager::SetBadgeCount(const std::string& app_id, #else } else if (ret == BADGE_ERROR_INVALID_PARAMETER) { #endif - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid values error"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid values error"); } else if (ret != BADGE_ERROR_NONE && ret != BADGE_ERROR_ALREADY_EXIST) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Unknown error"); } @@ -102,25 +99,23 @@ PlatformResult BadgeManager::SetBadgeCount(const std::string& app_id, #else } else if (ret == BADGE_ERROR_INVALID_PARAMETER) { #endif - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid values error"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid values error"); } else if (ret != BADGE_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("Unknown error : %d, %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", + ("Unknown error : %d, %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult BadgeManager::GetBadgeCount(const std::string& app_id, - unsigned int *count) { +PlatformResult BadgeManager::GetBadgeCount(const std::string &app_id, unsigned int *count) { LoggerD("Enter"); SLoggerD("app_id : %s ", app_id.c_str()); Assert(count); if (!IsAppInstalled(app_id)) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "InvalidValues error : app_id", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "InvalidValues error : app_id", ("Application is not installed")); } @@ -128,8 +123,7 @@ PlatformResult BadgeManager::GetBadgeCount(const std::string& app_id, int ret = badge_is_existing(app_id.c_str(), &badge_exist); if (ret != BADGE_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while checking badge.", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while checking badge.", ("Unknown error : %d, %s", ret, get_error_message(ret))); } @@ -156,8 +150,7 @@ PlatformResult BadgeManager::GetBadgeCount(const std::string& app_id, #else case BADGE_ERROR_INVALID_PARAMETER: #endif - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "InvalidValues error : app_id"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "InvalidValues error : app_id"); default: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("Unknown error : %d, %s", ret, get_error_message(ret))); @@ -174,8 +167,7 @@ PlatformResult BadgeManager::AddChangeListener(const JsonObject &obj) { if (!is_cb_registered_) { ret = badge_register_changed_cb(badge_changed_cb, this); if (ret != BADGE_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while adding listener.", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while adding listener.", ("Unknown error: %d, %s", ret, get_error_message(ret))); } is_cb_registered_ = true; @@ -193,8 +185,7 @@ PlatformResult BadgeManager::RemoveChangeListener(const JsonObject &obj) { if (watched_applications_.empty() && is_cb_registered_) { int ret = badge_unregister_changed_cb(badge_changed_cb); if (ret != BADGE_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while removing listener.", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while removing listener.", ("Unknown error : %d, %s", ret, get_error_message(ret))); } is_cb_registered_ = false; @@ -203,10 +194,10 @@ PlatformResult BadgeManager::RemoveChangeListener(const JsonObject &obj) { return PlatformResult(ErrorCode::NO_ERROR); } -void BadgeManager::badge_changed_cb(unsigned int action, const char *pkgname, - unsigned int count, void *user_data) { +void BadgeManager::badge_changed_cb(unsigned int action, const char *pkgname, unsigned int count, + void *user_data) { LoggerD("Enter"); - BadgeManager* that = static_cast(user_data); + BadgeManager *that = static_cast(user_data); if (action == BADGE_ACTION_UPDATE && that->watched_applications_.find(pkgname) != that->watched_applications_.end()) { picojson::value response = picojson::value(picojson::object()); @@ -230,7 +221,7 @@ bool BadgeManager::IsAppInstalled(const std::string &app_id) { // if app information is hold in global database: // /usr/dbspace/.pkgmgr_parser.db below line should be used - //int ret = pkgmgrinfo_appinfo_get_appinfo(app_id.c_str(), &pkgmgrinfo_appinfo); + // int ret = pkgmgrinfo_appinfo_get_appinfo(app_id.c_str(), &pkgmgrinfo_appinfo); // if app information is hold in users database like: // /home/app/.applications/dbspace/.pkgmgr_parser.db below line should be used diff --git a/src/badge/badge_manager.h b/src/badge/badge_manager.h old mode 100755 new mode 100644 index 48e64b6..33ad5fc --- a/src/badge/badge_manager.h +++ b/src/badge/badge_manager.h @@ -17,8 +17,8 @@ #ifndef BADGE_BADGE_MANAGER_H_ #define BADGE_BADGE_MANAGER_H_ -#include #include +#include #include "common/logger.h" #include "common/picojson.h" @@ -39,10 +39,8 @@ class BadgeManager { explicit BadgeManager(BadgeInstance& instance); ~BadgeManager(); - common::PlatformResult SetBadgeCount(const std::string& app_id, - unsigned int count); - common::PlatformResult GetBadgeCount(const std::string& app_id, - unsigned int* count); + common::PlatformResult SetBadgeCount(const std::string& app_id, unsigned int count); + common::PlatformResult GetBadgeCount(const std::string& app_id, unsigned int* count); common::PlatformResult AddChangeListener(const JsonObject& obj); common::PlatformResult RemoveChangeListener(const JsonObject& obj); static void badge_changed_cb(unsigned int, const char*, unsigned int, void*); diff --git a/src/bluetooth/bluetooth_adapter.cc b/src/bluetooth/bluetooth_adapter.cc old mode 100755 new mode 100644 index 126de34..f7a0007 --- a/src/bluetooth/bluetooth_adapter.cc +++ b/src/bluetooth/bluetooth_adapter.cc @@ -25,8 +25,8 @@ #include #endif -#include #include +#include #include "bluetooth_internal.h" #include "common/converter.h" @@ -53,10 +53,10 @@ namespace { const std::string kAction = "action"; const std::string kData = "data"; const std::string kName = "name"; -//adapter +// adapter const std::string kAdapterPowered = "powered"; const std::string kAdapterVisible = "visible"; -//AdapterChangeCallback +// AdapterChangeCallback const std::string kOnStateChanged = "onstatechanged"; const std::string kOnNameChanged = "onnamechanged"; const std::string kOnVisibilityChanged = "onvisibilitychanged"; @@ -64,21 +64,21 @@ const std::string kAdapterChangeCallbackEvent = "BluetoothAdapterChangeCallback" // BluetoothProfileHandler const std::string kBluetoothProfileHealth = "HEALTH"; const std::string kFeatureBluetoothHealth = "tizen.org/feature/network.bluetooth.health"; -//DiscoverDevicesCallback +// DiscoverDevicesCallback const std::string kOnDiscoverStarted = "onstarted"; const std::string kOnDiscoverFound = "ondevicefound"; const std::string kOnDiscoverDisappeared = "ondevicedisappeared"; const std::string kOnDiscoverFinished = "onfinished"; const std::string kAdapterDiscoverSuccessEvent = "BluetoothDiscoverDevicesSuccessCallback"; const std::string kAdapterDiscoverErrorEvent = "BluetoothDiscoverDevicesErrorCallback"; -//device +// device const std::string kDeviceAddress = "address"; const unsigned short kTimeout = 180; } static bool IsValidAddress(const std::string& address) { static pcrecpp::RE re("(([0-9a-zA-Z]+):)+([0-9a-zA-Z]+)"); - static std::string compare_address = "00:12:47:08:9A:A6"; + static std::string compare_address = "00:12:47:08:9A:A6"; if (!re.FullMatch(address)) { LoggerE("Invalid address"); @@ -108,7 +108,7 @@ static bool IsValidUUID(const std::string& uuid) { return true; } -void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void *user_data) { +void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void* user_data) { LoggerD("Entered"); BluetoothAdapter* adapter = static_cast(user_data); @@ -122,7 +122,7 @@ void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void adapter->is_powered_ = powered; if (powered) { - //update visible state if bluetooth device has been turned on + // update visible state if bluetooth device has been turned on adapter->is_visible_ = adapter->get_visible(); } @@ -142,21 +142,21 @@ void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void } PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - switch(result) { + switch (result) { case BT_ERROR_NONE: case BT_ERROR_ALREADY_DONE: case BT_ERROR_NOT_ENABLED: - //do nothing + // do nothing break; case BT_ERROR_NOW_IN_PROGRESS: ret = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is busy", - ("StateChangedCB result: %d (%s)", result, get_error_message(result))); + ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is busy", + ("StateChangedCB result: %d (%s)", result, get_error_message(result))); break; default: ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("StateChangedCB result: %d (%s)", result, get_error_message(result))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("StateChangedCB result: %d (%s)", result, get_error_message(result))); } adapter->instance_.AsyncResponse(adapter->user_request_callback_[SET_POWERED], ret); @@ -164,7 +164,7 @@ void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void } } -void BluetoothAdapter::NameChangedCB(char *name, void *user_data) { +void BluetoothAdapter::NameChangedCB(char* name, void* user_data) { LoggerD("Entered"); BluetoothAdapter* adapter = static_cast(user_data); @@ -189,7 +189,8 @@ void BluetoothAdapter::NameChangedCB(char *name, void *user_data) { } } -void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mode_e mode, void *user_data) { +void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mode_e mode, + void* user_data) { LoggerD("Entered"); BluetoothAdapter* adapter = static_cast(user_data); @@ -217,8 +218,8 @@ void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mod if (BT_ERROR_NONE != result) { ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("VisibilityChangedCB error: %d (%s)", result, get_error_message(result))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("VisibilityChangedCB error: %d (%s)", result, get_error_message(result))); } adapter->instance_.AsyncResponse(adapter->user_request_callback_[SET_VISIBLE], ret); @@ -226,8 +227,7 @@ void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mod } } -static bool ForeachBondedDevicesCB(bt_device_info_s *device_info, void *user_data) -{ +static bool ForeachBondedDevicesCB(bt_device_info_s* device_info, void* user_data) { LoggerD("Entered"); if (nullptr == user_data) { LoggerD("user data is NULL."); @@ -242,7 +242,9 @@ static bool ForeachBondedDevicesCB(bt_device_info_s *device_info, void *user_dat picojson::array* array = static_cast(user_data); for (auto iter = array->begin(); iter != array->end(); iter++) { if (!strcmp(device_info->remote_address, ((*iter).get()) - .find(kDeviceAddress)->second.get().c_str())) { + .find(kDeviceAddress) + ->second.get() + .c_str())) { BluetoothDevice::ToJson(device_info, &iter->get()); return true; } @@ -254,12 +256,10 @@ static bool ForeachBondedDevicesCB(bt_device_info_s *device_info, void *user_dat return true; } -void BluetoothAdapter::DiscoveryStateChangedCB( - int result, - bt_adapter_device_discovery_state_e discovery_state, - bt_adapter_device_discovery_info_s *discovery_info, - void *user_data) -{ +void BluetoothAdapter::DiscoveryStateChangedCB(int result, + bt_adapter_device_discovery_state_e discovery_state, + bt_adapter_device_discovery_info_s* discovery_info, + void* user_data) { LoggerD("Entered"); BluetoothAdapter* adapter = static_cast(user_data); @@ -271,11 +271,11 @@ void BluetoothAdapter::DiscoveryStateChangedCB( picojson::value value = picojson::value(picojson::object()); picojson::object* data_obj = &value.get(); - switch(discovery_state) { + switch (discovery_state) { case BT_ADAPTER_DEVICE_DISCOVERY_STARTED: { if (adapter->user_request_list_[DISCOVER_DEVICES]) { if (BT_ERROR_NONE == result) { - //store addresses of previously found devices into disappeared_addresses + // store addresses of previously found devices into disappeared_addresses adapter->disappeared_addresses_ = adapter->discovered_addresses_; adapter->discovered_addresses_.clear(); adapter->discovered_devices_.clear(); @@ -300,8 +300,8 @@ void BluetoothAdapter::DiscoveryStateChangedCB( picojson::value disapeared_val = picojson::value(picojson::object()); picojson::object* disapeared_obj = &disapeared_val.get(); - disapeared_obj->insert(std::make_pair(kAction, - picojson::value(kOnDiscoverDisappeared))); + disapeared_obj->insert( + std::make_pair(kAction, picojson::value(kOnDiscoverDisappeared))); disapeared_obj->insert(std::make_pair(kData, picojson::value(it))); adapter->instance_.FireEvent(kAdapterDiscoverSuccessEvent, disapeared_val); @@ -318,7 +318,8 @@ void BluetoothAdapter::DiscoveryStateChangedCB( std::shared_ptr(new picojson::value(picojson::object())); ReportSuccess(response->get()); - adapter->instance_.AsyncResponse(adapter->user_request_callback_[STOP_DISCOVERY], response); + adapter->instance_.AsyncResponse(adapter->user_request_callback_[STOP_DISCOVERY], + response); adapter->user_request_list_[STOP_DISCOVERY] = false; } @@ -328,13 +329,13 @@ void BluetoothAdapter::DiscoveryStateChangedCB( case BT_ADAPTER_DEVICE_DISCOVERY_FOUND: { if (adapter->user_request_list_[DISCOVER_DEVICES]) { if (BT_ERROR_NONE == result && - adapter->discovered_addresses_.insert( - discovery_info->remote_address).second) { + adapter->discovered_addresses_.insert(discovery_info->remote_address).second) { adapter->disappeared_addresses_.erase(discovery_info->remote_address); data_obj->insert(std::make_pair(kAction, picojson::value(kOnDiscoverFound))); - picojson::value& data = data_obj->insert(std::make_pair(kData, - picojson::value(picojson::object()))).first->second; + picojson::value& data = + data_obj->insert(std::make_pair(kData, picojson::value(picojson::object()))) + .first->second; BluetoothDevice::ToJson(discovery_info, &data.get()); adapter->discovered_devices_.push_back(data); @@ -350,16 +351,15 @@ void BluetoothAdapter::DiscoveryStateChangedCB( } } -BluetoothAdapter::BluetoothAdapter(BluetoothInstance& instance) : - is_visible_(false), - is_powered_(false), - is_initialized_(false), - user_request_list_(), - user_request_callback_(), - requested_powered_(), - requested_visibility_(), - instance_(instance) -{ +BluetoothAdapter::BluetoothAdapter(BluetoothInstance& instance) + : is_visible_(false), + is_powered_(false), + is_initialized_(false), + user_request_list_(), + user_request_callback_(), + requested_powered_(), + requested_visibility_(), + instance_(instance) { LoggerD("Entered"); if (BT_ERROR_NONE == bt_initialize()) { LoggerD("Bluetooth service is initialized."); @@ -457,8 +457,8 @@ bool BluetoothAdapter::is_initialized() const { void BluetoothAdapter::SetName(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -487,24 +487,25 @@ void BluetoothAdapter::SetName(const picojson::value& data, picojson::object& ou this->user_request_callback_[SET_NAME] = callback_handle; int ret = bt_adapter_set_name(name.c_str()); - switch(ret) { + switch (ret) { case BT_ERROR_NONE: - //bt_adapter_name_changed_cb() will be invoked - //if this function returns #BT_ERROR_NONE + // bt_adapter_name_changed_cb() will be invoked + // if this function returns #BT_ERROR_NONE this->requested_name_ = name; break; case BT_ERROR_INVALID_PARAMETER: - result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_adapter_set_name error: %d (%s)", ret, get_error_message(ret))); + result = + LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_adapter_set_name error: %d (%s)", ret, get_error_message(ret))); break; default: - result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_adapter_set_name error: %d (%s)", ret, get_error_message(ret))); + result = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_adapter_set_name error: %d (%s)", ret, get_error_message(ret))); } } else { - result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + result = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } if (result.IsError()) { @@ -516,11 +517,12 @@ void BluetoothAdapter::SetName(const picojson::value& data, picojson::object& ou void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - LoggerW("DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. " - "Let the user turn on/off Bluetooth through the Settings application instead."); + LoggerW( + "DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. " + "Let the user turn on/off Bluetooth through the Settings application instead."); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -544,26 +546,23 @@ void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& int err = 0; if ((err = app_control_create(&service)) != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control create failed", - ("app control create failed: %d", err)); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control create failed", + ("app control create failed: %d", err)); } if (ret.IsSuccess()) { err = app_control_set_operation(service, "http://tizen.org/appcontrol/operation/edit"); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control set operation failed", - ("app control set operation failed: %d", err)); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control set operation failed", + ("app control set operation failed: %d", err)); } } if (ret.IsSuccess()) { err = app_control_set_mime(service, "application/x-bluetooth-on-off"); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control set mime failed", - ("app control set mime failed: %d", err)); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control set mime failed", + ("app control set mime failed: %d", err)); } } @@ -573,35 +572,35 @@ void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& double callback_handle; }; - UserData* user_data = new UserData{ this, callback_handle }; + UserData* user_data = new UserData{this, callback_handle}; - err = app_control_send_launch_request(service, []( - app_control_h request, app_control_h reply, - app_control_result_e r, void* user_data) { - LoggerD("app_control_send_launch_request() callback"); + err = app_control_send_launch_request( + service, + [](app_control_h request, app_control_h reply, app_control_result_e r, void* user_data) { + LoggerD("app_control_send_launch_request() callback"); - UserData* data = static_cast(user_data); + UserData* data = static_cast(user_data); - char* result = nullptr; - app_control_get_extra_data(reply, "result", &result); + char* result = nullptr; + app_control_get_extra_data(reply, "result", &result); - if (result && strcmp(result, "success") == 0) { - LoggerD("bt onoff: %s", result); - free(result); - } else { - LoggerE("app control setPowered failed"); - data->adapter->instance_.AsyncResponse( - data->callback_handle, - LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control setPowered failed")); - } + if (result && strcmp(result, "success") == 0) { + LoggerD("bt onoff: %s", result); + free(result); + } else { + LoggerE("app control setPowered failed"); + data->adapter->instance_.AsyncResponse( + data->callback_handle, + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control setPowered failed")); + } - delete data; - }, user_data); + delete data; + }, + user_data); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control set launch request failed", - ("app control set launch request failed: %d", err)); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control set launch request failed", + ("app control set launch request failed: %d", err)); delete user_data; } else { this->requested_powered_ = new_powered; @@ -612,9 +611,8 @@ void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& err = app_control_destroy(service); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control destroy failed", - ("app control destroy failed: %d", err)); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control destroy failed", + ("app control destroy failed: %d", err)); } if (!ret) { @@ -639,8 +637,8 @@ void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothManager, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothManager, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -662,7 +660,6 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& } if (ret.IsSuccess() && this->get_powered()) { - bt_adapter_visibility_mode_e new_mode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE; if (visible) { if (0 == new_timeout) { @@ -674,16 +671,16 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& bt_adapter_visibility_mode_e cur_mode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE; int cur_timeout = 0; - int ntv_ret = bt_adapter_get_visibility(&cur_mode , &cur_timeout); + int ntv_ret = bt_adapter_get_visibility(&cur_mode, &cur_timeout); if (BT_ERROR_NONE != ntv_ret) { ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_adapter_get_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_adapter_get_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } if (ret.IsSuccess() && new_mode == cur_mode) { if (BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE != new_mode || - (unsigned int) cur_timeout == new_timeout) { + (unsigned int)cur_timeout == new_timeout) { instance_.AsyncResponse(callback_handle, ret); return; } @@ -695,62 +692,70 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& int err = 0; if ((err = app_control_create(&service)) != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control create failed", - ("app control create failed: %d (%s)", err, get_error_message(err))); + ret = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control create failed", + ("app control create failed: %d (%s)", err, get_error_message(err))); } if (ret.IsSuccess()) { err = app_control_set_operation(service, "http://tizen.org/appcontrol/operation/edit"); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control set operation failed", - ("app control set operation failed: %d (%s)", err, get_error_message(err))); + ret = LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "app control set operation failed", + ("app control set operation failed: %d (%s)", err, get_error_message(err))); } } if (ret.IsSuccess()) { err = app_control_set_mime(service, "application/x-bluetooth-visibility"); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control set mime failed", - ("app control set mime failed: %d (%s)", err, get_error_message(err))); + ret = LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "app control set mime failed", + ("app control set mime failed: %d (%s)", err, get_error_message(err))); } } if (ret.IsSuccess()) { - const void* t_param[] = { this, &ret, &new_mode, &callback_handle }; - - err = app_control_send_launch_request(service, []( - app_control_h request, app_control_h reply, - app_control_result_e r, void* user_data) { - BluetoothAdapter* self = static_cast(((void**) user_data)[0]); - PlatformResult* p_ret = static_cast(((void**) user_data)[1]); - bt_adapter_visibility_mode_e* p_new_mode = static_cast(((void**) user_data)[2]); - double* p_callback_handle = static_cast(((void**) user_data)[3]); - - char* result = nullptr; - app_control_get_extra_data(reply, "result", &result); - LoggerD("bt visibility onoff: %s", result); - - if (strcmp(result, "success") == 0) { - self->requested_visibility_ = *p_new_mode; - self->user_request_list_[SET_VISIBLE] = true; - self->user_request_callback_[SET_VISIBLE] = *p_callback_handle; - } else { - *p_ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control setVisible failed"); - } - free(result); - }, t_param); + const void* t_param[] = {this, &ret, &new_mode, &callback_handle}; + + err = app_control_send_launch_request( + service, + [](app_control_h request, app_control_h reply, app_control_result_e r, + void* user_data) { + BluetoothAdapter* self = static_cast(((void**)user_data)[0]); + PlatformResult* p_ret = static_cast(((void**)user_data)[1]); + bt_adapter_visibility_mode_e* p_new_mode = + static_cast(((void**)user_data)[2]); + double* p_callback_handle = static_cast(((void**)user_data)[3]); + + char* result = nullptr; + app_control_get_extra_data(reply, "result", &result); + LoggerD("bt visibility onoff: %s", result); + + if (strcmp(result, "success") == 0) { + self->requested_visibility_ = *p_new_mode; + self->user_request_list_[SET_VISIBLE] = true; + self->user_request_callback_[SET_VISIBLE] = *p_callback_handle; + } else { + *p_ret = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control setVisible failed"); + } + free(result); + }, + t_param); if (err != APP_CONTROL_ERROR_NONE) { ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "app control set launch request failed", - ("app control set launch request failed: %d (%s)", err, get_error_message(err))); + ErrorCode::UNKNOWN_ERR, "app control set launch request failed", + ("app control set launch request failed: %d (%s)", err, get_error_message(err))); } } err = app_control_destroy(service); if (err != APP_CONTROL_ERROR_NONE) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "app control destroy failed", - ("app control destroy failed: %d (%s)", err, get_error_message(err))); + ret = LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "app control destroy failed", + ("app control destroy failed: %d (%s)", err, get_error_message(err))); } #else this->requested_visibility_ = new_mode; @@ -758,25 +763,26 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& this->user_request_callback_[SET_VISIBLE] = callback_handle; int ntv_ret = bt_adapter_set_visibility(new_mode, new_timeout); - switch(ntv_ret) { + switch (ntv_ret) { case BT_ERROR_NONE: - //bt_adapter_visibility_mode_changed_cb() will be invoked - //if this function returns #BT_ERROR_NONE + // bt_adapter_visibility_mode_changed_cb() will be invoked + // if this function returns #BT_ERROR_NONE break; case BT_ERROR_INVALID_PARAMETER: ret = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_adapter_set_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_adapter_set_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); break; default: ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_adapter_set_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_adapter_set_visibility error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } #endif } - } else if (ret.IsSuccess()){ - ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + } else if (ret.IsSuccess()) { + ret = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } instance_.AsyncResponse(callback_handle, ret); @@ -785,8 +791,8 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& void BluetoothAdapter::DiscoverDevices(const picojson::value& /* data */, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); @@ -799,8 +805,8 @@ void BluetoothAdapter::DiscoverDevices(const picojson::value& /* data */, picojs } if (result.IsSuccess() && !get_powered()) { - result = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + result = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } if (result.IsSuccess()) { @@ -811,17 +817,19 @@ void BluetoothAdapter::DiscoverDevices(const picojson::value& /* data */, picojs std::shared_ptr(new picojson::value(picojson::object())); LogAndReportError(result, &response->get()); - TaskQueue::GetInstance().Async([this](const std::shared_ptr& result) { - instance_.FireEvent(kAdapterDiscoverErrorEvent, result); - }, response); + TaskQueue::GetInstance().Async( + [this](const std::shared_ptr& result) { + instance_.FireEvent(kAdapterDiscoverErrorEvent, result); + }, + response); } } void BluetoothAdapter::StopDiscovery(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); @@ -847,20 +855,21 @@ void BluetoothAdapter::StopDiscovery(const picojson::value& data, picojson::obje this->user_request_list_[STOP_DISCOVERY] = true; this->user_request_callback_[STOP_DISCOVERY] = callback_handle; int ret = bt_adapter_stop_device_discovery(); - switch(ret) { + switch (ret) { case BT_ERROR_NONE: { - //This function invokes bt_adapter_device_discovery_state_changed_cb(). + // This function invokes bt_adapter_device_discovery_state_changed_cb(). break; } default: { this->user_request_list_[STOP_DISCOVERY] = false; result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_adapter_stop_device_discovery error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_adapter_stop_device_discovery error: %d (%s)", ret, get_error_message(ret))); } } } else if (result.IsSuccess()) { - result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + result = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } if (result.IsError()) { @@ -871,8 +880,8 @@ void BluetoothAdapter::StopDiscovery(const picojson::value& data, picojson::obje void BluetoothAdapter::GetKnownDevices(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); @@ -887,8 +896,9 @@ void BluetoothAdapter::GetKnownDevices(const picojson::value& data, picojson::ob picojson::object& response_obj = response->get(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - picojson::array& array = result_obj.insert(std::make_pair("devices", picojson::value( - picojson::array()))).first->second.get(); + picojson::array& array = + result_obj.insert(std::make_pair("devices", picojson::value(picojson::array()))) + .first->second.get(); array = discovered_devices_; @@ -896,38 +906,37 @@ void BluetoothAdapter::GetKnownDevices(const picojson::value& data, picojson::ob if (BT_ERROR_NONE == ntv_ret) { ReportSuccess(result, response_obj); } else { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_adapter_foreach_bonded_device error %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_adapter_foreach_bonded_device error %d (%s)", ntv_ret, + get_error_message(ntv_ret))); } } else if (ret.IsSuccess()) { - ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, + "Bluetooth device is turned off"); } if (ret.IsError()) { LogAndReportError(ret, &response->get()); } }; - auto get_known_devices_response = [this, callback_handle]( - const std::shared_ptr& response) -> void { + auto get_known_devices_response = + [this, callback_handle](const std::shared_ptr& response) -> void { instance_.SyncResponse(callback_handle, response); }; auto queue_data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_known_devices, - get_known_devices_response, - queue_data); + TaskQueue::GetInstance().Queue(get_known_devices, get_known_devices_response, + queue_data); ReportSuccess(out); } -void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& out) { +void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -945,7 +954,7 @@ void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& } if (ret.IsSuccess() && this->get_powered()) { picojson::object& response_obj = response->get(); - bt_device_info_s *info = nullptr; + bt_device_info_s* info = nullptr; if (bt_adapter_get_bonded_device_info(address.c_str(), &info) == BT_ERROR_NONE && info != nullptr) { @@ -960,21 +969,23 @@ void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& auto is_address = discovered_addresses_.find(address); if (is_address != discovered_addresses_.end()) { - for (auto iter = discovered_devices_.begin(); - iter != discovered_devices_.end(); iter++) { + for (auto iter = discovered_devices_.begin(); iter != discovered_devices_.end(); iter++) { if (!strcmp(address.c_str(), ((*iter).get()) - .find(kDeviceAddress)->second.get().c_str())) { + .find(kDeviceAddress) + ->second.get() + .c_str())) { ReportSuccess(*iter, response_obj); return; } } } else { ret = LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "There is no device with the given address", - ("There is no device with the given address: %s", address.c_str())); + ErrorCode::NOT_FOUND_ERR, "There is no device with the given address", + ("There is no device with the given address: %s", address.c_str())); } } else if (ret.IsSuccess()) { - ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, + "Bluetooth device is turned off"); } if (ret.IsError()) { @@ -982,25 +993,23 @@ void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& } }; - auto get_device_response = [this, callback_handle]( - const std::shared_ptr& response) -> void { + auto get_device_response = + [this, callback_handle](const std::shared_ptr& response) -> void { instance_.SyncResponse(callback_handle, response); }; auto queue_data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - get_device, - get_device_response, - queue_data); + TaskQueue::GetInstance().Queue(get_device, get_device_response, queue_data); ReportSuccess(out); } class BondingHandler { public: - BondingHandler(BluetoothInstance& instance, double callback_handle, const std::string& address) : - instance_(instance) ,callback_handle_(callback_handle), address_(address) {} + BondingHandler(BluetoothInstance& instance, double callback_handle, const std::string& address) + : instance_(instance), callback_handle_(callback_handle), address_(address) { + } void set_address(const std::string& address) { address_ = address; @@ -1031,8 +1040,8 @@ class BondingHandler { void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -1041,10 +1050,9 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje auto create_bonding = [address, callback_handle, this]() -> void { PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); - if(!IsValidAddress(address)) { - result = LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Wrong address", - ("Wrong address: %s", address.c_str())); + if (!IsValidAddress(address)) { + result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Wrong address", + ("Wrong address: %s", address.c_str())); } if (result.IsSuccess() && !this->is_initialized()) { @@ -1052,10 +1060,8 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje } if (result.IsSuccess() && this->get_powered()) { - - auto bond_create_callback = [](int callback_result, - bt_device_info_s *device_info, - void *user_data) { + auto bond_create_callback = [](int callback_result, bt_device_info_s* device_info, + void* user_data) { LoggerD("bond_create_callback"); BondingHandler* handler = static_cast(user_data); @@ -1073,17 +1079,17 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje std::shared_ptr(new picojson::value(picojson::object())); std::string address(handler->address()); - for(size_t i = 0; i < handler->address().length(); i++) { + for (size_t i = 0; i < handler->address().length(); i++) { address[i] = toupper(handler->address()[i]); } std::string remote_address(device_info->remote_address); - for(size_t i = 0; i < sizeof(device_info->remote_address); i++) { + for (size_t i = 0; i < sizeof(device_info->remote_address); i++) { remote_address[i] = toupper(device_info->remote_address[i]); } if (!strcmp(address.c_str(), remote_address.c_str())) { // requested event - if (BT_ERROR_NONE == callback_result && nullptr != device_info ) { + if (BT_ERROR_NONE == callback_result && nullptr != device_info) { picojson::object& response_obj = response->get(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -1092,15 +1098,13 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje result_obj["address"] = picojson::value(handler->address()); ReportSuccess(result, response_obj); } else if (BT_ERROR_REMOTE_DEVICE_NOT_FOUND == callback_result) { - ret = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Not found", - ("bond_create_callback result: %d (%s)", callback_result, - get_error_message(callback_result))); + ret = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Not found", + ("bond_create_callback result: %d (%s)", callback_result, + get_error_message(callback_result))); } else { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bond_create_callback result: %d (%s)", callback_result, - get_error_message(callback_result))); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bond_create_callback result: %d (%s)", callback_result, + get_error_message(callback_result))); } handler->Invoke(ret, response); @@ -1115,28 +1119,25 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje bt_device_set_bond_created_cb(bond_create_callback, handler); int ret = bt_device_create_bond(address.c_str()); - switch(ret) { - case BT_ERROR_NONE: - { + switch (ret) { + case BT_ERROR_NONE: { LoggerD("bt_device_create_bond() succeeded"); break; } - case BT_ERROR_INVALID_PARAMETER: - { + case BT_ERROR_INVALID_PARAMETER: { bt_device_unset_bond_created_cb(); delete handler; result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_device_create_bond error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_device_create_bond error: %d (%s)", ret, get_error_message(ret))); break; } - default: - { + default: { bt_device_unset_bond_created_cb(); delete handler; result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_device_create_bond error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_device_create_bond error: %d (%s)", ret, get_error_message(ret))); } } } else if (result.IsSuccess()) { @@ -1152,12 +1153,11 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje ReportSuccess(out); } -void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::object& out) -{ +void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothGap, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -1166,29 +1166,26 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj auto destroy_bonding = [address, callback_handle, this]() -> void { PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); - if(!IsValidAddress(address)) { - result = LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Wrong address", - ("Wrong address: %s", address.c_str())); + if (!IsValidAddress(address)) { + result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Wrong address", + ("Wrong address: %s", address.c_str())); } if (result.IsSuccess() && !this->is_initialized()) { result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Bluetooth service is not initialized."); } if (result.IsSuccess() && this->get_powered()) { - bt_device_info_s *device_info = nullptr; + bt_device_info_s* device_info = nullptr; int ret = bt_adapter_get_bonded_device_info(address.c_str(), &device_info); if (BT_ERROR_NONE != ret || nullptr == device_info) { - result = LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Not found", - ("There is no bonding %d (%s)", ret, get_error_message(ret))); + result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Not found", + ("There is no bonding %d (%s)", ret, get_error_message(ret))); } else { bt_adapter_free_device_info(device_info); - auto bond_destroy_callback = [](int callback_result, - char *remote_address, - void *user_data) { + auto bond_destroy_callback = [](int callback_result, char* remote_address, + void* user_data) { LoggerD("bond_destroy_callback"); BondingHandler* handler = static_cast(user_data); @@ -1213,11 +1210,9 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj if (!strcmp(address.c_str(), r_address.c_str())) { // requested event if (BT_ERROR_NONE != callback_result) { - ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bond_destroy_callback result error: %d (%s)", - callback_result, - get_error_message(callback_result))); + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bond_destroy_callback result error: %d (%s)", + callback_result, get_error_message(callback_result))); } handler->Invoke(ret, response); @@ -1233,34 +1228,31 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj int ret = bt_device_destroy_bond(address.c_str()); - switch(ret) { - case BT_ERROR_NONE: - { + switch (ret) { + case BT_ERROR_NONE: { LoggerD("bt_device_destroy_bond() succeeded"); break; } - case BT_ERROR_INVALID_PARAMETER: - { + case BT_ERROR_INVALID_PARAMETER: { bt_device_unset_bond_destroyed_cb(); delete handler; result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_device_destroy_bond error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_device_destroy_bond error: %d (%s)", ret, get_error_message(ret))); break; } - default: - { + default: { bt_device_unset_bond_destroyed_cb(); delete handler; result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_device_destroy_bond error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_device_destroy_bond error: %d (%s)", ret, get_error_message(ret))); } } } - } else if (result.IsSuccess()) { - result = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + } else if (result.IsSuccess()) { + result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, + "Bluetooth device is turned off"); } if (result.IsError()) { @@ -1271,11 +1263,12 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj ReportSuccess(out); } -void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, picojson::object& out) { +void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, + picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -1290,9 +1283,8 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, } if (result.IsSuccess() && !IsValidUUID(uuid)) { - result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", - ("Wrong UUID: %s", uuid.c_str())); + result = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", + ("Wrong UUID: %s", uuid.c_str())); } if (result.IsSuccess() && this->get_powered()) { @@ -1301,8 +1293,8 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, if (BT_ERROR_NONE == ret && is_registered) { result = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Already requested", - ("bt_adapter_is_service_used error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Already requested", + ("bt_adapter_is_service_used error: %d (%s)", ret, get_error_message(ret))); } else { int socket = -1; ret = bt_socket_create_rfcomm(uuid.c_str(), &socket); @@ -1310,29 +1302,28 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, switch (ret) { case BT_ERROR_NONE: { int ret_in = bt_socket_listen_and_accept_rfcomm(socket, 0); - switch(ret_in) { + switch (ret_in) { case BT_ERROR_NONE: { LoggerD("bt_socket_listen() succeeded"); bt_socket_set_connection_state_changed_cb(OnSocketConnected, this); - registered_uuids_.insert(std::make_pair(uuid, - std::make_pair(socket, false))); + registered_uuids_.insert(std::make_pair(uuid, std::make_pair(socket, false))); ReportSuccess(response->get()); break; } case BT_ERROR_INVALID_PARAMETER: { - result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_socket_listen_and_accept_rfcomm error: %d (%s)", ret_in, get_error_message(ret_in))); + result = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_socket_listen_and_accept_rfcomm error: %d (%s)", + ret_in, get_error_message(ret_in))); break; } default: { - result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error", - ("bt_socket_listen_and_accept_rfcomm error: %d (%s)", ret_in, get_error_message(ret_in))); + result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", + ("bt_socket_listen_and_accept_rfcomm error: %d (%s)", + ret_in, get_error_message(ret_in))); break; } } @@ -1340,19 +1331,19 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, } case BT_ERROR_INVALID_PARAMETER: result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_socket_create_rfcomm error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_socket_create_rfcomm error: %d (%s)", ret, get_error_message(ret))); break; default: result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error", - ("bt_socket_create_rfcomm error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown error", + ("bt_socket_create_rfcomm error: %d (%s)", ret, get_error_message(ret))); break; } } } else if (result.IsSuccess()) { - result = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, + "Bluetooth device is turned off"); } if (result.IsError()) { @@ -1360,16 +1351,14 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, } }; - auto rfcomm_response = [this, callback_handle](const std::shared_ptr& response) -> void { + auto rfcomm_response = + [this, callback_handle](const std::shared_ptr& response) -> void { instance_.SyncResponse(callback_handle, response); }; auto queue_data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - rfcomm, - rfcomm_response, - queue_data); + TaskQueue::GetInstance().Queue(rfcomm, rfcomm_response, queue_data); ReportSuccess(out); } @@ -1379,9 +1368,8 @@ void BluetoothAdapter::UnregisterUUID(const std::string& uuid, int callback_hand PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidUUID(uuid)) { - result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", - ("Wrong UUID: %s", uuid.c_str())); + result = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", + ("Wrong UUID: %s", uuid.c_str())); } if (result.IsSuccess() && is_powered_) { @@ -1392,18 +1380,17 @@ void BluetoothAdapter::UnregisterUUID(const std::string& uuid, int callback_hand registered_uuids_.erase(iter); } else { result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown exception", - ("bt_socket_destroy_rfcomm error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Unknown exception", + ("bt_socket_destroy_rfcomm error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } } - if (registered_uuids_.empty() && - connection_requests_.empty() && - connected_sockets_.empty()) { + if (registered_uuids_.empty() && connection_requests_.empty() && connected_sockets_.empty()) { bt_socket_unset_connection_state_changed_cb(); } - } else if (result.IsSuccess()){ - result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); + } else if (result.IsSuccess()) { + result = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } instance_.AsyncResponse(callback_handle, result); @@ -1426,8 +1413,8 @@ void BluetoothAdapter::GetBluetoothProfileHandler(const picojson::value& data, } if (!supported) { - result = LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Bluetooth health profile is not supported"); + result = LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Bluetooth health profile is not supported"); } else { LoggerD("BT health profile is supported"); } @@ -1452,8 +1439,8 @@ void BluetoothAdapter::GetAddress(const picojson::value& /* data */, picojson::o LoggerD("Entered"); if (!is_initialized_) { - LogAndReportError(PlatformResult( - ErrorCode::UNKNOWN_ERR, "Bluetooth service is not initialized."), &out); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Bluetooth service is not initialized."), &out); return; } @@ -1481,11 +1468,8 @@ void BluetoothAdapter::GetVisible(const picojson::value& /* data */, picojson::o ReportSuccess(picojson::value(get_visible()), out); } -void BluetoothAdapter::OnSocketConnected( - int result, - bt_socket_connection_state_e state, - bt_socket_connection_s* connection, - void* user_data) { +void BluetoothAdapter::OnSocketConnected(int result, bt_socket_connection_state_e state, + bt_socket_connection_s* connection, void* user_data) { LoggerD("Entered"); BluetoothAdapter* object = static_cast(user_data); @@ -1515,7 +1499,8 @@ void BluetoothAdapter::OnSocketConnected( iter->second.second = true; // Call BluetoothServiceHandler.onconnect - object->instance_.FireEvent("BLUETOOTH_SERVICE_ONCONNECT", BluetoothSocket::ToJson(connection)); + object->instance_.FireEvent("BLUETOOTH_SERVICE_ONCONNECT", + BluetoothSocket::ToJson(connection)); // Update connected_sockets_ object->connected_sockets_.push_back(connection->socket_fd); @@ -1529,8 +1514,7 @@ void BluetoothAdapter::OnSocketConnected( // Update registered_uuids_ state iter->second.second = false; object->RemoveSocket(connection->socket_fd); - } - else { + } else { LoggerW("Disconnecting a connection failed"); } } @@ -1563,8 +1547,8 @@ void BluetoothAdapter::OnSocketConnected( ReportSuccess(BluetoothSocket::ToJson(connection), response->get()); } else { - LogAndReportError(PlatformResult( - ErrorCode::NOT_FOUND_ERR, "Not found"), &response->get()); + LogAndReportError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Not found"), + &response->get()); } // request will be handled, can be safely removed @@ -1587,8 +1571,7 @@ void BluetoothAdapter::OnSocketConnected( bt_socket_unset_data_received_cb(); } - if (object->registered_uuids_.empty() && - object->connection_requests_.empty() && + if (object->registered_uuids_.empty() && object->connection_requests_.empty() && object->connected_sockets_.empty()) { bt_socket_unset_connection_state_changed_cb(); } @@ -1609,8 +1592,7 @@ void BluetoothAdapter::OnSocketReceivedData(bt_socket_received_data_s* data, voi return; } - const auto it = std::find(object->connected_sockets_.begin(), - object->connected_sockets_.end(), + const auto it = std::find(object->connected_sockets_.begin(), object->connected_sockets_.end(), data->socket_fd); if (it == object->connected_sockets_.end()) { @@ -1624,18 +1606,15 @@ void BluetoothAdapter::OnSocketReceivedData(bt_socket_received_data_s* data, voi object->InvokeSocketOnMessageEvent(*it); } -void BluetoothAdapter::ConnectToServiceByUUID( - const std::string& address, - const std::string& uuid, - double callback_handle) { +void BluetoothAdapter::ConnectToServiceByUUID(const std::string& address, const std::string& uuid, + double callback_handle) { LoggerD("Entered"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidUUID(uuid)) { - result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", - ("Wrong UUID: %s", uuid.c_str())); + result = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Wrong UUID", + ("Wrong UUID: %s", uuid.c_str())); } if (result.IsSuccess() && is_powered_) { @@ -1650,7 +1629,7 @@ void BluetoothAdapter::ConnectToServiceByUUID( request->callback_handle_ = callback_handle; std::string r_address(address); - for(size_t i = 0; i < address.length(); i++) { + for (size_t i = 0; i < address.length(); i++) { r_address[i] = toupper(address[i]); } connection_requests_.insert(std::make_pair(r_address, request)); @@ -1662,18 +1641,18 @@ void BluetoothAdapter::ConnectToServiceByUUID( case BT_ERROR_INVALID_PARAMETER: case BT_ERROR_REMOTE_DEVICE_NOT_BONDED: result = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid value", - ("bt_socket_connect_rfcomm error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Invalid value", + ("bt_socket_connect_rfcomm error: %d (%s)", ret, get_error_message(ret))); break; default: result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error", - ("bt_socket_connect_rfcomm error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown error", + ("bt_socket_connect_rfcomm error: %d (%s)", ret, get_error_message(ret))); break; } } else if (result.IsSuccess()) { - result = LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, - "Bluetooth device is turned off"); + result = + LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off"); } if (result.IsError()) { @@ -1681,7 +1660,6 @@ void BluetoothAdapter::ConnectToServiceByUUID( } } - void BluetoothAdapter::InvokeSocketEvent(int id, const char* event) { picojson::value value = picojson::value(picojson::object()); picojson::object& value_obj = value.get(); @@ -1753,8 +1731,8 @@ void BluetoothAdapter::IsServiceConnected(const picojson::value& data, picojson: auto iter = registered_uuids_.find(uuid); if (iter == registered_uuids_.end()) { - LogAndReportError(PlatformResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed."), &out, + LogAndReportError( + PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed."), &out, ("Invalid uuid was passed: %s", uuid.c_str())); return; } @@ -1762,5 +1740,5 @@ void BluetoothAdapter::IsServiceConnected(const picojson::value& data, picojson: ReportSuccess(picojson::value(iter->second.second), out); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_adapter.h b/src/bluetooth/bluetooth_adapter.h old mode 100755 new mode 100644 index ad77af9..5d536d0 --- a/src/bluetooth/bluetooth_adapter.h +++ b/src/bluetooth/bluetooth_adapter.h @@ -17,11 +17,11 @@ #ifndef BLUETOOTH_BLUETOOTH_ADAPTER_H_ #define BLUETOOTH_BLUETOOTH_ADAPTER_H_ -#include #include +#include #include +#include #include -#include #include #include "bluetooth_internal.h" @@ -31,13 +31,7 @@ namespace extension { namespace bluetooth { -enum AdapterAsyncEvent { - SET_POWERED = 0, - SET_NAME, - SET_VISIBLE, - DISCOVER_DEVICES, - STOP_DISCOVERY -}; +enum AdapterAsyncEvent { SET_POWERED = 0, SET_NAME, SET_VISIBLE, DISCOVER_DEVICES, STOP_DISCOVERY }; class BluetoothInstance; @@ -79,7 +73,8 @@ class BluetoothAdapter { /** * Signature: @code void setVisible(mode, successCallback, errorCallback, timeout); @endcode - * JSON: @code data: {method: 'BluetoothAdapter_setVisible', args: {mode: mode, timeout: timeout}} @endcode + * JSON: @code data: {method: 'BluetoothAdapter_setVisible', args: {mode: mode, timeout: timeout}} + * @endcode * Invocation: @code native.call(request, result_callback); @endcode * Return: * @code @@ -96,7 +91,8 @@ class BluetoothAdapter { /** * Signature: @code void discoverDevices(discoveryCallback, errorCallback); @endcode - * JSON: @code data: {method: 'BluetoothAdapter_discoverDevices', args: {discoveryCallbackId: id}} @endcode + * JSON: @code data: {method: 'BluetoothAdapter_discoverDevices', args: {discoveryCallbackId: id}} + * @endcode * Invocation: @code native.callSync(request); @endcode * Return: * @code @@ -181,7 +177,8 @@ class BluetoothAdapter { /** * Signature: @code void destroyBonding(address, successCallback, errorCallback); @endcode - * JSON: @code data: {method: 'BluetoothAdapter_destroyBonding', args: {address: address}} @endcode + * JSON: @code data: {method: 'BluetoothAdapter_destroyBonding', args: {address: address}} + * @endcode * Invocation: @code native.call(request, result_callback); @endcode * Return: * @code @@ -197,7 +194,8 @@ class BluetoothAdapter { void DestroyBonding(const picojson::value& data, picojson::object& out); /** - * Signature: @code void registerRFCOMMServiceByUUID(uuid, name, successCallback, errorCallback); @endcode + * Signature: @code void registerRFCOMMServiceByUUID(uuid, name, successCallback, errorCallback); + * @endcode * JSON: @code data: {method: 'BluetoothAdapter_registerRFCOMMServiceByUUID', * args: {uuid: uuid, name: name}} @endcode * Invocation: @code native.call(request, result_callback); @endcode @@ -297,8 +295,7 @@ class BluetoothAdapter { void set_powered(bool powered); bool is_initialized() const; - void ConnectToServiceByUUID(const std::string& address, - const std::string& uuid, + void ConnectToServiceByUUID(const std::string& address, const std::string& uuid, double callback_handle); const std::list& ReadSocketData(int socket); @@ -311,30 +308,22 @@ class BluetoothAdapter { BluetoothAdapter(const BluetoothAdapter&) = delete; BluetoothAdapter& operator=(const BluetoothAdapter&) = delete; - static void StateChangedCB(int result, - bt_adapter_state_e state, - void *user_data); - static void NameChangedCB(char *name, - void *user_data); - static void VisibilityChangedCB(int result, - bt_adapter_visibility_mode_e mode, - void *user_data); + static void StateChangedCB(int result, bt_adapter_state_e state, void* user_data); + static void NameChangedCB(char* name, void* user_data); + static void VisibilityChangedCB(int result, bt_adapter_visibility_mode_e mode, void* user_data); static void DiscoveryStateChangedCB(int result, bt_adapter_device_discovery_state_e discovery_state, - bt_adapter_device_discovery_info_s *discovery_info, - void *user_data); + bt_adapter_device_discovery_info_s* discovery_info, + void* user_data); void StoreSocketData(bt_socket_received_data_s* data); void RemoveSocket(int socket); - static void OnSocketConnected(int result, - bt_socket_connection_state_e state, - bt_socket_connection_s* connection, - void* user_data); + static void OnSocketConnected(int result, bt_socket_connection_state_e state, + bt_socket_connection_s* connection, void* user_data); - static void OnSocketReceivedData(bt_socket_received_data_s* data, - void* user_data); + static void OnSocketReceivedData(bt_socket_received_data_s* data, void* user_data); void InvokeSocketEvent(int id, const char* event); void InvokeSocketOnMessageEvent(int id); @@ -343,8 +332,8 @@ class BluetoothAdapter { bool is_visible_; bool is_powered_; bool is_initialized_; - bool user_request_list_ [STOP_DISCOVERY + 1]; - double user_request_callback_ [STOP_DISCOVERY + 1]; + bool user_request_list_[STOP_DISCOVERY + 1]; + double user_request_callback_[STOP_DISCOVERY + 1]; bool requested_powered_; bt_adapter_visibility_mode_e requested_visibility_; @@ -368,7 +357,7 @@ class BluetoothAdapter { ConnectedSocketList connected_sockets_; - typedef std::pair BluetoothServicePair; //registered socket - connection state + typedef std::pair BluetoothServicePair; // registered socket - connection state typedef std::map RegisteredUuidMap; RegisteredUuidMap registered_uuids_; @@ -378,7 +367,7 @@ class BluetoothAdapter { BluetoothInstance& instance_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_ADAPTER_H_ +#endif // BLUETOOTH_BLUETOOTH_ADAPTER_H_ diff --git a/src/bluetooth/bluetooth_class.cc b/src/bluetooth/bluetooth_class.cc old mode 100755 new mode 100644 index 4d7f62f..976c151 --- a/src/bluetooth/bluetooth_class.cc +++ b/src/bluetooth/bluetooth_class.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "bluetooth_class.h" #include "common/logger.h" @@ -33,82 +33,80 @@ std::map g_major_enum_map = { {BT_MAJOR_DEVICE_CLASS_WEARABLE, 0x07}, {BT_MAJOR_DEVICE_CLASS_TOY, 0x08}, {BT_MAJOR_DEVICE_CLASS_HEALTH, 0x09}, - {BT_MAJOR_DEVICE_CLASS_UNCATEGORIZED, 0x1F} -}; + {BT_MAJOR_DEVICE_CLASS_UNCATEGORIZED, 0x1F}}; std::map g_minor_enum_map = { {BT_MINOR_DEVICE_CLASS_COMPUTER_UNCATEGORIZED, 0x00}, - {BT_MINOR_DEVICE_CLASS_COMPUTER_DESKTOP_WORKSTATION , 0x01}, - {BT_MINOR_DEVICE_CLASS_COMPUTER_SERVER_CLASS , 0x02}, - {BT_MINOR_DEVICE_CLASS_COMPUTER_LAPTOP , 0x03}, - {BT_MINOR_DEVICE_CLASS_COMPUTER_HANDHELD_PC_OR_PDA , 0x04}, + {BT_MINOR_DEVICE_CLASS_COMPUTER_DESKTOP_WORKSTATION, 0x01}, + {BT_MINOR_DEVICE_CLASS_COMPUTER_SERVER_CLASS, 0x02}, + {BT_MINOR_DEVICE_CLASS_COMPUTER_LAPTOP, 0x03}, + {BT_MINOR_DEVICE_CLASS_COMPUTER_HANDHELD_PC_OR_PDA, 0x04}, {BT_MINOR_DEVICE_CLASS_COMPUTER_PALM_SIZED_PC_OR_PDA, 0x5}, - {BT_MINOR_DEVICE_CLASS_COMPUTER_WEARABLE_COMPUTER , 0x06}, - {BT_MINOR_DEVICE_CLASS_PHONE_UNCATEGORIZED , 0x00}, - {BT_MINOR_DEVICE_CLASS_PHONE_CELLULAR , 0x01}, - {BT_MINOR_DEVICE_CLASS_PHONE_CORDLESS , 0x02}, - {BT_MINOR_DEVICE_CLASS_PHONE_SMART_PHONE , 0x03}, - {BT_MINOR_DEVICE_CLASS_PHONE_WIRED_MODEM_OR_VOICE_GATEWAY , 0x04}, - {BT_MINOR_DEVICE_CLASS_PHONE_COMMON_ISDN_ACCESS , 0x05}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_UNCATEGORIZED , 0x00}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_WEARABLE_HEADSET , 0x01}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HANDS_FREE , 0x02}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_MICROPHONE , 0x04}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_LOUDSPEAKER , 0x05}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HEADPHONES , 0x06}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_PORTABLE_AUDIO , 0x07}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAR_AUDIO , 0x08}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_SET_TOP_BOX , 0x09}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HIFI_AUDIO_DEVICE , 0x0a}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VCR , 0x0b}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CAMERA , 0x0c}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAMCORDER , 0x0d}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_MONITOR , 0x0e}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_DISPLAY_LOUDSPEAKER , 0x0f}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CONFERENCING , 0x10}, - {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_GAMING_TOY , 0x12}, - {BT_MINOR_DEVICE_CLASS_PERIPHERA_UNCATEGORIZED , 0}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_KEY_BOARD , 0x10}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_POINTING_DEVICE , 0x20}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_COMBO_KEYBOARD_POINTING_DEVICE , 0x30}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_JOYSTICK , 0x01}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_GAME_PAD , 0x02}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_REMOTE_CONTROL , 0x03}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_SENSING_DEVICE , 0x04}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITIZER_TABLET , 0x05}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_CARD_READER , 0x06}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITAL_PEN , 0x07}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_SCANNER , 0x08}, - {BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_GESTURAL_INPUT_DEVICE , 0x09}, - {BT_MINOR_DEVICE_CLASS_IMAGING_DISPLAY , 0x04}, - {BT_MINOR_DEVICE_CLASS_IMAGING_CAMERA , 0x08}, - {BT_MINOR_DEVICE_CLASS_IMAGING_SCANNER , 0x10}, + {BT_MINOR_DEVICE_CLASS_COMPUTER_WEARABLE_COMPUTER, 0x06}, + {BT_MINOR_DEVICE_CLASS_PHONE_UNCATEGORIZED, 0x00}, + {BT_MINOR_DEVICE_CLASS_PHONE_CELLULAR, 0x01}, + {BT_MINOR_DEVICE_CLASS_PHONE_CORDLESS, 0x02}, + {BT_MINOR_DEVICE_CLASS_PHONE_SMART_PHONE, 0x03}, + {BT_MINOR_DEVICE_CLASS_PHONE_WIRED_MODEM_OR_VOICE_GATEWAY, 0x04}, + {BT_MINOR_DEVICE_CLASS_PHONE_COMMON_ISDN_ACCESS, 0x05}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_UNCATEGORIZED, 0x00}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_WEARABLE_HEADSET, 0x01}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HANDS_FREE, 0x02}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_MICROPHONE, 0x04}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_LOUDSPEAKER, 0x05}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HEADPHONES, 0x06}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_PORTABLE_AUDIO, 0x07}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAR_AUDIO, 0x08}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_SET_TOP_BOX, 0x09}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HIFI_AUDIO_DEVICE, 0x0a}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VCR, 0x0b}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CAMERA, 0x0c}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAMCORDER, 0x0d}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_MONITOR, 0x0e}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_DISPLAY_LOUDSPEAKER, 0x0f}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CONFERENCING, 0x10}, + {BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_GAMING_TOY, 0x12}, + {BT_MINOR_DEVICE_CLASS_PERIPHERA_UNCATEGORIZED, 0}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_KEY_BOARD, 0x10}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_POINTING_DEVICE, 0x20}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_COMBO_KEYBOARD_POINTING_DEVICE, 0x30}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_JOYSTICK, 0x01}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_GAME_PAD, 0x02}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_REMOTE_CONTROL, 0x03}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_SENSING_DEVICE, 0x04}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITIZER_TABLET, 0x05}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_CARD_READER, 0x06}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITAL_PEN, 0x07}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_SCANNER, 0x08}, + {BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_GESTURAL_INPUT_DEVICE, 0x09}, + {BT_MINOR_DEVICE_CLASS_IMAGING_DISPLAY, 0x04}, + {BT_MINOR_DEVICE_CLASS_IMAGING_CAMERA, 0x08}, + {BT_MINOR_DEVICE_CLASS_IMAGING_SCANNER, 0x10}, {BT_MINOR_DEVICE_CLASS_IMAGING_PRINTER, 0x20}, - {BT_MINOR_DEVICE_CLASS_WEARABLE_WRIST_WATCH , 0x01}, - {BT_MINOR_DEVICE_CLASS_WEARABLE_PAGER , 0x02}, - {BT_MINOR_DEVICE_CLASS_WEARABLE_JACKET , 0x03}, - {BT_MINOR_DEVICE_CLASS_WEARABLE_HELMET , 0x04}, - {BT_MINOR_DEVICE_CLASS_WEARABLE_GLASSES , 0x05}, - {BT_MINOR_DEVICE_CLASS_TOY_ROBOT , 0x01}, - {BT_MINOR_DEVICE_CLASS_TOY_VEHICLE , 0x02}, - {BT_MINOR_DEVICE_CLASS_TOY_DOLL_ACTION , 0x03}, - {BT_MINOR_DEVICE_CLASS_TOY_CONTROLLER , 0x04}, - {BT_MINOR_DEVICE_CLASS_TOY_GAME , 0x05}, - {BT_MINOR_DEVICE_CLASS_HEALTH_UNCATEGORIZED , 0x00}, - {BT_MINOR_DEVICE_CLASS_HEALTH_BLOOD_PRESSURE_MONITOR , 0x01}, - {BT_MINOR_DEVICE_CLASS_HEALTH_THERMOMETER , 0x02}, - {BT_MINOR_DEVICE_CLASS_HEALTH_WEIGHING_SCALE , 0x03}, - {BT_MINOR_DEVICE_CLASS_HEALTH_GLUCOSE_METER , 0x04}, - {BT_MINOR_DEVICE_CLASS_HEALTH_PULSE_OXIMETER , 0x05}, - {BT_MINOR_DEVICE_CLASS_HEALTH_HEART_PULSE_RATE_MONITOR , 0x06}, - {BT_MINOR_DEVICE_CLASS_HEALTH_DATA_DISPLAY , 0x07}, - {BT_MINOR_DEVICE_CLASS_HEALTH_STEP_COUNTER , 0x08}, - {BT_MINOR_DEVICE_CLASS_HEALTH_BODY_COMPOSITION_ANALYZER , 0x09}, - {BT_MINOR_DEVICE_CLASS_HEALTH_PEAK_FLOW_MONITOR , 0x0a}, - {BT_MINOR_DEVICE_CLASS_HEALTH_MEDICATION_MONITOR , 0x0b}, - {BT_MINOR_DEVICE_CLASS_HEALTH_KNEE_PROSTHESIS , 0x0c}, - {BT_MINOR_DEVICE_CLASS_HEALTH_ANKLE_PROSTHESIS , 0x0d} -}; + {BT_MINOR_DEVICE_CLASS_WEARABLE_WRIST_WATCH, 0x01}, + {BT_MINOR_DEVICE_CLASS_WEARABLE_PAGER, 0x02}, + {BT_MINOR_DEVICE_CLASS_WEARABLE_JACKET, 0x03}, + {BT_MINOR_DEVICE_CLASS_WEARABLE_HELMET, 0x04}, + {BT_MINOR_DEVICE_CLASS_WEARABLE_GLASSES, 0x05}, + {BT_MINOR_DEVICE_CLASS_TOY_ROBOT, 0x01}, + {BT_MINOR_DEVICE_CLASS_TOY_VEHICLE, 0x02}, + {BT_MINOR_DEVICE_CLASS_TOY_DOLL_ACTION, 0x03}, + {BT_MINOR_DEVICE_CLASS_TOY_CONTROLLER, 0x04}, + {BT_MINOR_DEVICE_CLASS_TOY_GAME, 0x05}, + {BT_MINOR_DEVICE_CLASS_HEALTH_UNCATEGORIZED, 0x00}, + {BT_MINOR_DEVICE_CLASS_HEALTH_BLOOD_PRESSURE_MONITOR, 0x01}, + {BT_MINOR_DEVICE_CLASS_HEALTH_THERMOMETER, 0x02}, + {BT_MINOR_DEVICE_CLASS_HEALTH_WEIGHING_SCALE, 0x03}, + {BT_MINOR_DEVICE_CLASS_HEALTH_GLUCOSE_METER, 0x04}, + {BT_MINOR_DEVICE_CLASS_HEALTH_PULSE_OXIMETER, 0x05}, + {BT_MINOR_DEVICE_CLASS_HEALTH_HEART_PULSE_RATE_MONITOR, 0x06}, + {BT_MINOR_DEVICE_CLASS_HEALTH_DATA_DISPLAY, 0x07}, + {BT_MINOR_DEVICE_CLASS_HEALTH_STEP_COUNTER, 0x08}, + {BT_MINOR_DEVICE_CLASS_HEALTH_BODY_COMPOSITION_ANALYZER, 0x09}, + {BT_MINOR_DEVICE_CLASS_HEALTH_PEAK_FLOW_MONITOR, 0x0a}, + {BT_MINOR_DEVICE_CLASS_HEALTH_MEDICATION_MONITOR, 0x0b}, + {BT_MINOR_DEVICE_CLASS_HEALTH_KNEE_PROSTHESIS, 0x0c}, + {BT_MINOR_DEVICE_CLASS_HEALTH_ANKLE_PROSTHESIS, 0x0d}}; std::map g_service_enum_map = { {BT_MAJOR_SERVICE_CLASS_LIMITED_DISCOVERABLE_MODE, 0x0001}, @@ -119,11 +117,9 @@ std::map g_service_enum_map = { {BT_MAJOR_SERVICE_CLASS_OBJECT_TRANSFER, 0x0080}, {BT_MAJOR_SERVICE_CLASS_AUDIO, 0x0100}, {BT_MAJOR_SERVICE_CLASS_TELEPHONY, 0x0200}, - {BT_MAJOR_SERVICE_CLASS_INFORMATION, 0x0400} -}; + {BT_MAJOR_SERVICE_CLASS_INFORMATION, 0x0400}}; -unsigned long BluetoothClass::GetMajorValue(bt_major_device_class_e major) -{ +unsigned long BluetoothClass::GetMajorValue(bt_major_device_class_e major) { LoggerD("Enter"); auto iter = g_major_enum_map.find(major); if (iter != g_major_enum_map.end()) { @@ -133,8 +129,7 @@ unsigned long BluetoothClass::GetMajorValue(bt_major_device_class_e major) return 0; } -unsigned long BluetoothClass::GetMinorValue(bt_minor_device_class_e minor) -{ +unsigned long BluetoothClass::GetMinorValue(bt_minor_device_class_e minor) { LoggerD("Enter"); auto iter = g_minor_enum_map.find(minor); if (iter != g_minor_enum_map.end()) { @@ -144,8 +139,7 @@ unsigned long BluetoothClass::GetMinorValue(bt_minor_device_class_e minor) return 0; } -std::vector BluetoothClass::getServiceValues(int serviceMask) -{ +std::vector BluetoothClass::getServiceValues(int serviceMask) { LoggerD("Enter"); std::vector ret; for (auto iter = g_service_enum_map.begin(); iter != g_service_enum_map.end(); iter++) { @@ -157,5 +151,5 @@ std::vector BluetoothClass::getServiceValues(int serviceMask) return ret; } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_class.h b/src/bluetooth/bluetooth_class.h old mode 100755 new mode 100644 index 7476369..2a931cb --- a/src/bluetooth/bluetooth_class.h +++ b/src/bluetooth/bluetooth_class.h @@ -31,7 +31,7 @@ class BluetoothClass { static std::vector getServiceValues(int serviceMask); }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_CLASS_H_ +#endif // BLUETOOTH_BLUETOOTH_CLASS_H_ diff --git a/src/bluetooth/bluetooth_device.cc b/src/bluetooth/bluetooth_device.cc old mode 100755 new mode 100644 index 51834e2..0f82b45 --- a/src/bluetooth/bluetooth_device.cc +++ b/src/bluetooth/bluetooth_device.cc @@ -33,7 +33,7 @@ using namespace common; using namespace common::tools; namespace { -//device +// device const std::string kDeviceName = "name"; const std::string kDeviceAddress = "address"; const std::string kDeviceClass = "deviceClass"; @@ -49,50 +49,55 @@ const std::string kDeviceIsConnected = "isConnected"; static void ToJsonFromBTClass(bt_class_s bluetooth_class, picojson::object* device) { LoggerD("Entered"); - picojson::object& bt = device->insert(std::make_pair(kDeviceClass, picojson::value(picojson::object()))) - .first->second.get(); + picojson::object& bt = + device->insert(std::make_pair(kDeviceClass, picojson::value(picojson::object()))) + .first->second.get(); - bt.insert(std::make_pair(kDeviceClassMajor, picojson::value(static_cast( - BluetoothClass::GetMajorValue(bluetooth_class.major_device_class))))); - bt.insert(std::make_pair(kDeviceClassMinor, picojson::value(static_cast( - BluetoothClass::GetMinorValue(bluetooth_class.minor_device_class))))); + bt.insert(std::make_pair( + kDeviceClassMajor, picojson::value(static_cast( + BluetoothClass::GetMajorValue(bluetooth_class.major_device_class))))); + bt.insert(std::make_pair( + kDeviceClassMinor, picojson::value(static_cast( + BluetoothClass::GetMinorValue(bluetooth_class.minor_device_class))))); - picojson::array& array = bt.insert(std::make_pair( - kDeviceClassService, picojson::value(picojson::array()))).first->second.get(); + picojson::array& array = + bt.insert(std::make_pair(kDeviceClassService, picojson::value(picojson::array()))) + .first->second.get(); - std::vector services_vector = BluetoothClass::getServiceValues( - bluetooth_class.major_service_class_mask); + std::vector services_vector = + BluetoothClass::getServiceValues(bluetooth_class.major_service_class_mask); for (auto v : services_vector) { array.push_back(picojson::value(static_cast(v))); } } -static void ToJsonFromUUID(char **service_uuid, int service_count, picojson::object* device) { +static void ToJsonFromUUID(char** service_uuid, int service_count, picojson::object* device) { LoggerD("Entered"); - picojson::array& array = device->insert(std::make_pair(kDeviceUuids, picojson::value(picojson::array()))) - .first->second.get(); + picojson::array& array = + device->insert(std::make_pair(kDeviceUuids, picojson::value(picojson::array()))) + .first->second.get(); for (int i = 0; i < service_count; i++) { array.push_back(picojson::value(service_uuid[i])); } } -BluetoothDevice::BluetoothDevice(BluetoothAdapter& adapter) - : adapter_(adapter) { +BluetoothDevice::BluetoothDevice(BluetoothAdapter& adapter) : adapter_(adapter) { } void BluetoothDevice::ToJson(bt_device_info_s* info, picojson::object* device) { LoggerD("Entered"); device->insert(std::make_pair(kDeviceName, picojson::value(std::string(info->remote_name)))); - device->insert(std::make_pair(kDeviceAddress, picojson::value(std::string(info->remote_address)))); + device->insert( + std::make_pair(kDeviceAddress, picojson::value(std::string(info->remote_address)))); ToJsonFromBTClass(info->bt_class, device); ToJsonFromUUID(info->service_uuid, info->service_count, device); } -void BluetoothDevice::ToJson(bt_adapter_device_discovery_info_s *info, picojson::object* device) { +void BluetoothDevice::ToJson(bt_adapter_device_discovery_info_s* info, picojson::object* device) { LoggerD("Entered"); device->insert(std::make_pair(kDeviceName, picojson::value(info->remote_name))); @@ -105,8 +110,8 @@ void BluetoothDevice::ToJson(bt_adapter_device_discovery_info_s *info, picojson: void BluetoothDevice::ConnectToServiceByUUID(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto& args = util::GetArguments(data); @@ -126,7 +131,7 @@ void BluetoothDevice::GetBoolValue(const picojson::value& data, picojson::object PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); bool value = false; - bt_device_info_s *info = nullptr; + bt_device_info_s* info = nullptr; int ntv_ret = bt_adapter_get_bonded_device_info(address.c_str(), &info); if (BT_ERROR_NONE == ntv_ret && info != nullptr) { if (kDeviceIsBonded == field) { @@ -136,15 +141,14 @@ void BluetoothDevice::GetBoolValue(const picojson::value& data, picojson::object } else if (kDeviceIsConnected == field) { value = info->is_connected; } else { - result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Wrong field passed.", - ("Wrong field passed: %s", field.c_str())); + result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Wrong field passed.", + ("Wrong field passed: %s", field.c_str())); } bt_adapter_free_device_info(info); } else { result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error", - ("bt_adapter_get_bonded_device_info error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Unknown error", + ("bt_adapter_get_bonded_device_info error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } if (result.IsSuccess()) { @@ -154,5 +158,5 @@ void BluetoothDevice::GetBoolValue(const picojson::value& data, picojson::object } } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_device.h b/src/bluetooth/bluetooth_device.h old mode 100755 new mode 100644 index 2df25a7..8c70e88 --- a/src/bluetooth/bluetooth_device.h +++ b/src/bluetooth/bluetooth_device.h @@ -32,7 +32,8 @@ class BluetoothDevice { /** * Signature: @code void connectToServiceByUUID(uuid, successCallback, errorCallback); @endcode - * JSON: @code data: {method: 'BluetoothDevice_connectToServiceByUUID', args: {uuid: uuid}} @endcode + * JSON: @code data: {method: 'BluetoothDevice_connectToServiceByUUID', args: {uuid: uuid}} + * @endcode * Invocation: @code native.call(request, result_callback); @endcode * Return: * @code @@ -60,16 +61,14 @@ class BluetoothDevice { */ void GetBoolValue(const picojson::value& data, picojson::object& out); - static void ToJson(bt_device_info_s* info, - picojson::object* device); - static void ToJson(bt_adapter_device_discovery_info_s *info, - picojson::object* device); + static void ToJson(bt_device_info_s* info, picojson::object* device); + static void ToJson(bt_adapter_device_discovery_info_s* info, picojson::object* device); private: BluetoothAdapter& adapter_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_DEVICE_H_ +#endif // BLUETOOTH_BLUETOOTH_DEVICE_H_ diff --git a/src/bluetooth/bluetooth_extension.cc b/src/bluetooth/bluetooth_extension.cc old mode 100755 new mode 100644 index d9efdd1..62418f0 --- a/src/bluetooth/bluetooth_extension.cc +++ b/src/bluetooth/bluetooth_extension.cc @@ -33,16 +33,13 @@ common::Extension* CreateExtension() { BluetoothExtension::BluetoothExtension() { SetExtensionName(kBluetooth); SetJavaScriptAPI(kSource_bluetooth_api); - const char* entry_points[] = { - kBluetoothLEAdvertiseData, - kBluetoothLEServiceData, - kBluetoothLEManufacturerData, - NULL - }; + const char* entry_points[] = {kBluetoothLEAdvertiseData, kBluetoothLEServiceData, + kBluetoothLEManufacturerData, NULL}; SetExtraJSEntryPoints(entry_points); } -BluetoothExtension::~BluetoothExtension() {} +BluetoothExtension::~BluetoothExtension() { +} common::Instance* BluetoothExtension::CreateInstance() { return new extension::bluetooth::BluetoothInstance(); diff --git a/src/bluetooth/bluetooth_extension.h b/src/bluetooth/bluetooth_extension.h old mode 100755 new mode 100644 index 32613b0..37ff5b6 --- a/src/bluetooth/bluetooth_extension.h +++ b/src/bluetooth/bluetooth_extension.h @@ -28,5 +28,4 @@ class BluetoothExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // BLUETOOTH_BLUETOOTH_EXTENSION_H_ - +#endif // BLUETOOTH_BLUETOOTH_EXTENSION_H_ diff --git a/src/bluetooth/bluetooth_gatt_service.cc b/src/bluetooth/bluetooth_gatt_service.cc old mode 100755 new mode 100644 index f16fb92..eaa7894 --- a/src/bluetooth/bluetooth_gatt_service.cc +++ b/src/bluetooth/bluetooth_gatt_service.cc @@ -25,8 +25,8 @@ #include "common/tools.h" #include "bluetooth/bluetooth_instance.h" -#include "bluetooth/bluetooth_util.h" #include "bluetooth/bluetooth_privilege.h" +#include "bluetooth/bluetooth_util.h" namespace extension { namespace bluetooth { @@ -53,14 +53,12 @@ const std::string kWriteNoResponse = "isWriteNoResponse"; const std::string kOnValueChanged = "BluetoothGATTCharacteristicValueChangeListener"; -bool IsProperty (int propertyBits, bt_gatt_property_e property) { +bool IsProperty(int propertyBits, bt_gatt_property_e property) { return (propertyBits & property) != 0; } } -BluetoothGATTService::BluetoothGATTService(BluetoothInstance& instance) : - instance_(instance) -{ +BluetoothGATTService::BluetoothGATTService(BluetoothInstance& instance) : instance_(instance) { LoggerD("Entered"); } @@ -106,28 +104,26 @@ bt_gatt_client_h BluetoothGATTService::GetGattClient(const std::string& address) } // this method should be used to inform this object that some device was disconnected -void BluetoothGATTService::TryDestroyClient(const std::string &address) { +void BluetoothGATTService::TryDestroyClient(const std::string& address) { auto it = gatt_clients_.find(address); if (gatt_clients_.end() != it) { LoggerD("destroying client for address: %s", it->first.c_str()); bt_gatt_client_destroy(it->second); gatt_clients_.erase(it); } else { - LoggerD("Client for address: %s does not exist, no need for deletion", - address.c_str()); + LoggerD("Client for address: %s does not exist, no need for deletion", address.c_str()); } } -PlatformResult BluetoothGATTService::GetSpecifiedGATTService(const std::string &address, - const std::string &uuid, +PlatformResult BluetoothGATTService::GetSpecifiedGATTService(const std::string& address, + const std::string& uuid, picojson::object* result) { LoggerD("Entered"); bt_gatt_client_h client = GetGattClient(address); if (nullptr == client) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create the GATT client's handle"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create the GATT client's handle"); } bt_gatt_h service = nullptr; @@ -137,32 +133,31 @@ PlatformResult BluetoothGATTService::GetSpecifiedGATTService(const std::string & switch (ret) { case BT_ERROR_NO_DATA: return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Service not found", - ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::NOT_FOUND_ERR, "Service not found", + ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); case BT_ERROR_INVALID_PARAMETER: return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Service UUID is invalid", - ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::NOT_FOUND_ERR, "Service UUID is invalid", + ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); default: return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get a service's GATT handle", - ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Failed to get a service's GATT handle", + ("bt_gatt_client_get_service error: %d (%s)", ret, get_error_message(ret))); } } - //report BluetoothGattService + // report BluetoothGattService result->insert(std::make_pair(kUuid, picojson::value(uuid))); - //handle is passed to upper layer because there is no need to delete it + // handle is passed to upper layer because there is no need to delete it result->insert(std::make_pair(kHandle, picojson::value((double)(long)service))); - //address is necessary to later check if device is still connected + // address is necessary to later check if device is still connected result->insert(std::make_pair(kAddress, picojson::value(address))); return PlatformResult(ErrorCode::NO_ERROR); } -void BluetoothGATTService::GetServices(const picojson::value& args, - picojson::object& out) { +void BluetoothGATTService::GetServices(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); @@ -177,20 +172,18 @@ void BluetoothGATTService::GetServices(const picojson::value& args, } } -PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, - const std::string& address, +PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, const std::string& address, picojson::array* array) { LoggerD("Entered"); if (!IsStillConnected(address)) { - return LogAndCreateResult( - ErrorCode::INVALID_STATE_ERR, "Device is not connected", - ("Device with address %s is no longer connected", address.c_str())); + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected", + ("Device with address %s is no longer connected", address.c_str())); } int ret = bt_gatt_service_foreach_included_services( handle, - [](int total, int index, bt_gatt_h gatt_handle, void *data) { + [](int total, int index, bt_gatt_h gatt_handle, void* data) { LoggerD("Enter"); picojson::value result = picojson::value(picojson::object()); @@ -205,11 +198,12 @@ PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, result_obj.insert(std::make_pair(kUuid, picojson::value("FFFF"))); } - //handle is passed to upper layer because there is no need of deletion + // handle is passed to upper layer because there is no need of deletion result_obj.insert(std::make_pair(kHandle, picojson::value((double)(long)gatt_handle))); static_cast(data)->push_back(result); return true; - }, array); + }, + array); if (BT_ERROR_NONE != ret) { LoggerE("Failed bt_gatt_service_foreach_included_services() (%d)", ret); return util::GetBluetoothError(ret, "Failed to set a service's GATT callback"); @@ -218,8 +212,7 @@ PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -void BluetoothGATTService::GetCharacteristics(const picojson::value& args, - picojson::object& out) { +void BluetoothGATTService::GetCharacteristics(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); @@ -242,9 +235,8 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, LoggerD("Entered"); if (!IsStillConnected(address)) { - return LogAndCreateResult( - ErrorCode::INVALID_STATE_ERR, "Device is not connected", - ("Device with address %s is no longer connected", address.c_str())); + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected", + ("Device with address %s is no longer connected", address.c_str())); } struct Data { @@ -257,7 +249,7 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, int ret = bt_gatt_service_foreach_characteristics( handle, - [](int total, int index, bt_gatt_h gatt_handle, void *data) { + [](int total, int index, bt_gatt_h gatt_handle, void* data) { LoggerD("Enter"); Data* user_data = static_cast(data); picojson::array* array = user_data->array; @@ -266,60 +258,64 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - //handle is passed to upper layer because there is no need of deletion + // handle is passed to upper layer because there is no need of deletion result_obj.insert(std::make_pair(kHandle, picojson::value((double)(long)gatt_handle))); - //descriptors - picojson::array& desc_array = result_obj.insert( - std::make_pair("descriptors", picojson::value(picojson::array()))). - first->second.get(); + // descriptors + picojson::array& desc_array = + result_obj.insert(std::make_pair("descriptors", picojson::value(picojson::array()))) + .first->second.get(); int ret = bt_gatt_characteristic_foreach_descriptors( gatt_handle, - [](int total, int index, bt_gatt_h desc_handle, void *data) { + [](int total, int index, bt_gatt_h desc_handle, void* data) { LoggerD("Enter"); picojson::array& desc_array = *(static_cast(data)); picojson::value desc = picojson::value(picojson::object()); picojson::object& desc_obj = desc.get(); - //handle is passed to upper layer because there is no need of deletion - desc_obj.insert(std::make_pair(kHandle, picojson::value( - (double)(long)desc_handle))); + // handle is passed to upper layer because there is no need of deletion + desc_obj.insert(std::make_pair(kHandle, picojson::value((double)(long)desc_handle))); desc_array.push_back(desc); return true; - }, static_cast(&desc_array)); + }, + static_cast(&desc_array)); if (BT_ERROR_NONE != ret) { *platform_result = util::GetBluetoothError(ret, "Failed to get descriptors"); LoggerE("Failed bt_gatt_characteristic_foreach_descriptors() (%d)", ret); return false; } - //other properties + // other properties int property_bits = 0; int err = bt_gatt_characteristic_get_properties(gatt_handle, &property_bits); - if(BT_ERROR_NONE != err) { + if (BT_ERROR_NONE != err) { LoggerE("Properties of characteristic couldn't be acquired"); } - result_obj.insert(std::make_pair(kBroadcast, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_BROADCAST)))); - result_obj.insert(std::make_pair(kReadable, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_READ)))); - result_obj.insert(std::make_pair(kWriteNoResponse, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_WRITE_WITHOUT_RESPONSE)))); - result_obj.insert(std::make_pair(kWritable, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_WRITE)))); - result_obj.insert(std::make_pair(kNotify, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_NOTIFY)))); - result_obj.insert(std::make_pair(kIndication, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_INDICATE)))); - result_obj.insert(std::make_pair(kSignedWrite, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_AUTHENTICATED_SIGNED_WRITES)))); - result_obj.insert(std::make_pair(kExtendedProperties, picojson::value( - IsProperty(property_bits, BT_GATT_PROPERTY_EXTENDED_PROPERTIES)))); + result_obj.insert(std::make_pair( + kBroadcast, picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_BROADCAST)))); + result_obj.insert(std::make_pair( + kReadable, picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_READ)))); + result_obj.insert(std::make_pair( + kWriteNoResponse, + picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_WRITE_WITHOUT_RESPONSE)))); + result_obj.insert(std::make_pair( + kWritable, picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_WRITE)))); + result_obj.insert(std::make_pair( + kNotify, picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_NOTIFY)))); + result_obj.insert(std::make_pair( + kIndication, picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_INDICATE)))); + result_obj.insert(std::make_pair( + kSignedWrite, picojson::value(IsProperty( + property_bits, BT_GATT_PROPERTY_AUTHENTICATED_SIGNED_WRITES)))); + result_obj.insert(std::make_pair( + kExtendedProperties, + picojson::value(IsProperty(property_bits, BT_GATT_PROPERTY_EXTENDED_PROPERTIES)))); array->push_back(result); return true; - }, static_cast(&user_data)); + }, + static_cast(&user_data)); if (platform_result.IsError()) { return platform_result; } @@ -331,17 +327,15 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -void BluetoothGATTService::ReadValue(const picojson::value& args, - picojson::object& out) { +void BluetoothGATTService::ReadValue(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const std::string& address = args.get("address").get(); if (!IsStillConnected(address)) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, - ("Device with address %s is no longer connected", address.c_str())); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, + ("Device with address %s is no longer connected", address.c_str())); return; } @@ -354,7 +348,7 @@ void BluetoothGATTService::ReadValue(const picojson::value& args, Data* user_data = new Data{callback_handle, this}; bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); - auto read_value = [](int result, bt_gatt_h handle, void *user_data) -> void { + auto read_value = [](int result, bt_gatt_h handle, void* user_data) -> void { Data* data = static_cast(user_data); double callback_handle = data->callback_handle; BluetoothGATTService* service = data->service; @@ -368,13 +362,13 @@ void BluetoothGATTService::ReadValue(const picojson::value& args, if (BT_ERROR_NONE != result) { plarform_res = util::GetBluetoothError(result, "Error while reading value"); } else { - char *value = nullptr; + char* value = nullptr; int length = 0; int ret = bt_gatt_get_value(handle, &value, &length); if (BT_ERROR_NONE != ret) { plarform_res = util::GetBluetoothError(ret, "Error while getting value"); } else { - for (int i = 0 ; i < length; i++) { + for (int i = 0; i < length; i++) { byte_array_obj.push_back(picojson::value(std::to_string(value[i]))); } } @@ -393,31 +387,28 @@ void BluetoothGATTService::ReadValue(const picojson::value& args, } TaskQueue::GetInstance().Async( [service, callback_handle](const std::shared_ptr& response) { - service->instance_.SyncResponse(callback_handle, response); - }, response); + service->instance_.SyncResponse(callback_handle, response); + }, + response); }; int ret = bt_gatt_client_read_value(handle, read_value, (void*)user_data); if (BT_ERROR_NONE != ret) { delete user_data; user_data = nullptr; - LoggerE("Couldn't register callback for read value %d (%s)", - ret, get_error_message(ret)); + LoggerE("Couldn't register callback for read value %d (%s)", ret, get_error_message(ret)); } ReportSuccess(out); } - -void BluetoothGATTService::WriteValue(const picojson::value& args, - picojson::object& out) { +void BluetoothGATTService::WriteValue(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const std::string& address = args.get("address").get(); if (!IsStillConnected(address)) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, - ("Device with address %s is no longer connected", address.c_str())); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, + ("Device with address %s is no longer connected", address.c_str())); return; } @@ -437,7 +428,7 @@ void BluetoothGATTService::WriteValue(const picojson::value& args, bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); - auto write_value = [](int result, bt_gatt_h handle, void *user_data) -> void { + auto write_value = [](int result, bt_gatt_h handle, void* user_data) -> void { Data* data = static_cast(user_data); double callback_handle = data->callback_handle; BluetoothGATTService* service = data->service; @@ -457,8 +448,9 @@ void BluetoothGATTService::WriteValue(const picojson::value& args, } TaskQueue::GetInstance().Async( [service, callback_handle](const std::shared_ptr& response) { - service->instance_.SyncResponse(callback_handle, response); - }, response); + service->instance_.SyncResponse(callback_handle, response); + }, + response); }; int ret = bt_gatt_set_value(handle, value_data.get(), value_size); @@ -466,21 +458,20 @@ void BluetoothGATTService::WriteValue(const picojson::value& args, if (BT_ERROR_NONE != ret) { std::shared_ptr response = std::shared_ptr(new picojson::value(picojson::object())); - LogAndReportError( - util::GetBluetoothError(ret, "Failed to set value"), - &response->get(), - ("bt_gatt_set_value error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to set value"), + &response->get(), + ("bt_gatt_set_value error: %d (%s)", ret, get_error_message(ret))); TaskQueue::GetInstance().Async( [this, callback_handle](const std::shared_ptr& response) { - instance_.SyncResponse(callback_handle, response); - }, response); + instance_.SyncResponse(callback_handle, response); + }, + response); } else { Data* user_data = new Data{callback_handle, this}; ret = bt_gatt_client_write_value(handle, write_value, user_data); if (BT_ERROR_NONE != ret) { delete user_data; - LoggerE("Couldn't register callback for write value %d (%s)", - ret, get_error_message(ret)); + LoggerE("Couldn't register callback for write value %d (%s)", ret, get_error_message(ret)); } } ReportSuccess(out); @@ -491,54 +482,54 @@ void BluetoothGATTService::AddValueChangeListener(const picojson::value& args, LoggerD("Entered"); const auto& address = args.get("address").get(); if (!IsStillConnected(address)) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, - ("Device with address %s is no longer connected", address.c_str())); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, + ("Device with address %s is no longer connected", address.c_str())); return; } - bt_gatt_h handle = (bt_gatt_h)static_cast(args.get(kHandle).get()); + bt_gatt_h handle = (bt_gatt_h) static_cast(args.get(kHandle).get()); - int ret = bt_gatt_client_set_characteristic_value_changed_cb(handle, OnCharacteristicValueChanged, this); + int ret = bt_gatt_client_set_characteristic_value_changed_cb(handle, OnCharacteristicValueChanged, + this); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to register listener"), &out, - ("bt_gatt_client_set_characteristic_value_changed_cb() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to register listener"), &out, + ("bt_gatt_client_set_characteristic_value_changed_cb() failed with: %d (%s)", + ret, get_error_message(ret))); } else { gatt_characteristic_.push_back(handle); ReportSuccess(out); } } -void BluetoothGATTService::RemoveValueChangeListener( - const picojson::value& args, picojson::object& out) { +void BluetoothGATTService::RemoveValueChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const auto& address = args.get("address").get(); if (!IsStillConnected(address)) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, - ("Device with address %s is no longer connected", address.c_str())); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, + ("Device with address %s is no longer connected", address.c_str())); return; } - bt_gatt_h handle = (bt_gatt_h)static_cast(args.get(kHandle).get()); + bt_gatt_h handle = (bt_gatt_h) static_cast(args.get(kHandle).get()); int ret = bt_gatt_client_unset_characteristic_value_changed_cb(handle); if (BT_ERROR_NONE != ret) { LogAndReportError( util::GetBluetoothError(ret, "Failed to unregister listener"), &out, - ("bt_gatt_client_unset_characteristic_value_changed_cb() failed with: %d (%s)", - ret, get_error_message(ret))); + ("bt_gatt_client_unset_characteristic_value_changed_cb() failed with: %d (%s)", ret, + get_error_message(ret))); } else { - gatt_characteristic_.erase(std::remove(gatt_characteristic_.begin(), gatt_characteristic_.end(), handle), gatt_characteristic_.end()); + gatt_characteristic_.erase( + std::remove(gatt_characteristic_.begin(), gatt_characteristic_.end(), handle), + gatt_characteristic_.end()); ReportSuccess(out); } } -common::PlatformResult BluetoothGATTService::GetServiceAllUuids( - const std::string& address, picojson::array* array) { +common::PlatformResult BluetoothGATTService::GetServiceAllUuids(const std::string& address, + picojson::array* array) { LoggerD("Entered"); bt_gatt_client_h client = GetGattClient(address); @@ -576,9 +567,10 @@ common::PlatformResult BluetoothGATTService::GetServiceAllUuids( } } -void BluetoothGATTService::OnCharacteristicValueChanged( - bt_gatt_h characteristic, char* value, int length, void* user_data) { - LoggerD("Entered, characteristic: [%p], len: [%d], user_data: [%p]", characteristic, length, user_data); +void BluetoothGATTService::OnCharacteristicValueChanged(bt_gatt_h characteristic, char* value, + int length, void* user_data) { + LoggerD("Entered, characteristic: [%p], len: [%d], user_data: [%p]", characteristic, length, + user_data); auto service = static_cast(user_data); @@ -595,7 +587,7 @@ void BluetoothGATTService::OnCharacteristicValueChanged( picojson::value byte_array = picojson::value(picojson::array()); picojson::array& byte_array_obj = byte_array.get(); - for (int i = 0 ; i < length; ++i) { + for (int i = 0; i < length; ++i) { byte_array_obj.push_back(picojson::value(std::to_string(value[i]))); } @@ -604,5 +596,5 @@ void BluetoothGATTService::OnCharacteristicValueChanged( service->instance_.FireEvent(kOnValueChanged, result); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_gatt_service.h b/src/bluetooth/bluetooth_gatt_service.h old mode 100755 new mode 100644 index e6936a6..db2ab48 --- a/src/bluetooth/bluetooth_gatt_service.h +++ b/src/bluetooth/bluetooth_gatt_service.h @@ -34,22 +34,18 @@ class BluetoothGATTService { BluetoothGATTService(BluetoothInstance& instance); ~BluetoothGATTService(); - common::PlatformResult GetSpecifiedGATTService(const std::string &address, - const std::string &uuid, - picojson::object* result); + common::PlatformResult GetSpecifiedGATTService(const std::string& address, + const std::string& uuid, picojson::object* result); - void TryDestroyClient(const std::string &address); + void TryDestroyClient(const std::string& address); void GetServices(const picojson::value& data, picojson::object& out); void GetCharacteristics(const picojson::value& data, picojson::object& out); void ReadValue(const picojson::value& args, picojson::object& out); void WriteValue(const picojson::value& args, picojson::object& out); - void AddValueChangeListener(const picojson::value& args, - picojson::object& out); - void RemoveValueChangeListener(const picojson::value& args, - picojson::object& out); + void AddValueChangeListener(const picojson::value& args, picojson::object& out); + void RemoveValueChangeListener(const picojson::value& args, picojson::object& out); - common::PlatformResult GetServiceAllUuids(const std::string& address, - picojson::array* array); + common::PlatformResult GetServiceAllUuids(const std::string& address, picojson::array* array); private: bool IsStillConnected(const std::string& address); @@ -57,14 +53,11 @@ class BluetoothGATTService { bt_gatt_client_h GetGattClient(const std::string& address); common::PlatformResult GetServicesHelper(bt_gatt_h handle, const std::string& address, - picojson::array* array); - common::PlatformResult GetCharacteristicsHelper(bt_gatt_h handle, - const std::string& address, - const std::string& uuid, - picojson::array* array); - - static void OnCharacteristicValueChanged(bt_gatt_h characteristic, - char* value, int len, + picojson::array* array); + common::PlatformResult GetCharacteristicsHelper(bt_gatt_h handle, const std::string& address, + const std::string& uuid, picojson::array* array); + + static void OnCharacteristicValueChanged(bt_gatt_h characteristic, char* value, int len, void* user_data); std::map gatt_clients_; @@ -73,7 +66,7 @@ class BluetoothGATTService { BluetoothInstance& instance_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_GATT_SERVICE_H_ +#endif // BLUETOOTH_BLUETOOTH_GATT_SERVICE_H_ diff --git a/src/bluetooth/bluetooth_health_application.cc b/src/bluetooth/bluetooth_health_application.cc old mode 100755 new mode 100644 index dec2a6d..7d347f7 --- a/src/bluetooth/bluetooth_health_application.cc +++ b/src/bluetooth/bluetooth_health_application.cc @@ -32,20 +32,19 @@ namespace { const std::string kDataType = "dataType"; const std::string kName = "name"; const std::string kId = "_id"; -} // namespace +} // namespace using namespace common; -BluetoothHealthApplication::BluetoothHealthApplication( - BluetoothHealthProfileHandler& handler) +BluetoothHealthApplication::BluetoothHealthApplication(BluetoothHealthProfileHandler& handler) : handler_(handler) { } void BluetoothHealthApplication::Unregister(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothHealth, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, + &out); const auto& args = util::GetArguments(data); @@ -55,14 +54,12 @@ void BluetoothHealthApplication::Unregister(const picojson::value& data, picojso tools::ReportSuccess(out); } -void BluetoothHealthApplication::ToJson(short data_type, - const std::string& name, - const char* id, +void BluetoothHealthApplication::ToJson(short data_type, const std::string& name, const char* id, picojson::object* out) { out->insert(std::make_pair(kDataType, picojson::value(static_cast(data_type)))); out->insert(std::make_pair(kName, picojson::value(name))); out->insert(std::make_pair(kId, picojson::value(id))); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_health_application.h b/src/bluetooth/bluetooth_health_application.h old mode 100755 new mode 100644 index e1f773b..a0027f8 --- a/src/bluetooth/bluetooth_health_application.h +++ b/src/bluetooth/bluetooth_health_application.h @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef BLUETOOTH_BLUETOOTH_HEALTH_APPLICATION_H_ #define BLUETOOTH_BLUETOOTH_HEALTH_APPLICATION_H_ - #include "common/picojson.h" namespace extension { @@ -46,16 +45,14 @@ class BluetoothHealthApplication { */ void Unregister(const picojson::value& data, picojson::object& out); - static void ToJson(short data_type, - const std::string& name, - const char* id, + static void ToJson(short data_type, const std::string& name, const char* id, picojson::object* out); private: BluetoothHealthProfileHandler& handler_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_HEALTH_APPLICATION_H_ +#endif // BLUETOOTH_BLUETOOTH_HEALTH_APPLICATION_H_ diff --git a/src/bluetooth/bluetooth_health_channel.cc b/src/bluetooth/bluetooth_health_channel.cc old mode 100755 new mode 100644 index 6ee2726..da7f6f6 --- a/src/bluetooth/bluetooth_health_channel.cc +++ b/src/bluetooth/bluetooth_health_channel.cc @@ -39,13 +39,13 @@ const std::string kChannelType = "channelType"; const std::string kApplication = "appId"; const std::string kIsConnected = "isConnected"; const std::string kId = "_id"; -} // namespace +} // namespace -void BluetoothHealthChannel::Close(const picojson::value& data , picojson::object& out) { +void BluetoothHealthChannel::Close(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothHealth, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, + &out); const auto& args = util::GetArguments(data); @@ -54,9 +54,8 @@ void BluetoothHealthChannel::Close(const picojson::value& data , picojson::objec int ntv_ret = bt_hdp_disconnect(address.c_str(), channel); if (BT_ERROR_NONE != ntv_ret) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, - ("bt_hdp_disconnect error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, + ("bt_hdp_disconnect error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); return; } @@ -66,8 +65,8 @@ void BluetoothHealthChannel::Close(const picojson::value& data , picojson::objec void BluetoothHealthChannel::SendData(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothHealth, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, + &out); const auto& args = util::GetArguments(data); @@ -83,17 +82,15 @@ void BluetoothHealthChannel::SendData(const picojson::value& data, picojson::obj int ntv_ret = bt_hdp_send_data(channel, data_ptr.get(), data_size); if (BT_ERROR_NONE != ntv_ret) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, - ("bt_hdp_send_data() failed: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, + ("bt_hdp_send_data() failed: %d (%s)", ntv_ret, get_error_message(ntv_ret))); return; } ReportSuccess(picojson::value(static_cast(data_size)), out); } -void BluetoothHealthChannel::ToJson(unsigned int channel, - bt_hdp_channel_type_e type, +void BluetoothHealthChannel::ToJson(unsigned int channel, bt_hdp_channel_type_e type, picojson::object* out) { LoggerD("Enter"); const char* type_str = "UNKNOWN"; @@ -117,19 +114,17 @@ void BluetoothHealthChannel::ToJson(unsigned int channel, out->insert(std::make_pair(kIsConnected, picojson::value(true))); } -void BluetoothHealthChannel::ToJson(unsigned int channel, - bt_hdp_channel_type_e type, - bt_device_info_s* device_info, - const char* app_id, +void BluetoothHealthChannel::ToJson(unsigned int channel, bt_hdp_channel_type_e type, + bt_device_info_s* device_info, const char* app_id, picojson::object* out) { LoggerD("Enter"); ToJson(channel, type, out); - auto& device = out->insert( - std::make_pair(kPeer, picojson::value(picojson::object()))) .first->second.get(); + auto& device = out->insert(std::make_pair(kPeer, picojson::value(picojson::object()))) + .first->second.get(); BluetoothDevice::ToJson(device_info, &device); out->insert(std::make_pair(kApplication, picojson::value(app_id))); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_health_channel.h b/src/bluetooth/bluetooth_health_channel.h old mode 100755 new mode 100644 index 922d370..80c13c3 --- a/src/bluetooth/bluetooth_health_channel.h +++ b/src/bluetooth/bluetooth_health_channel.h @@ -49,18 +49,13 @@ class BluetoothHealthChannel { */ void SendData(const picojson::value& data, picojson::object& out); - static void ToJson(unsigned int channel, - bt_hdp_channel_type_e type, - picojson::object* out); + static void ToJson(unsigned int channel, bt_hdp_channel_type_e type, picojson::object* out); - static void ToJson(unsigned int channel, - bt_hdp_channel_type_e type, - bt_device_info_s* device_info, - const char* app_id, - picojson::object* out); + static void ToJson(unsigned int channel, bt_hdp_channel_type_e type, + bt_device_info_s* device_info, const char* app_id, picojson::object* out); }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_HEALTH_CHANNEL_H_ +#endif // BLUETOOTH_BLUETOOTH_HEALTH_CHANNEL_H_ diff --git a/src/bluetooth/bluetooth_health_profile_handler.cc b/src/bluetooth/bluetooth_health_profile_handler.cc old mode 100755 new mode 100644 index ab0fe0b..7581eef --- a/src/bluetooth/bluetooth_health_profile_handler.cc +++ b/src/bluetooth/bluetooth_health_profile_handler.cc @@ -23,9 +23,9 @@ #include "common/tools.h" #include "bluetooth/bluetooth_adapter.h" -#include "bluetooth/bluetooth_instance.h" #include "bluetooth/bluetooth_health_application.h" #include "bluetooth/bluetooth_health_channel.h" +#include "bluetooth/bluetooth_instance.h" #include "bluetooth/bluetooth_privilege.h" #include "bluetooth/bluetooth_util.h" @@ -43,7 +43,7 @@ const std::string kOnConnect = "onconnect"; const std::string kOnClose = "onclose"; const std::string kOnMessage = "onmessage"; const std::string kChangeCallback = "BluetoothHealthChannelChangeCallback"; -} //namespace +} // namespace BluetoothHealthProfileHandler::BluetoothHealthProfileHandler(BluetoothInstance& instance) : instance_(instance) { @@ -68,12 +68,9 @@ BluetoothHealthProfileHandler::~BluetoothHealthProfileHandler() { } } -void BluetoothHealthProfileHandler::OnConnected(int result, - const char* remote_address, - const char* app_id, - bt_hdp_channel_type_e type, - unsigned int channel, - void* user_data) { +void BluetoothHealthProfileHandler::OnConnected(int result, const char* remote_address, + const char* app_id, bt_hdp_channel_type_e type, + unsigned int channel, void* user_data) { LoggerD("Entered"); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -117,10 +114,7 @@ void BluetoothHealthProfileHandler::OnConnected(int result, picojson::value result = picojson::value(picojson::object()); - BluetoothHealthChannel::ToJson(channel, - type, - device_info, - app_id, + BluetoothHealthChannel::ToJson(channel, type, device_info, app_id, &result.get()); ReportSuccess(result, response_obj); @@ -147,32 +141,27 @@ void BluetoothHealthProfileHandler::OnConnected(int result, picojson::value result = picojson::value(picojson::object()); - BluetoothHealthChannel::ToJson(channel, - type, - &result.get()); + BluetoothHealthChannel::ToJson(channel, type, &result.get()); ReportSuccess(result, response->get()); } else { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to establish a connection with health profile"), - &response->get(), - ("OnConnected result: %d (%s)", result, get_error_message(result))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, + "Failed to establish a connection with health profile"), + &response->get(), + ("OnConnected result: %d (%s)", result, get_error_message(result))); } object->instance_.AsyncResponse(request->second, response); // request was handled, remove object->connection_requests_.erase(request); - } - else { + } else { LoggerD("This connection was not requested."); } } -void BluetoothHealthProfileHandler::OnDisconnected(int result, - const char* /* remote_address */, - unsigned int channel, - void* user_data) { +void BluetoothHealthProfileHandler::OnDisconnected(int result, const char* /* remote_address */, + unsigned int channel, void* user_data) { LoggerD("Entered"); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -194,10 +183,8 @@ void BluetoothHealthProfileHandler::OnDisconnected(int result, } } -void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, - const char* data, - unsigned int size, - void* user_data) { +void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, const char* data, + unsigned int size, void* user_data) { LoggerD("Entered"); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -215,8 +202,9 @@ void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, data_obj->insert(std::make_pair(kEvent, picojson::value(kOnMessage))); data_obj->insert(std::make_pair(kId, picojson::value(std::to_string(channel)))); - picojson::array& array = data_obj->insert(std::make_pair(kData, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& array = + data_obj->insert(std::make_pair(kData, picojson::value(picojson::array()))) + .first->second.get(); for (unsigned int i = 0; i < size; i++) { array.push_back(picojson::value(static_cast(data[i]))); @@ -226,11 +214,12 @@ void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, } } -void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, picojson::object& out) { +void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, + picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothHealth, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, + &out); const auto& args = util::GetArguments(data); const auto data_type = static_cast(FromJson(args, "dataType")); @@ -238,7 +227,8 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, const auto callback_handle = util::GetAsyncCallbackHandle(data); - auto register_app = [data_type, name, this](const std::shared_ptr& response) -> void { + auto register_app = [data_type, name, + this](const std::shared_ptr& response) -> void { LoggerD("Entered"); PlatformResult platform_result = PlatformResult(ErrorCode::NO_ERROR); @@ -246,16 +236,13 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, const int ret = bt_hdp_register_sink_app(data_type, &app_id); switch (ret) { - case BT_ERROR_NONE: - { + case BT_ERROR_NONE: { LoggerD("Registered app: %s", app_id); this->registered_health_apps_.insert(app_id); picojson::value result = picojson::value(picojson::object()); - BluetoothHealthApplication::ToJson(data_type, - name, - app_id, + BluetoothHealthApplication::ToJson(data_type, name, app_id, &result.get()); ReportSuccess(result, response->get()); return; @@ -263,39 +250,38 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, case BT_ERROR_NOT_ENABLED: platform_result = LogAndCreateResult( - ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off", - ("bt_hdp_register_sink_app error %d (%s)", ret, get_error_message(ret))); + ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Bluetooth device is turned off", + ("bt_hdp_register_sink_app error %d (%s)", ret, get_error_message(ret))); break; default: platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error", - ("bt_hdp_register_sink_app() failed: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Unknown error", + ("bt_hdp_register_sink_app() failed: %d (%s)", ret, get_error_message(ret))); break; } LogAndReportError(platform_result, &response->get()); }; - auto register_app_response = [this, callback_handle](const std::shared_ptr& response) -> void { + auto register_app_response = + [this, callback_handle](const std::shared_ptr& response) -> void { instance_.SyncResponse(callback_handle, response); }; auto queue_data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - register_app, - register_app_response, - queue_data); + TaskQueue::GetInstance().Queue(register_app, register_app_response, queue_data); ReportSuccess(out); } -void BluetoothHealthProfileHandler::ConnectToSource(const picojson::value& data, picojson::object& out) { +void BluetoothHealthProfileHandler::ConnectToSource(const picojson::value& data, + picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothHealth, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, + &out); const auto& args = util::GetArguments(data); const auto& address = FromJson(args, "address"); @@ -359,7 +345,7 @@ void BluetoothHealthProfileHandler::UnregisterSinkAppAsync(const std::string& ap const int ret = bt_hdp_unregister_sink_app(app_id.c_str()); - switch(ret) { + switch (ret) { case BT_ERROR_NONE: this->registered_health_apps_.erase(iter); break; @@ -388,17 +374,15 @@ void BluetoothHealthProfileHandler::UnregisterSinkAppAsync(const std::string& ap } }; - auto unregister_app_response = [this, callback_handle](const std::shared_ptr& response) -> void { + auto unregister_app_response = + [this, callback_handle](const std::shared_ptr& response) -> void { instance_.SyncResponse(callback_handle, response); }; auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - unregister_app, - unregister_app_response, - data); + TaskQueue::GetInstance().Queue(unregister_app, unregister_app_response, data); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_health_profile_handler.h b/src/bluetooth/bluetooth_health_profile_handler.h old mode 100755 new mode 100644 index 9b4bada..39f55eb --- a/src/bluetooth/bluetooth_health_profile_handler.h +++ b/src/bluetooth/bluetooth_health_profile_handler.h @@ -49,7 +49,8 @@ class BluetoothHealthProfileHandler { void RegisterSinkApp(const picojson::value& data, picojson::object& out); /** - * Signature: @code void connectToSource(peer, application, successCallback, errorCallback); @endcode + * Signature: @code void connectToSource(peer, application, successCallback, errorCallback); + * @endcode * JSON: @code data: {method: 'BluetoothHealthProfileHandler_connectToSource', * args: {peer: peer, application: application}} @endcode * Invocation: @code native.call(request, result_callback); @endcode @@ -75,21 +76,13 @@ class BluetoothHealthProfileHandler { BluetoothHealthProfileHandler(const BluetoothHealthProfileHandler&) = delete; BluetoothHealthProfileHandler& operator=(const BluetoothHealthProfileHandler&) = delete; - static void OnConnected(int result, - const char* remote_address, - const char* app_id, - bt_hdp_channel_type_e type, - unsigned int channel, - void* user_data); + static void OnConnected(int result, const char* remote_address, const char* app_id, + bt_hdp_channel_type_e type, unsigned int channel, void* user_data); - static void OnDisconnected(int result, - const char* remote_address, - unsigned int channel, + static void OnDisconnected(int result, const char* remote_address, unsigned int channel, void* user_data); - static void OnDataReceived(unsigned int channel, - const char* data, - unsigned int size, + static void OnDataReceived(unsigned int channel, const char* data, unsigned int size, void* user_data); std::set registered_health_apps_; @@ -99,7 +92,7 @@ class BluetoothHealthProfileHandler { BluetoothInstance& instance_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_HEALTH_PROFILE_HANDLER_H_ +#endif // BLUETOOTH_BLUETOOTH_HEALTH_PROFILE_HANDLER_H_ diff --git a/src/bluetooth/bluetooth_instance.cc b/src/bluetooth/bluetooth_instance.cc old mode 100755 new mode 100644 index 158555f..3082985 --- a/src/bluetooth/bluetooth_instance.cc +++ b/src/bluetooth/bluetooth_instance.cc @@ -26,165 +26,162 @@ namespace bluetooth { using namespace common; -BluetoothInstance::BluetoothInstance() : - bluetooth_adapter_(*this), - bluetooth_device_(bluetooth_adapter_), - bluetooth_health_channel_(), - bluetooth_health_profile_handler_(*this), - bluetooth_health_application_(bluetooth_health_profile_handler_), - bluetooth_service_handler_(bluetooth_adapter_), - bluetooth_socket_(bluetooth_adapter_), - bluetooth_le_adapter_(*this), - bluetooth_gatt_service_(*this), - bluetooth_le_device_(*this, bluetooth_gatt_service_) -{ +BluetoothInstance::BluetoothInstance() + : bluetooth_adapter_(*this), + bluetooth_device_(bluetooth_adapter_), + bluetooth_health_channel_(), + bluetooth_health_profile_handler_(*this), + bluetooth_health_application_(bluetooth_health_profile_handler_), + bluetooth_service_handler_(bluetooth_adapter_), + bluetooth_socket_(bluetooth_adapter_), + bluetooth_le_adapter_(*this), + bluetooth_gatt_service_(*this), + bluetooth_le_device_(*this, bluetooth_gatt_service_) { LoggerD("Entered"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_ASYNC(c, func) \ - RegisterSyncHandler(c, func); - #define REGISTER_SYNC(c, func) \ - RegisterSyncHandler(c, func); +#define REGISTER_ASYNC(c, func) RegisterSyncHandler(c, func); +#define REGISTER_SYNC(c, func) RegisterSyncHandler(c, func); // BluetoothAdapter REGISTER_ASYNC("BluetoothAdapter_setName", - std::bind(&BluetoothAdapter::SetName, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::SetName, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_setPowered", - std::bind(&BluetoothAdapter::SetPowered, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::SetPowered, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_setVisible", - std::bind(&BluetoothAdapter::SetVisible, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::SetVisible, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_discoverDevices", - std::bind(&BluetoothAdapter::DiscoverDevices, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::DiscoverDevices, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_stopDiscovery", - std::bind(&BluetoothAdapter::StopDiscovery, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::StopDiscovery, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_getKnownDevices", - std::bind(&BluetoothAdapter::GetKnownDevices, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetKnownDevices, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_getDevice", - std::bind(&BluetoothAdapter::GetDevice, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetDevice, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_createBonding", - std::bind(&BluetoothAdapter::CreateBonding, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::CreateBonding, &bluetooth_adapter_, _1, _2)); REGISTER_ASYNC("BluetoothAdapter_destroyBonding", - std::bind(&BluetoothAdapter::DestroyBonding, &bluetooth_adapter_, _1, _2)); - REGISTER_ASYNC("BluetoothAdapter_registerRFCOMMServiceByUUID", + std::bind(&BluetoothAdapter::DestroyBonding, &bluetooth_adapter_, _1, _2)); + REGISTER_ASYNC( + "BluetoothAdapter_registerRFCOMMServiceByUUID", std::bind(&BluetoothAdapter::RegisterRFCOMMServiceByUUID, &bluetooth_adapter_, _1, _2)); - REGISTER_SYNC("BluetoothAdapter_getBluetoothProfileHandler", + REGISTER_SYNC( + "BluetoothAdapter_getBluetoothProfileHandler", std::bind(&BluetoothAdapter::GetBluetoothProfileHandler, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_getName", - std::bind(&BluetoothAdapter::GetName, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetName, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_getAddress", - std::bind(&BluetoothAdapter::GetAddress, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetAddress, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_getPowered", - std::bind(&BluetoothAdapter::GetPowered, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetPowered, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_getVisible", - std::bind(&BluetoothAdapter::GetVisible, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::GetVisible, &bluetooth_adapter_, _1, _2)); REGISTER_SYNC("BluetoothAdapter_isServiceConnected", - std::bind(&BluetoothAdapter::IsServiceConnected, &bluetooth_adapter_, _1, _2)); + std::bind(&BluetoothAdapter::IsServiceConnected, &bluetooth_adapter_, _1, _2)); // BluetoothDevice REGISTER_ASYNC("BluetoothDevice_connectToServiceByUUID", - std::bind(&BluetoothDevice::ConnectToServiceByUUID, &bluetooth_device_, _1, _2)); + std::bind(&BluetoothDevice::ConnectToServiceByUUID, &bluetooth_device_, _1, _2)); REGISTER_SYNC("BluetoothDevice_getBoolValue", - std::bind(&BluetoothDevice::GetBoolValue, &bluetooth_device_, _1, _2)); + std::bind(&BluetoothDevice::GetBoolValue, &bluetooth_device_, _1, _2)); // BluetoothHealthApplication - REGISTER_ASYNC("BluetoothHealthApplication_unregister", + REGISTER_ASYNC( + "BluetoothHealthApplication_unregister", std::bind(&BluetoothHealthApplication::Unregister, &bluetooth_health_application_, _1, _2)); // BluetoothHealthChannel REGISTER_SYNC("BluetoothHealthChannel_close", - std::bind(&BluetoothHealthChannel::Close, &bluetooth_health_channel_, _1, _2)); + std::bind(&BluetoothHealthChannel::Close, &bluetooth_health_channel_, _1, _2)); REGISTER_SYNC("BluetoothHealthChannel_sendData", - std::bind(&BluetoothHealthChannel::SendData, &bluetooth_health_channel_, _1, _2)); + std::bind(&BluetoothHealthChannel::SendData, &bluetooth_health_channel_, _1, _2)); // BluetoothHealthProfileHandler REGISTER_ASYNC("BluetoothHealthProfileHandler_registerSinkApp", - std::bind(&BluetoothHealthProfileHandler::RegisterSinkApp, &bluetooth_health_profile_handler_, _1, _2)); + std::bind(&BluetoothHealthProfileHandler::RegisterSinkApp, + &bluetooth_health_profile_handler_, _1, _2)); REGISTER_ASYNC("BluetoothHealthProfileHandler_connectToSource", - std::bind(&BluetoothHealthProfileHandler::ConnectToSource, &bluetooth_health_profile_handler_, _1, _2)); + std::bind(&BluetoothHealthProfileHandler::ConnectToSource, + &bluetooth_health_profile_handler_, _1, _2)); // BluetoothServiceHandler - REGISTER_ASYNC("BluetoothServiceHandler_unregister", + REGISTER_ASYNC( + "BluetoothServiceHandler_unregister", std::bind(&BluetoothServiceHandler::Unregister, &bluetooth_service_handler_, _1, _2)); // BluetoothSocket REGISTER_SYNC("BluetoothSocket_writeData", - std::bind(&BluetoothSocket::WriteData, &bluetooth_socket_, _1, _2)); + std::bind(&BluetoothSocket::WriteData, &bluetooth_socket_, _1, _2)); REGISTER_SYNC("BluetoothSocket_readData", - std::bind(&BluetoothSocket::ReadData, &bluetooth_socket_, _1, _2)); + std::bind(&BluetoothSocket::ReadData, &bluetooth_socket_, _1, _2)); REGISTER_SYNC("BluetoothSocket_close", - std::bind(&BluetoothSocket::Close, &bluetooth_socket_, _1, _2)); + std::bind(&BluetoothSocket::Close, &bluetooth_socket_, _1, _2)); // BluetoothLEAdapter REGISTER_SYNC("BluetoothLEAdapter_startScan", - std::bind(&BluetoothLEAdapter::StartScan, &bluetooth_le_adapter_, _1, _2)); + std::bind(&BluetoothLEAdapter::StartScan, &bluetooth_le_adapter_, _1, _2)); REGISTER_SYNC("BluetoothLEAdapter_stopScan", - std::bind(&BluetoothLEAdapter::StopScan, &bluetooth_le_adapter_, _1, _2)); + std::bind(&BluetoothLEAdapter::StopScan, &bluetooth_le_adapter_, _1, _2)); REGISTER_SYNC("BluetoothLEAdapter_startAdvertise", - std::bind(&BluetoothLEAdapter::StartAdvertise, &bluetooth_le_adapter_, _1, _2)); + std::bind(&BluetoothLEAdapter::StartAdvertise, &bluetooth_le_adapter_, _1, _2)); REGISTER_SYNC("BluetoothLEAdapter_stopAdvertise", - std::bind(&BluetoothLEAdapter::StopAdvertise, &bluetooth_le_adapter_, _1, _2)); + std::bind(&BluetoothLEAdapter::StopAdvertise, &bluetooth_le_adapter_, _1, _2)); // BluetoothLEDevice - REGISTER_ASYNC( - "BluetoothLEDevice_connect", - std::bind(&BluetoothLEDevice::Connect, &bluetooth_le_device_, _1, _2)); - REGISTER_ASYNC( - "BluetoothLEDevice_disconnect", - std::bind(&BluetoothLEDevice::Disconnect, &bluetooth_le_device_, _1, _2)); - REGISTER_SYNC( - "BluetoothLEDevice_getService", - std::bind(&BluetoothLEDevice::GetService, &bluetooth_le_device_, _1, _2)); + REGISTER_ASYNC("BluetoothLEDevice_connect", + std::bind(&BluetoothLEDevice::Connect, &bluetooth_le_device_, _1, _2)); + REGISTER_ASYNC("BluetoothLEDevice_disconnect", + std::bind(&BluetoothLEDevice::Disconnect, &bluetooth_le_device_, _1, _2)); + REGISTER_SYNC("BluetoothLEDevice_getService", + std::bind(&BluetoothLEDevice::GetService, &bluetooth_le_device_, _1, _2)); REGISTER_SYNC( "BluetoothLEDevice_addConnectStateChangeListener", - std::bind(&BluetoothLEDevice::AddConnectStateChangeListener, - &bluetooth_le_device_, _1, _2)); - REGISTER_SYNC( - "BluetoothLEDevice_removeConnectStateChangeListener", - std::bind(&BluetoothLEDevice::RemoveConnectStateChangeListener, - &bluetooth_le_device_, _1, _2)); - REGISTER_SYNC( - "BluetoothLEDevice_getServiceAllUuids", - std::bind(&BluetoothLEDevice::GetServiceAllUuids, - &bluetooth_le_device_, _1, _2)); + std::bind(&BluetoothLEDevice::AddConnectStateChangeListener, &bluetooth_le_device_, _1, _2)); + REGISTER_SYNC("BluetoothLEDevice_removeConnectStateChangeListener", + std::bind(&BluetoothLEDevice::RemoveConnectStateChangeListener, + &bluetooth_le_device_, _1, _2)); + REGISTER_SYNC("BluetoothLEDevice_getServiceAllUuids", + std::bind(&BluetoothLEDevice::GetServiceAllUuids, &bluetooth_le_device_, _1, _2)); // BluetoothGATTService REGISTER_SYNC("BluetoothGATTService_getServices", - std::bind(&BluetoothGATTService::GetServices, &bluetooth_gatt_service_, _1, _2)); - REGISTER_SYNC("BluetoothGATTService_getCharacteristics", + std::bind(&BluetoothGATTService::GetServices, &bluetooth_gatt_service_, _1, _2)); + REGISTER_SYNC( + "BluetoothGATTService_getCharacteristics", std::bind(&BluetoothGATTService::GetCharacteristics, &bluetooth_gatt_service_, _1, _2)); REGISTER_SYNC("BluetoothGATT_readValue", - std::bind(&BluetoothGATTService::ReadValue, &bluetooth_gatt_service_, _1, _2)); + std::bind(&BluetoothGATTService::ReadValue, &bluetooth_gatt_service_, _1, _2)); REGISTER_SYNC("BluetoothGATT_writeValue", - std::bind(&BluetoothGATTService::WriteValue, &bluetooth_gatt_service_, _1, _2)); + std::bind(&BluetoothGATTService::WriteValue, &bluetooth_gatt_service_, _1, _2)); REGISTER_SYNC( "BluetoothGATTCharacteristic_addValueChangeListener", - std::bind(&BluetoothGATTService::AddValueChangeListener, - &bluetooth_gatt_service_, _1, _2)); - REGISTER_SYNC( - "BluetoothGATTCharacteristic_removeValueChangeListener", - std::bind(&BluetoothGATTService::RemoveValueChangeListener, - &bluetooth_gatt_service_, _1, _2)); + std::bind(&BluetoothGATTService::AddValueChangeListener, &bluetooth_gatt_service_, _1, _2)); + REGISTER_SYNC("BluetoothGATTCharacteristic_removeValueChangeListener", + std::bind(&BluetoothGATTService::RemoveValueChangeListener, + &bluetooth_gatt_service_, _1, _2)); - #undef REGISTER_ASYNC - #undef REGISTER_SYNC +#undef REGISTER_ASYNC +#undef REGISTER_SYNC } -BluetoothInstance::~BluetoothInstance() -{ +BluetoothInstance::~BluetoothInstance() { LoggerD("Entered"); } namespace { const char* JSON_CALLBACK_ID = "callbackId"; const char* JSON_LISTENER_ID = "listenerId"; -} // namespace +} // namespace -void BluetoothInstance::AsyncResponse(double callback_handle, const std::shared_ptr& response) { +void BluetoothInstance::AsyncResponse(double callback_handle, + const std::shared_ptr& response) { LoggerD("Entered"); - common::TaskQueue::GetInstance().Async([this, callback_handle](const std::shared_ptr& response) { - SyncResponse(callback_handle, response); - }, response); + common::TaskQueue::GetInstance().Async( + [this, callback_handle](const std::shared_ptr& response) { + SyncResponse(callback_handle, response); + }, + response); } void BluetoothInstance::AsyncResponse(double callback_handle, const PlatformResult& result) { @@ -198,12 +195,15 @@ void BluetoothInstance::AsyncResponse(double callback_handle, const PlatformResu ReportSuccess(response->get()); } - TaskQueue::GetInstance().Async([this, callback_handle](const std::shared_ptr& response) { - SyncResponse(callback_handle, response); - }, response); + TaskQueue::GetInstance().Async( + [this, callback_handle](const std::shared_ptr& response) { + SyncResponse(callback_handle, response); + }, + response); } -void BluetoothInstance::SyncResponse(double callback_handle, const std::shared_ptr& response) { +void BluetoothInstance::SyncResponse(double callback_handle, + const std::shared_ptr& response) { LoggerD("Entered"); auto& obj = response->get(); obj[JSON_CALLBACK_ID] = picojson::value(callback_handle); @@ -223,12 +223,11 @@ void BluetoothInstance::FireEvent(const std::string& event, const picojson::valu FireEvent(event, v); } -void BluetoothInstance::FireEvent(const std::string& event, const std::shared_ptr& value) { +void BluetoothInstance::FireEvent(const std::string& event, + const std::shared_ptr& value) { LoggerD("Entered"); FireEvent(event, *value.get()); } - -} // namespace bluetooth -} // namespace extension - +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_instance.h b/src/bluetooth/bluetooth_instance.h old mode 100755 new mode 100644 index 30bb4cf..6fb0023 --- a/src/bluetooth/bluetooth_instance.h +++ b/src/bluetooth/bluetooth_instance.h @@ -21,6 +21,7 @@ #include "bluetooth/bluetooth_adapter.h" #include "bluetooth/bluetooth_device.h" +#include "bluetooth/bluetooth_gatt_service.h" #include "bluetooth/bluetooth_health_application.h" #include "bluetooth/bluetooth_health_channel.h" #include "bluetooth/bluetooth_health_profile_handler.h" @@ -28,13 +29,12 @@ #include "bluetooth/bluetooth_le_device.h" #include "bluetooth/bluetooth_service_handler.h" #include "bluetooth/bluetooth_socket.h" -#include "bluetooth/bluetooth_gatt_service.h" #include "bluetooth/bluetooth_util.h" namespace extension { namespace bluetooth { -class BluetoothInstance: public common::ParsedInstance { +class BluetoothInstance : public common::ParsedInstance { public: BluetoothInstance(); virtual ~BluetoothInstance(); @@ -60,7 +60,7 @@ class BluetoothInstance: public common::ParsedInstance { BluetoothLEDevice bluetooth_le_device_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_INSTANCE_H_ +#endif // BLUETOOTH_BLUETOOTH_INSTANCE_H_ diff --git a/src/bluetooth/bluetooth_le_adapter.cc b/src/bluetooth/bluetooth_le_adapter.cc old mode 100755 new mode 100644 index b63fc32..58efa13 --- a/src/bluetooth/bluetooth_le_adapter.cc +++ b/src/bluetooth/bluetooth_le_adapter.cc @@ -16,13 +16,13 @@ #include "bluetooth/bluetooth_le_adapter.h" -#include "common/tools.h" #include "common/logger.h" +#include "common/tools.h" #include "bluetooth/bluetooth_instance.h" #include "bluetooth/bluetooth_le_device.h" -#include "bluetooth/bluetooth_util.h" #include "bluetooth/bluetooth_privilege.h" +#include "bluetooth/bluetooth_util.h" namespace extension { namespace bluetooth { @@ -31,8 +31,10 @@ namespace { class ParsedDataHolder { public: - ParsedDataHolder() : valid_(false) {} - virtual ~ParsedDataHolder() {} + ParsedDataHolder() : valid_(false) { + } + virtual ~ParsedDataHolder() { + } bool valid() const { return valid_; @@ -49,8 +51,7 @@ class ParsedDataHolder { class HexData { public: - HexData() - : length_(0) { + HexData() : length_(0) { } void Parse(const std::string& d) { @@ -88,11 +89,8 @@ class BluetoothLEServiceData : public ParsedDataHolder { return data_; } - static bool Construct(const picojson::value& obj, - BluetoothLEServiceData* out) { - if (!obj.is() || - !ParseUUID(obj, out) || - !ParseData(obj, out)) { + static bool Construct(const picojson::value& obj, BluetoothLEServiceData* out) { + if (!obj.is() || !ParseUUID(obj, out) || !ParseData(obj, out)) { return false; } @@ -102,8 +100,7 @@ class BluetoothLEServiceData : public ParsedDataHolder { } private: - static bool ParseUUID(const picojson::value& obj, - BluetoothLEServiceData* out) { + static bool ParseUUID(const picojson::value& obj, BluetoothLEServiceData* out) { LoggerD("Entered"); const auto& uuid = obj.get("uuid"); if (uuid.is()) { @@ -115,8 +112,7 @@ class BluetoothLEServiceData : public ParsedDataHolder { return true; } - static bool ParseData(const picojson::value& obj, - BluetoothLEServiceData* out) { + static bool ParseData(const picojson::value& obj, BluetoothLEServiceData* out) { LoggerD("Entered"); const auto& data = obj.get("data"); if (data.is()) { @@ -142,12 +138,9 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { return data_; } - static bool Construct(const picojson::value& obj, - BluetoothLEManufacturerData* out) { + static bool Construct(const picojson::value& obj, BluetoothLEManufacturerData* out) { LoggerD("Entered"); - if (!obj.is() || - !ParseId(obj, out) || - !ParseData(obj, out)) { + if (!obj.is() || !ParseId(obj, out) || !ParseData(obj, out)) { return false; } @@ -157,8 +150,7 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { } private: - static bool ParseId(const picojson::value& obj, - BluetoothLEManufacturerData* out) { + static bool ParseId(const picojson::value& obj, BluetoothLEManufacturerData* out) { LoggerD("Entered"); const auto& id = obj.get("id"); if (id.is()) { @@ -170,8 +162,7 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { return true; } - static bool ParseData(const picojson::value& obj, - BluetoothLEManufacturerData* out) { + static bool ParseData(const picojson::value& obj, BluetoothLEManufacturerData* out) { LoggerD("Entered"); const auto& val_data = obj.get("data"); @@ -225,17 +216,12 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return manufacturer_data_; } - static bool Construct(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool Construct(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); - if (!obj.is() || - !ParseIncludeName(obj, out) || - !ParseServiceUUIDs(obj, out) || - !ParseSolicitationUUIDs(obj, out) || - !ParseAppearance(obj, out) || - !ParseIncludeTxPowerLevel(obj, out) || - !ParseServiceData(obj, out) || - !ParseManufacturerData(obj, out)) { + if (!obj.is() || !ParseIncludeName(obj, out) || + !ParseServiceUUIDs(obj, out) || !ParseSolicitationUUIDs(obj, out) || + !ParseAppearance(obj, out) || !ParseIncludeTxPowerLevel(obj, out) || + !ParseServiceData(obj, out) || !ParseManufacturerData(obj, out)) { return false; } @@ -245,8 +231,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } private: - static bool ParseIncludeName(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseIncludeName(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& include_name = obj.get("includeName"); if (include_name.is()) { @@ -258,8 +243,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseServiceUUIDs(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseServiceUUIDs(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& service_uuids = obj.get("uuids"); if (service_uuids.is()) { @@ -277,8 +261,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseSolicitationUUIDs(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseSolicitationUUIDs(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& solicitation_uuids = obj.get("solicitationuuids"); if (solicitation_uuids.is()) { @@ -296,8 +279,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseAppearance(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseAppearance(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& appearance = obj.get("appearance"); if (appearance.is()) { @@ -309,8 +291,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseIncludeTxPowerLevel(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseIncludeTxPowerLevel(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& include_tx_power_level = obj.get("includeTxPowerLevel"); if (include_tx_power_level.is()) { @@ -322,8 +303,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseServiceData(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseServiceData(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& service_data = obj.get("serviceData"); BluetoothLEServiceData data; @@ -336,8 +316,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { return true; } - static bool ParseManufacturerData(const picojson::value& obj, - BluetoothLEAdvertiseData* out) { + static bool ParseManufacturerData(const picojson::value& obj, BluetoothLEAdvertiseData* out) { LoggerD("Entered"); const auto& manufacturer_data = obj.get("manufacturerData"); BluetoothLEManufacturerData data; @@ -378,7 +357,7 @@ const std::string kOnAdvertiseState = "onstate"; const std::string kOnAdvertiseError = "onerror"; const std::string kAdvertiseEvent = "BluetoothLEAdvertiseCallback"; -} // namespace +} // namespace using common::ErrorCode; using common::PlatformResult; @@ -386,10 +365,7 @@ using common::tools::ReportError; using common::tools::ReportSuccess; BluetoothLEAdapter::BluetoothLEAdapter(BluetoothInstance& instance) - : instance_(instance), - enabled_(false), - scanning_(false), - bt_advertiser_(nullptr) { + : instance_(instance), enabled_(false), scanning_(false), bt_advertiser_(nullptr) { LoggerD("Entered"); bt_adapter_le_state_e le_state = BT_ADAPTER_LE_DISABLED; @@ -422,25 +398,22 @@ BluetoothLEAdapter::~BluetoothLEAdapter() { void BluetoothLEAdapter::StartScan(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); int ret = bt_adapter_le_start_scan(OnScanResult, this); if (BT_ERROR_NONE != ret) { if (BT_ERROR_NOW_IN_PROGRESS == ret) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Scan already in progress"), &out, - ("Scan in progress %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Scan already in progress"), + &out, ("Scan in progress %d (%s)", ret, get_error_message(ret))); } else { - // other errors are reported asynchronously picojson::value value = picojson::value(picojson::object()); picojson::object* data_obj = &value.get(); data_obj->insert(std::make_pair(kAction, picojson::value(kOnScanError))); - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to start scan"), data_obj, - ("Failed to start scan: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to start scan"), data_obj, + ("Failed to start scan: %d (%s)", ret, get_error_message(ret))); instance_.FireEvent(kScanEvent, value); } } else { @@ -451,15 +424,14 @@ void BluetoothLEAdapter::StartScan(const picojson::value& data, picojson::object void BluetoothLEAdapter::StopScan(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); int ret = bt_adapter_le_stop_scan(); if (BT_ERROR_NONE != ret && BT_ERROR_NOT_IN_PROGRESS != ret) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to stop scan"), &out, - ("Failed to stop scan: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to stop scan"), &out, + ("Failed to stop scan: %d (%s)", ret, get_error_message(ret))); } else { scanning_ = false; ReportSuccess(out); @@ -468,20 +440,18 @@ void BluetoothLEAdapter::StopScan(const picojson::value& data, picojson::object& void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto& json_advertise_data = data.get("advertiseData"); const auto& json_packet_type = data.get("packetType"); const auto& json_mode = data.get("mode"); const auto& json_connectable = data.get("connectable"); - if (!json_advertise_data.is() || - !json_packet_type.is() || - !json_mode.is() || - !json_connectable.is()) { - LogAndReportError( - PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, "Unexpected parameter type"), &out); + if (!json_advertise_data.is() || !json_packet_type.is() || + !json_mode.is() || !json_connectable.is()) { + LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, "Unexpected parameter type"), + &out); return; } @@ -517,16 +487,15 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o } else if ("LOW_ENERGY" == str_mode) { mode = BT_ADAPTER_LE_ADVERTISING_MODE_LOW_ENERGY; } else { - LogAndReportError( - PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, "Unexpected value of mode"), &out, - ("Wrong mode: %s", str_mode.c_str())); + LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, "Unexpected value of mode"), + &out, ("Wrong mode: %s", str_mode.c_str())); return; } } if (nullptr != bt_advertiser_) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, "Advertise already in progress"), &out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Advertise already in progress"), + &out); return; } @@ -540,41 +509,40 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o return; } - std::unique_ptr::type, - int (*)(bt_advertiser_h)> advertiser_ptr(advertiser, &bt_adapter_le_destroy_advertiser); // automatically release the memory + std::unique_ptr::type, int (*)(bt_advertiser_h)> + advertiser_ptr(advertiser, + &bt_adapter_le_destroy_advertiser); // automatically release the memory // configure advertiser if (advertise_data.include_name()) { ret = bt_adapter_le_set_advertising_device_name(advertiser, packet_type, - advertise_data.include_name()); + advertise_data.include_name()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_set_advertising_device_name() failed with: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_set_advertising_device_name() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } for (const auto& i : advertise_data.service_uuids()) { - ret = bt_adapter_le_add_advertising_service_uuid(advertiser, packet_type, - i.c_str()); + ret = bt_adapter_le_add_advertising_service_uuid(advertiser, packet_type, i.c_str()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_add_advertising_service_uuid() failed with: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_add_advertising_service_uuid() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } for (const auto& i : advertise_data.solicitation_uuids()) { - ret = bt_adapter_le_add_advertising_service_solicitation_uuid(advertiser, - packet_type, - i.c_str()); + ret = + bt_adapter_le_add_advertising_service_solicitation_uuid(advertiser, packet_type, i.c_str()); if (BT_ERROR_NONE != ret) { LogAndReportError( util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_add_advertising_service_solicitation_uuid() failed with: %d (%s)", - ret, get_error_message(ret))); + ("bt_adapter_le_add_advertising_service_solicitation_uuid() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } @@ -582,10 +550,9 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o ret = bt_adapter_le_set_advertising_appearance(advertiser, packet_type, advertise_data.appearance()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_set_advertising_appearance() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_set_advertising_appearance() failed with: %d (%s)", ret, + get_error_message(ret))); return; } @@ -593,10 +560,9 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o ret = bt_adapter_le_set_advertising_tx_power_level(advertiser, packet_type, advertise_data.include_tx_power_level()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_set_advertising_tx_power_level() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_set_advertising_tx_power_level() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } @@ -605,15 +571,13 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o if (service_data.uuid().empty() && nullptr == service_data.data().pointer()) { LoggerD("service data is empty"); } else { - ret = bt_adapter_le_add_advertising_service_data(advertiser, packet_type, - service_data.uuid().c_str(), - service_data.data().pointer(), - service_data.data().length()); + ret = bt_adapter_le_add_advertising_service_data( + advertiser, packet_type, service_data.uuid().c_str(), service_data.data().pointer(), + service_data.data().length()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_add_advertising_service_data() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_add_advertising_service_data() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } @@ -623,16 +587,13 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o LoggerD("manufacturerData is empty"); } else { if (manufacturer_data.valid()) { - ret = bt_adapter_le_add_advertising_manufacturer_data(advertiser, - packet_type, - atoi(manufacturer_data.id().c_str()), - manufacturer_data.data().pointer(), - manufacturer_data.data().length()); + ret = bt_adapter_le_add_advertising_manufacturer_data( + advertiser, packet_type, atoi(manufacturer_data.id().c_str()), + manufacturer_data.data().pointer(), manufacturer_data.data().length()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_add_advertising_manufacturer_data() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_add_advertising_manufacturer_data() failed with: %d (%s)", + ret, get_error_message(ret))); return; } } @@ -642,17 +603,15 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o if (BT_ERROR_NONE != ret) { LogAndReportError( util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_set_advertising_mode() failed with: %d (%s)", - ret, get_error_message(ret))); + ("bt_adapter_le_set_advertising_mode() failed with: %d (%s)", ret, get_error_message(ret))); return; } ret = bt_adapter_le_set_advertising_connectable(advertiser, json_connectable.get()); if (BT_ERROR_NONE != ret) { - LogAndReportError( - util::GetBluetoothError(ret, "Failed to create advertiser"), &out, - ("bt_adapter_le_set_advertising_connectable() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to create advertiser"), &out, + ("bt_adapter_le_set_advertising_connectable() failed with: %d (%s)", ret, + get_error_message(ret))); return; } @@ -666,30 +625,29 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o return; } - LogAndReportError( - util::GetBluetoothError(ret, "Failed to start advertising"), &out, - ("bt_adapter_le_start_advertising_new() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(util::GetBluetoothError(ret, "Failed to start advertising"), &out, + ("bt_adapter_le_start_advertising_new() failed with: %d (%s)", ret, + get_error_message(ret))); return; } - // everything went well, we want to store the pointer, so unique_ptr should no longer manage the memory + // everything went well, we want to store the pointer, so unique_ptr should no longer manage the + // memory bt_advertiser_ = advertiser_ptr.release(); ReportSuccess(out); } void BluetoothLEAdapter::StopAdvertise(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); if (nullptr != bt_advertiser_) { int ret = bt_adapter_le_stop_advertising(bt_advertiser_); if (BT_ERROR_NONE != ret && BT_ERROR_NOT_IN_PROGRESS != ret) { LogAndReportError( PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to stop advertising"), &out, - ("bt_adapter_le_stop_advertising() failed with: %d (%s)", - ret, get_error_message(ret))); + ("bt_adapter_le_stop_advertising() failed with: %d (%s)", ret, get_error_message(ret))); return; } @@ -701,8 +659,7 @@ void BluetoothLEAdapter::StopAdvertise(const picojson::value& data, picojson::ob ReportSuccess(out); } -void BluetoothLEAdapter::OnStateChanged(int result, - bt_adapter_le_state_e adapter_le_state, +void BluetoothLEAdapter::OnStateChanged(int result, bt_adapter_le_state_e adapter_le_state, void* user_data) { LoggerD("Entered"); @@ -716,9 +673,8 @@ void BluetoothLEAdapter::OnStateChanged(int result, adapter->enabled_ = ToBool(adapter_le_state); } -void BluetoothLEAdapter::OnScanResult( - int result, bt_adapter_le_device_scan_result_info_s* info, - void* user_data) { +void BluetoothLEAdapter::OnScanResult(int result, bt_adapter_le_device_scan_result_info_s* info, + void* user_data) { LoggerD("Entered, result: %d, info: %p, data: %p", result, info, user_data); auto adapter = static_cast(user_data); @@ -732,9 +688,8 @@ void BluetoothLEAdapter::OnScanResult( picojson::object* data_obj = &value.get(); if (BT_ERROR_NONE != result) { - LogAndReportError( - util::GetBluetoothError(result, "Error during scanning"), data_obj, - ("Error during scanning: %d (%s)", result, get_error_message(result))); + LogAndReportError(util::GetBluetoothError(result, "Error during scanning"), data_obj, + ("Error during scanning: %d (%s)", result, get_error_message(result))); data_obj->insert(std::make_pair(kAction, picojson::value(kOnScanError))); } else { // this is probably capi-network-bluetooth error: when scan is stopped info has 0x1 value @@ -756,10 +711,11 @@ void BluetoothLEAdapter::OnScanResult( adapter->instance_.FireEvent(kScanEvent, value); } -void BluetoothLEAdapter::OnAdvertiseResult( - int result, bt_advertiser_h advertiser, - bt_adapter_le_advertising_state_e adv_state, void* user_data) { - LoggerD("Entered, result: %d, advertiser: %p, adv_state: %d, user_data: %p", result, advertiser, adv_state, user_data); +void BluetoothLEAdapter::OnAdvertiseResult(int result, bt_advertiser_h advertiser, + bt_adapter_le_advertising_state_e adv_state, + void* user_data) { + LoggerD("Entered, result: %d, advertiser: %p, adv_state: %d, user_data: %p", result, advertiser, + adv_state, user_data); auto adapter = static_cast(user_data); @@ -772,23 +728,21 @@ void BluetoothLEAdapter::OnAdvertiseResult( picojson::object* data_obj = &value.get(); if (BT_ERROR_NONE != result) { - LogAndReportError( - util::GetBluetoothError(result, "Error during advertising"), data_obj, - ("Error during advertising: %d (%s)", result, get_error_message(result))); + LogAndReportError(util::GetBluetoothError(result, "Error during advertising"), data_obj, + ("Error during advertising: %d (%s)", result, get_error_message(result))); data_obj->insert(std::make_pair(kAction, picojson::value(kOnAdvertiseError))); } else { const char* state = (BT_ADAPTER_LE_ADVERTISING_STARTED == adv_state) ? "STARTED" : "STOPPED"; LoggerD("Advertise state is: %s", state); data_obj->insert(std::make_pair(kAction, picojson::value(kOnAdvertiseState))); ReportSuccess(picojson::value(state), *data_obj); - if (adv_state == BT_ADAPTER_LE_ADVERTISING_STOPPED){ + if (adv_state == BT_ADAPTER_LE_ADVERTISING_STOPPED) { LoggerD("Advertiser destroy"); - int ret = bt_adapter_le_destroy_advertiser(advertiser); + int ret = bt_adapter_le_destroy_advertiser(advertiser); if (BT_ERROR_NONE != ret && BT_ERROR_NOT_IN_PROGRESS != ret) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to destroy advertiser"), data_obj, - ("bt_adapter_le_destroy_advertiser() failed with: %d (%s)", - ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to destroy advertiser"), + data_obj, ("bt_adapter_le_destroy_advertiser() failed with: %d (%s)", ret, + get_error_message(ret))); return; } } @@ -797,5 +751,5 @@ void BluetoothLEAdapter::OnAdvertiseResult( adapter->instance_.FireEvent(kAdvertiseEvent, value); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_le_adapter.h b/src/bluetooth/bluetooth_le_adapter.h old mode 100755 new mode 100644 index 2c3a928..ed303cc --- a/src/bluetooth/bluetooth_le_adapter.h +++ b/src/bluetooth/bluetooth_le_adapter.h @@ -44,14 +44,11 @@ class BluetoothLEAdapter { BluetoothLEAdapter& operator=(const BluetoothLEAdapter&) = delete; BluetoothLEAdapter& operator=(const BluetoothLEAdapter&&) = delete; - static void OnStateChanged(int result, bt_adapter_le_state_e adapter_le_state, - void* user_data); - static void OnScanResult(int result, - bt_adapter_le_device_scan_result_info_s* info, + static void OnStateChanged(int result, bt_adapter_le_state_e adapter_le_state, void* user_data); + static void OnScanResult(int result, bt_adapter_le_device_scan_result_info_s* info, void* user_data); static void OnAdvertiseResult(int result, bt_advertiser_h advertiser, - bt_adapter_le_advertising_state_e adv_state, - void* user_data); + bt_adapter_le_advertising_state_e adv_state, void* user_data); BluetoothInstance& instance_; bool enabled_; @@ -59,7 +56,7 @@ class BluetoothLEAdapter { bt_advertiser_h bt_advertiser_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_LE_ADAPTER_H_ +#endif // BLUETOOTH_BLUETOOTH_LE_ADAPTER_H_ diff --git a/src/bluetooth/bluetooth_le_device.cc b/src/bluetooth/bluetooth_le_device.cc old mode 100755 new mode 100644 index a4f27dc..34e2964 --- a/src/bluetooth/bluetooth_le_device.cc +++ b/src/bluetooth/bluetooth_le_device.cc @@ -18,8 +18,8 @@ #include #include "bluetooth/bluetooth_instance.h" -#include "bluetooth/bluetooth_util.h" #include "bluetooth/bluetooth_privilege.h" +#include "bluetooth/bluetooth_util.h" #include "common/converter.h" #include "common/logger.h" @@ -35,7 +35,7 @@ namespace extension { namespace bluetooth { namespace { -//le_device +// le_device const std::string kDeviceName = "name"; const std::string kDeviceAddress = "address"; const std::string kTxPowerLevel = "txpowerlevel"; @@ -53,14 +53,10 @@ const std::string kRSSI = "rssi"; const std::string kOnConnected = "onconnected"; const std::string kOnDisconnected = "ondisconnected"; const std::string kConnectChangeEvent = "BluetoothLEConnectChangeCallback"; - } -BluetoothLEDevice::BluetoothLEDevice(BluetoothInstance& instance, - BluetoothGATTService& service) - : instance_(instance), - service_(service), - is_listener_set_(false) { +BluetoothLEDevice::BluetoothLEDevice(BluetoothInstance& instance, BluetoothGATTService& service) + : instance_(instance), service_(service), is_listener_set_(false) { LoggerD("Entered"); int ret = bt_gatt_set_connection_state_changed_cb(GattConnectionState, this); if (BT_ERROR_NONE != ret && BT_ERROR_ALREADY_DONE != ret) { @@ -76,42 +72,38 @@ BluetoothLEDevice::~BluetoothLEDevice() { } } -static void UUIDsToJson(char **service_uuid, int service_count, - const std::string &field, picojson::object* le_device) { +static void UUIDsToJson(char** service_uuid, int service_count, const std::string& field, + picojson::object* le_device) { LoggerD("Entered"); - picojson::array& array = le_device->insert( - std::make_pair(field, picojson::value(picojson::array()))).first->second - .get(); + picojson::array& array = + le_device->insert(std::make_pair(field, picojson::value(picojson::array()))) + .first->second.get(); for (int i = 0; i < service_count; i++) { array.push_back(picojson::value(service_uuid[i])); } } -static void ServiceDataToJson(bt_adapter_le_service_data_s *service_data_list, - int service_data_list_count, - picojson::object* le_device) { +static void ServiceDataToJson(bt_adapter_le_service_data_s* service_data_list, + int service_data_list_count, picojson::object* le_device) { LoggerD("Entered"); - picojson::array& array = le_device->insert( - std::make_pair(kServiceData, picojson::value(picojson::array()))).first - ->second.get(); + picojson::array& array = + le_device->insert(std::make_pair(kServiceData, picojson::value(picojson::array()))) + .first->second.get(); std::unique_ptr service_data_hex; for (int i = 0; i < service_data_list_count; i++) { picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); - response_obj[kServiceUuid] = picojson::value( - std::string(service_data_list[i].service_uuid)); + response_obj[kServiceUuid] = picojson::value(std::string(service_data_list[i].service_uuid)); const int hex_count = service_data_list[i].service_data_len * 2; service_data_hex.reset(new char[hex_count + 1]); - BinToHex((const unsigned char*) service_data_list[i].service_data, - service_data_list[i].service_data_len, - service_data_hex.get(), - hex_count); + BinToHex((const unsigned char*)service_data_list[i].service_data, + service_data_list[i].service_data_len, service_data_hex.get(), hex_count); service_data_hex[hex_count] = '\0'; response_obj[kData] = picojson::value(std::string(service_data_hex.get())); @@ -119,9 +111,7 @@ static void ServiceDataToJson(bt_adapter_le_service_data_s *service_data_list, } } -static void ManufacturerToJson(int manufacturer_id, - char *manufacturer_data, - int manufacturer_count, +static void ManufacturerToJson(int manufacturer_id, char* manufacturer_data, int manufacturer_count, picojson::object* le_device) { LoggerD("Entered"); @@ -131,39 +121,32 @@ static void ManufacturerToJson(int manufacturer_id, const int hex_count = manufacturer_count * 2; char* manuf_data_hex = new char[hex_count + 1]; - BinToHex((const unsigned char*) manufacturer_data, - manufacturer_count, - manuf_data_hex, - hex_count); + BinToHex((const unsigned char*)manufacturer_data, manufacturer_count, manuf_data_hex, hex_count); manuf_data_hex[hex_count] = '\0'; response_obj[kData] = picojson::value(std::string(manuf_data_hex)); - delete [] manuf_data_hex; + delete[] manuf_data_hex; manuf_data_hex = nullptr; le_device->insert(std::make_pair(kManufacturerData, response)); } -PlatformResult BluetoothLEDevice::ToJson( - bt_adapter_le_device_scan_result_info_s* info, - picojson::object* le_device) { - +PlatformResult BluetoothLEDevice::ToJson(bt_adapter_le_device_scan_result_info_s* info, + picojson::object* le_device) { LoggerD("Entered"); le_device->insert( - std::make_pair(kDeviceAddress, - picojson::value(std::string(info->remote_address)))); + std::make_pair(kDeviceAddress, picojson::value(std::string(info->remote_address)))); - char *device_name = nullptr; + char* device_name = nullptr; int ret = BT_ERROR_NONE; - std::vector types = { - BT_ADAPTER_LE_PACKET_SCAN_RESPONSE, BT_ADAPTER_LE_PACKET_ADVERTISING }; + std::vector types = {BT_ADAPTER_LE_PACKET_SCAN_RESPONSE, + BT_ADAPTER_LE_PACKET_ADVERTISING}; bool found = false; for (size_t i = 0; i < types.size() && !found; ++i) { - ret = bt_adapter_le_get_scan_result_device_name(info, types[i], - &device_name); + ret = bt_adapter_le_get_scan_result_device_name(info, types[i], &device_name); if (BT_ERROR_NONE == ret) { found = true; } else { @@ -172,8 +155,7 @@ PlatformResult BluetoothLEDevice::ToJson( } if (found) { - le_device->insert( - std::make_pair(kDeviceName, picojson::value(std::string(device_name)))); + le_device->insert(std::make_pair(kDeviceName, picojson::value(std::string(device_name)))); g_free(device_name); } @@ -181,8 +163,7 @@ PlatformResult BluetoothLEDevice::ToJson( int power_level = 0; found = false; for (size_t i = 0; i < types.size() && !found; ++i) { - ret = bt_adapter_le_get_scan_result_tx_power_level(info, types[i], - &power_level); + ret = bt_adapter_le_get_scan_result_tx_power_level(info, types[i], &power_level); if (BT_ERROR_NONE == ret) { found = true; } else { @@ -192,8 +173,7 @@ PlatformResult BluetoothLEDevice::ToJson( if (found) { le_device->insert( - std::make_pair(kTxPowerLevel, - picojson::value(static_cast(power_level)))); + std::make_pair(kTxPowerLevel, picojson::value(static_cast(power_level)))); } int appearance = 0; @@ -209,16 +189,14 @@ PlatformResult BluetoothLEDevice::ToJson( if (found) { le_device->insert( - std::make_pair(kAppearance, - picojson::value(static_cast(appearance)))); + std::make_pair(kAppearance, picojson::value(static_cast(appearance)))); } - char **uuids = nullptr; + char** uuids = nullptr; int count = 0; found = false; for (size_t i = 0; i < types.size() && !found; ++i) { - ret = bt_adapter_le_get_scan_result_service_uuids(info, types[i], &uuids, - &count); + ret = bt_adapter_le_get_scan_result_service_uuids(info, types[i], &uuids, &count); if (BT_ERROR_NONE == ret) { found = true; } else { @@ -240,44 +218,40 @@ PlatformResult BluetoothLEDevice::ToJson( for (size_t i = 0; i < types.size() && !found; ++i) { ret = bt_adapter_le_get_scan_result_service_solicitation_uuids( - info, types[i], &service_solicitation_uuids, - &service_solicitation_uuids_count); + info, types[i], &service_solicitation_uuids, &service_solicitation_uuids_count); if (BT_ERROR_NONE == ret) { found = true; } else { - LoggerE("Failed to get solicitation UUID (%d). Packet type: %d", ret, - types[i]); + LoggerE("Failed to get solicitation UUID (%d). Packet type: %d", ret, types[i]); } } if (found) { - UUIDsToJson(service_solicitation_uuids, service_solicitation_uuids_count, - kSolicitationUuids, le_device); + UUIDsToJson(service_solicitation_uuids, service_solicitation_uuids_count, kSolicitationUuids, + le_device); for (int i = 0; i < service_solicitation_uuids_count; ++i) { g_free(service_solicitation_uuids[i]); } g_free(service_solicitation_uuids); } - bt_adapter_le_service_data_s *serviceDataList = nullptr; + bt_adapter_le_service_data_s* serviceDataList = nullptr; int service_data_list_count = 0; found = false; for (size_t i = 0; i < types.size() && !found; ++i) { - ret = bt_adapter_le_get_scan_result_service_data_list( - info, types[i], &serviceDataList, &service_data_list_count); + ret = bt_adapter_le_get_scan_result_service_data_list(info, types[i], &serviceDataList, + &service_data_list_count); if (BT_ERROR_NONE == ret) { found = true; } else { - LoggerE("Failed to get device service data (%d). Packet type: %d", ret, - types[i]); + LoggerE("Failed to get device service data (%d). Packet type: %d", ret, types[i]); } } if (found) { ServiceDataToJson(serviceDataList, service_data_list_count, le_device); - ret = bt_adapter_le_free_service_data_list(serviceDataList, - service_data_list_count); + ret = bt_adapter_le_free_service_data_list(serviceDataList, service_data_list_count); if (BT_ERROR_NONE != ret) { LoggerW("Failed to free service data list: %d", ret); } @@ -290,34 +264,28 @@ PlatformResult BluetoothLEDevice::ToJson( for (size_t i = 0; i < types.size() && !found; ++i) { ret = bt_adapter_le_get_scan_result_manufacturer_data( - info, types[i], &manufacturer_id, &manufacturer_data, - &manufacturer_data_count); + info, types[i], &manufacturer_id, &manufacturer_data, &manufacturer_data_count); if (BT_ERROR_NONE == ret) { found = true; } else { - LoggerE("Failed to get device manufacturer (%d). Packet type: %d", ret, - types[i]); + LoggerE("Failed to get device manufacturer (%d). Packet type: %d", ret, types[i]); } } if (found) { - ManufacturerToJson(manufacturer_id, manufacturer_data, - manufacturer_data_count, le_device); + ManufacturerToJson(manufacturer_id, manufacturer_data, manufacturer_data_count, le_device); g_free(manufacturer_data); } - le_device->insert( - std::make_pair(kRSSI, - picojson::value(static_cast(info->rssi)))); + le_device->insert(std::make_pair(kRSSI, picojson::value(static_cast(info->rssi)))); return PlatformResult(ErrorCode::NO_ERROR); } -void BluetoothLEDevice::Connect(const picojson::value& data, - picojson::object& out) { +void BluetoothLEDevice::Connect(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -328,25 +296,21 @@ void BluetoothLEDevice::Connect(const picojson::value& data, int ret = bt_device_is_profile_connected(address.c_str(), BT_PROFILE_GATT, &connected); if (BT_ERROR_NONE != ret) { instance_.AsyncResponse( - callback_handle, - LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", - ("bt_device_is_profile_connected error: %d (%s)", ret, get_error_message(ret)))); + callback_handle, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", + ("bt_device_is_profile_connected error: %d (%s)", ret, + get_error_message(ret)))); return; } if (connected) { - instance_.AsyncResponse( - callback_handle, - PlatformResult(ErrorCode::NO_ERROR)); + instance_.AsyncResponse(callback_handle, PlatformResult(ErrorCode::NO_ERROR)); } else { // not connected yet ret = bt_gatt_connect(address.c_str(), false); if (BT_ERROR_NONE != ret) { instance_.AsyncResponse( callback_handle, - LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to connect.", - ("bt_gatt_connect error: %d (%s)", ret, get_error_message(ret)))); + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to connect.", + ("bt_gatt_connect error: %d (%s)", ret, get_error_message(ret)))); return; } connecting_[address] = callback_handle; @@ -355,11 +319,10 @@ void BluetoothLEDevice::Connect(const picojson::value& data, ReportSuccess(out); } -void BluetoothLEDevice::Disconnect(const picojson::value& data, - picojson::object& out) { +void BluetoothLEDevice::Disconnect(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto callback_handle = util::GetAsyncCallbackHandle(data); const auto& args = util::GetArguments(data); @@ -371,18 +334,16 @@ void BluetoothLEDevice::Disconnect(const picojson::value& data, ret = bt_device_is_profile_connected(address.c_str(), BT_PROFILE_GATT, &connected); if (BT_ERROR_NONE != ret) { instance_.AsyncResponse( - callback_handle, - LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", - ("bt_device_is_profile_connected error: %d (%s)", ret, get_error_message(ret)))); + callback_handle, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", + ("bt_device_is_profile_connected error: %d (%s)", ret, + get_error_message(ret)))); return; } if (!connected) { LogAndReportError( PlatformResult(ErrorCode::INVALID_STATE_ERR, "Bluetooth low energy device is not connected"), - &out, - ("bt_device_is_profile_connected error: %d (%s)", ret, get_error_message(ret))); + &out, ("bt_device_is_profile_connected error: %d (%s)", ret, get_error_message(ret))); return; } @@ -390,9 +351,8 @@ void BluetoothLEDevice::Disconnect(const picojson::value& data, if (BT_ERROR_NONE != ret) { instance_.AsyncResponse( callback_handle, - LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", - ("bt_gatt_disconnect error: %d (%s)", ret, get_error_message(ret)))); + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to disconnect.", + ("bt_gatt_disconnect error: %d (%s)", ret, get_error_message(ret)))); return; } @@ -401,11 +361,10 @@ void BluetoothLEDevice::Disconnect(const picojson::value& data, ReportSuccess(out); } -void BluetoothLEDevice::GetService(const picojson::value& data, - picojson::object& out) { +void BluetoothLEDevice::GetService(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothAdmin, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, + &out); const auto& args = util::GetArguments(data); @@ -414,18 +373,16 @@ void BluetoothLEDevice::GetService(const picojson::value& data, auto it = is_connected_.find(address); if (it == is_connected_.end()) { - LogAndReportError( - PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Bluetooth low energy device is not connected"), - &out); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, + "Bluetooth low energy device is not connected"), + &out); return; } picojson::value response = picojson::value(picojson::object()); - picojson::object *data_obj = &response.get(); + picojson::object* data_obj = &response.get(); - PlatformResult result = service_.GetSpecifiedGATTService(address, uuid, - data_obj); + PlatformResult result = service_.GetSpecifiedGATTService(address, uuid, data_obj); if (result.IsError()) { LogAndReportError(result, &out); @@ -434,8 +391,8 @@ void BluetoothLEDevice::GetService(const picojson::value& data, } } -void BluetoothLEDevice::AddConnectStateChangeListener( - const picojson::value& data, picojson::object& out) { +void BluetoothLEDevice::AddConnectStateChangeListener(const picojson::value& data, + picojson::object& out) { LoggerD("Entered"); is_listener_set_ = true; @@ -443,8 +400,8 @@ void BluetoothLEDevice::AddConnectStateChangeListener( ReportSuccess(out); } -void BluetoothLEDevice::RemoveConnectStateChangeListener( - const picojson::value& data, picojson::object& out) { +void BluetoothLEDevice::RemoveConnectStateChangeListener(const picojson::value& data, + picojson::object& out) { LoggerD("Entered"); is_listener_set_ = false; @@ -452,15 +409,14 @@ void BluetoothLEDevice::RemoveConnectStateChangeListener( ReportSuccess(out); } -void BluetoothLEDevice::GetServiceAllUuids(const picojson::value& data, - picojson::object& out) { +void BluetoothLEDevice::GetServiceAllUuids(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); const auto& args = util::GetArguments(data); const auto& address = common::FromJson(args, "address"); picojson::value response = picojson::value(picojson::array()); - picojson::array *data_obj = &response.get(); + picojson::array* data_obj = &response.get(); PlatformResult result = service_.GetServiceAllUuids(address, data_obj); @@ -471,11 +427,10 @@ void BluetoothLEDevice::GetServiceAllUuids(const picojson::value& data, } } -void BluetoothLEDevice::GattConnectionState(int result, bool connected, - const char* remote_address, +void BluetoothLEDevice::GattConnectionState(int result, bool connected, const char* remote_address, void* user_data) { LoggerD("Entered: %s connected: %d", remote_address, connected); - auto le_device = static_cast(user_data); + auto le_device = static_cast(user_data); if (!le_device) { LoggerE("user_data is NULL"); @@ -491,7 +446,6 @@ void BluetoothLEDevice::GattConnectionState(int result, bool connected, } if (le_device->is_listener_set_) { - picojson::value value = picojson::value(picojson::object()); picojson::object* data_obj = &value.get(); if (connected) { @@ -499,12 +453,10 @@ void BluetoothLEDevice::GattConnectionState(int result, bool connected, data_obj->insert(std::make_pair(kAction, picojson::value(kOnConnected))); } else { LoggerD("OnDisconnected"); - data_obj->insert( - std::make_pair(kAction, picojson::value(kOnDisconnected))); + data_obj->insert(std::make_pair(kAction, picojson::value(kOnDisconnected))); } - data_obj->insert( - std::make_pair(kDeviceAddress, picojson::value(remote_address))); + data_obj->insert(std::make_pair(kDeviceAddress, picojson::value(remote_address))); le_device->instance_.FireEvent(kConnectChangeEvent, value); } @@ -518,8 +470,8 @@ void BluetoothLEDevice::GattConnectionState(int result, bool connected, PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); if (BT_ERROR_NONE != result) { ret = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get connection state", - ("GattConnectionState error: %d (%s)", result, get_error_message(result))); + ErrorCode::UNKNOWN_ERR, "Failed to get connection state", + ("GattConnectionState error: %d (%s)", result, get_error_message(result))); } le_device->instance_.AsyncResponse(it->second, ret); diff --git a/src/bluetooth/bluetooth_le_device.h b/src/bluetooth/bluetooth_le_device.h old mode 100755 new mode 100644 index ed122f1..2715bcf --- a/src/bluetooth/bluetooth_le_device.h +++ b/src/bluetooth/bluetooth_le_device.h @@ -42,20 +42,17 @@ class BluetoothLEDevice { void GetService(const picojson::value& data, picojson::object& out); - void AddConnectStateChangeListener(const picojson::value& data, - picojson::object& out); - void RemoveConnectStateChangeListener(const picojson::value& data, - picojson::object& out); + void AddConnectStateChangeListener(const picojson::value& data, picojson::object& out); + void RemoveConnectStateChangeListener(const picojson::value& data, picojson::object& out); void GetServiceAllUuids(const picojson::value& data, picojson::object& out); - static common::PlatformResult ToJson( - bt_adapter_le_device_scan_result_info_s* info, - picojson::object* le_device); + static common::PlatformResult ToJson(bt_adapter_le_device_scan_result_info_s* info, + picojson::object* le_device); private: - static void GattConnectionState(int result, bool connected, - const char *remote_address, void *user_data); + static void GattConnectionState(int result, bool connected, const char* remote_address, + void* user_data); BluetoothInstance& instance_; BluetoothGATTService& service_; @@ -67,4 +64,4 @@ class BluetoothLEDevice { } // namespace bluetooth } // namespace extension -#endif // BLUETOOTH_BLUETOOTH_LE_DEVICE_H_ +#endif // BLUETOOTH_BLUETOOTH_LE_DEVICE_H_ diff --git a/src/bluetooth/bluetooth_privilege.cc b/src/bluetooth/bluetooth_privilege.cc index 78a1f90..847ef3c 100644 --- a/src/bluetooth/bluetooth_privilege.cc +++ b/src/bluetooth/bluetooth_privilege.cc @@ -26,7 +26,7 @@ const std::string kBluetoothGap = "http://tizen.org/privilege/bluetooth.gap"; const std::string kBluetoothSpp = "http://tizen.org/privilege/bluetooth.spp"; const std::string kBluetoothHealth = "http://tizen.org/privilege/bluetooth.health"; const std::string kBluetooth = "http://tizen.org/privilege/bluetooth"; -} // namespace Privilege +} // namespace Privilege -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_privilege.h b/src/bluetooth/bluetooth_privilege.h index 1c0ccff..b366fd2 100644 --- a/src/bluetooth/bluetooth_privilege.h +++ b/src/bluetooth/bluetooth_privilege.h @@ -31,9 +31,9 @@ extern const std::string kBluetoothSpp; extern const std::string kBluetoothHealth; extern const std::string kBluetooth; -} // namespace Privilege +} // namespace Privilege -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_PRIVILEGE_H_ +#endif // BLUETOOTH_BLUETOOTH_PRIVILEGE_H_ diff --git a/src/bluetooth/bluetooth_service_handler.cc b/src/bluetooth/bluetooth_service_handler.cc old mode 100755 new mode 100644 index e79c66a..d249f89 --- a/src/bluetooth/bluetooth_service_handler.cc +++ b/src/bluetooth/bluetooth_service_handler.cc @@ -30,23 +30,21 @@ namespace bluetooth { using namespace common; -BluetoothServiceHandler::BluetoothServiceHandler(BluetoothAdapter& adapter) - : adapter_(adapter) { +BluetoothServiceHandler::BluetoothServiceHandler(BluetoothAdapter& adapter) : adapter_(adapter) { } void BluetoothServiceHandler::Unregister(const picojson::value& data, picojson::object& out) { LoggerD("Entered"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto& args = util::GetArguments(data); - adapter_.UnregisterUUID(FromJson(args, "uuid"), - util::GetAsyncCallbackHandle(data)); + adapter_.UnregisterUUID(FromJson(args, "uuid"), util::GetAsyncCallbackHandle(data)); tools::ReportSuccess(out); } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_service_handler.h b/src/bluetooth/bluetooth_service_handler.h old mode 100755 new mode 100644 index 9feca9d..c4fcdeb --- a/src/bluetooth/bluetooth_service_handler.h +++ b/src/bluetooth/bluetooth_service_handler.h @@ -49,7 +49,7 @@ class BluetoothServiceHandler { BluetoothAdapter& adapter_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_SERVICE_HANDLER_H_ +#endif // BLUETOOTH_BLUETOOTH_SERVICE_HANDLER_H_ diff --git a/src/bluetooth/bluetooth_socket.cc b/src/bluetooth/bluetooth_socket.cc old mode 100755 new mode 100644 index dad2a96..3d4a8c1 --- a/src/bluetooth/bluetooth_socket.cc +++ b/src/bluetooth/bluetooth_socket.cc @@ -44,15 +44,14 @@ const int kBluetoothError = -1; using namespace common; using namespace common::tools; -BluetoothSocket::BluetoothSocket(BluetoothAdapter& adapter) - : adapter_(adapter) { +BluetoothSocket::BluetoothSocket(BluetoothAdapter& adapter) : adapter_(adapter) { } void BluetoothSocket::WriteData(const picojson::value& data, picojson::object& out) { LoggerD("Enter"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto& args = util::GetArguments(data); @@ -67,9 +66,8 @@ void BluetoothSocket::WriteData(const picojson::value& data, picojson::object& o } if (kBluetoothError == bt_socket_send_data(socket, data_ptr.get(), data_size)) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, - ("bt_socket_send_data() failed")); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, + ("bt_socket_send_data() failed")); return; } @@ -79,8 +77,8 @@ void BluetoothSocket::WriteData(const picojson::value& data, picojson::object& o void BluetoothSocket::ReadData(const picojson::value& data, picojson::object& out) { LoggerD("Enter"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto& args = util::GetArguments(data); @@ -102,17 +100,16 @@ void BluetoothSocket::ReadData(const picojson::value& data, picojson::object& ou void BluetoothSocket::Close(const picojson::value& data, picojson::object& out) { LoggerD("Enter"); - CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, - Privilege::kBluetoothSpp, &out); + CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, + &out); const auto& args = util::GetArguments(data); int socket = common::stol(FromJson(args, "id")); if (BT_ERROR_NONE != bt_socket_disconnect_rfcomm(socket)) { - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, - ("bt_socket_disconnect_rfcomm() failed")); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown error"), &out, + ("bt_socket_disconnect_rfcomm() failed")); return; } @@ -125,19 +122,19 @@ picojson::value BluetoothSocket::ToJson(bt_socket_connection_s* connection) { picojson::value ret = picojson::value(picojson::object()); auto& ret_obj = ret.get(); - ret_obj.insert(std::make_pair(kBluetoothSocketId, - picojson::value(std::to_string(connection->socket_fd)))); - ret_obj.insert(std::make_pair(kBluetoothSocketUuid, - picojson::value(connection->service_uuid))); - ret_obj.insert(std::make_pair(kBluetoothSocketState, - picojson::value(kBluetoothSocketStateOpen))); + ret_obj.insert( + std::make_pair(kBluetoothSocketId, picojson::value(std::to_string(connection->socket_fd)))); + ret_obj.insert(std::make_pair(kBluetoothSocketUuid, picojson::value(connection->service_uuid))); + ret_obj.insert(std::make_pair(kBluetoothSocketState, picojson::value(kBluetoothSocketStateOpen))); bt_device_info_s* device_info = nullptr; - if (BT_ERROR_NONE == bt_adapter_get_bonded_device_info(connection->remote_address, &device_info) && + if (BT_ERROR_NONE == + bt_adapter_get_bonded_device_info(connection->remote_address, &device_info) && nullptr != device_info) { - picojson::value& device = ret_obj.insert(std::make_pair( - kBluetoothSocketPeer, picojson::value(picojson::object()))).first->second; + picojson::value& device = + ret_obj.insert(std::make_pair(kBluetoothSocketPeer, picojson::value(picojson::object()))) + .first->second; BluetoothDevice::ToJson(device_info, &device.get()); bt_adapter_free_device_info(device_info); @@ -148,5 +145,5 @@ picojson::value BluetoothSocket::ToJson(bt_socket_connection_s* connection) { return ret; } -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension diff --git a/src/bluetooth/bluetooth_socket.h b/src/bluetooth/bluetooth_socket.h old mode 100755 new mode 100644 index 64321b8..4c74f66 --- a/src/bluetooth/bluetooth_socket.h +++ b/src/bluetooth/bluetooth_socket.h @@ -72,7 +72,7 @@ class BluetoothSocket { BluetoothAdapter& adapter_; }; -} // namespace bluetooth -} // namespace extension +} // namespace bluetooth +} // namespace extension -#endif // BLUETOOTH_BLUETOOTH_SOCKET_H__ +#endif // BLUETOOTH_BLUETOOTH_SOCKET_H__ diff --git a/src/bluetooth/bluetooth_util.cc b/src/bluetooth/bluetooth_util.cc old mode 100755 new mode 100644 index a449b39..ca4a813 --- a/src/bluetooth/bluetooth_util.cc +++ b/src/bluetooth/bluetooth_util.cc @@ -26,7 +26,7 @@ using common::PlatformResult; namespace { const char* JSON_CALLBACK_ID = "callbackId"; -} // namespace +} // namespace double GetAsyncCallbackHandle(const picojson::value& data) { return data.get(JSON_CALLBACK_ID).get(); @@ -36,8 +36,7 @@ const picojson::object& GetArguments(const picojson::value& data) { return data.get(); } -PlatformResult GetBluetoothError(int error_code, - const std::string& hint) { +PlatformResult GetBluetoothError(int error_code, const std::string& hint) { common::ErrorCode error = ErrorCode::UNKNOWN_ERR; switch (error_code) { @@ -56,8 +55,8 @@ PlatformResult GetBluetoothError(int error_code, break; case BT_ERROR_QUOTA_EXCEEDED: - error = ErrorCode::QUOTA_EXCEEDED_ERR; - break; + error = ErrorCode::QUOTA_EXCEEDED_ERR; + break; default: error = ErrorCode::UNKNOWN_ERR; @@ -66,9 +65,8 @@ PlatformResult GetBluetoothError(int error_code, std::string message = hint + " : " + GetBluetoothErrorMessage(error_code); - return LogAndCreateResult( - error, message.c_str(), - ("%s %d (%s)", message.c_str(), error_code, get_error_message(error_code))); + return LogAndCreateResult(error, message.c_str(), ("%s %d (%s)", message.c_str(), error_code, + get_error_message(error_code))); } std::string GetBluetoothErrorMessage(int error_code) { @@ -122,6 +120,6 @@ std::string GetBluetoothErrorMessage(int error_code) { } } -} // util -} // bluetooth -} // extension +} // util +} // bluetooth +} // extension diff --git a/src/bluetooth/bluetooth_util.h b/src/bluetooth/bluetooth_util.h index 2673711..69f5d46 100644 --- a/src/bluetooth/bluetooth_util.h +++ b/src/bluetooth/bluetooth_util.h @@ -34,8 +34,8 @@ const picojson::object& GetArguments(const picojson::value& data); common::PlatformResult GetBluetoothError(int error_code, const std::string& hint); std::string GetBluetoothErrorMessage(int error_code); -} // util -} // bluetooth -} // extension +} // util +} // bluetooth +} // extension -#endif // BLUETOOTH_BLUETOOTH_UTIL_H_ +#endif // BLUETOOTH_BLUETOOTH_UTIL_H_ diff --git a/src/bookmark/bookmark_extension.cc b/src/bookmark/bookmark_extension.cc old mode 100755 new mode 100644 index 8504f44..6f24178 --- a/src/bookmark/bookmark_extension.cc +++ b/src/bookmark/bookmark_extension.cc @@ -19,9 +19,9 @@ #include "common/logger.h" namespace { - const char kBookmark[] = "tizen.bookmark"; - const char kBookmarkItem[] = "tizen.BookmarkItem"; - const char kBookmarkFolder[] = "tizen.BookmarkFolder"; +const char kBookmark[] = "tizen.bookmark"; +const char kBookmarkItem[] = "tizen.BookmarkItem"; +const char kBookmarkFolder[] = "tizen.BookmarkFolder"; } // This will be generated from bookmark_api.js. @@ -35,15 +35,11 @@ BookmarkExtension::BookmarkExtension() { SetExtensionName(kBookmark); SetJavaScriptAPI(kSource_bookmark_api); - const char* entry_points[] = { - kBookmarkItem, - kBookmarkFolder, - NULL - }; + const char* entry_points[] = {kBookmarkItem, kBookmarkFolder, NULL}; SetExtraJSEntryPoints(entry_points); if (bp_bookmark_adaptor_initialize()) { - LOGGER(ERROR) << "Fail: Bookmark not supported"; + LOGGER(ERROR) << "Fail: Bookmark not supported"; } } diff --git a/src/bookmark/bookmark_instance.cc b/src/bookmark/bookmark_instance.cc old mode 100755 new mode 100644 index 7f8e4bd..e600e55 --- a/src/bookmark/bookmark_instance.cc +++ b/src/bookmark/bookmark_instance.cc @@ -19,9 +19,9 @@ #include #include -#include "common/platform_exception.h" #include "common/converter.h" #include "common/logger.h" +#include "common/platform_exception.h" #include "common/tools.h" using common::ErrorCode; @@ -31,14 +31,14 @@ namespace extension { namespace bookmark { namespace { - const char kId[] = "id"; - const char kTitle[] = "title"; - const char kType[] = "type"; - const char kParentId[] = "parentId"; - const char kUrl[] = "url"; - - const std::string kPrivilegeBookmarkRead = "http://tizen.org/privilege/bookmark.read"; - const std::string kPrivilegeBookmarkWrite = "http://tizen.org/privilege/bookmark.write"; +const char kId[] = "id"; +const char kTitle[] = "title"; +const char kType[] = "type"; +const char kParentId[] = "parentId"; +const char kUrl[] = "url"; + +const std::string kPrivilegeBookmarkRead = "http://tizen.org/privilege/bookmark.read"; +const std::string kPrivilegeBookmarkWrite = "http://tizen.org/privilege/bookmark.write"; } // namespace BookmarkInstance::BookmarkInstance() { @@ -46,8 +46,7 @@ BookmarkInstance::BookmarkInstance() { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&BookmarkInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&BookmarkInstance::x, this, _1, _2)); REGISTER_SYNC("Bookmark_get", BookmarkGet); REGISTER_SYNC("Bookmark_add", BookmarkAdd); REGISTER_SYNC("Bookmark_remove", BookmarkRemove); @@ -60,9 +59,7 @@ BookmarkInstance::~BookmarkInstance() { LoggerD("Enter"); } -bool BookmarkInstance::bookmark_foreach( - Context& ctx, bp_bookmark_info_fmt& info) { - +bool BookmarkInstance::bookmark_foreach(Context& ctx, bp_bookmark_info_fmt& info) { LoggerD("Enter"); int ids_count = 0; int* ids = NULL; @@ -71,14 +68,13 @@ bool BookmarkInstance::bookmark_foreach( BP_BOOKMARK_O_DATE_CREATED, 0) < 0) return false; - if (ids_count > 0) { for (int i = 0; i < ids_count; i++) { bp_bookmark_adaptor_get_easy_all(ids[i], &info); item.id = ids[i]; item.bookmark_info = info; if ((ctx.shouldGetItems && item.bookmark_info.parent != ctx.id) || - (!ctx.shouldGetItems && item.id != ctx.id)) + (!ctx.shouldGetItems && item.id != ctx.id)) continue; ctx.folders.push_back(item); } @@ -87,29 +83,26 @@ bool BookmarkInstance::bookmark_foreach( return true; } -PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, - bool* exists) { +PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, bool* exists) { LoggerD("Enter"); int ids_count = 0; int* ids = nullptr; char* compare_url = nullptr; - int ntv_ret = bp_bookmark_adaptor_get_ids_p( - &ids, // ids - &ids_count, // count - -1, //limit - 0, // offset - -1, //parent - -1, //type - -1, // is_operator - -1, // is_editable - BP_BOOKMARK_O_DATE_CREATED, // order_offset - 0 // ordering ASC - ); + int ntv_ret = bp_bookmark_adaptor_get_ids_p(&ids, // ids + &ids_count, // count + -1, // limit + 0, // offset + -1, // parent + -1, // type + -1, // is_operator + -1, // is_editable + BP_BOOKMARK_O_DATE_CREATED, // order_offset + 0); // ordering ASC if (ntv_ret < 0) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to obtain bookmarks", - ("bp_bookmark_adaptor_get_ids_p error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to obtain bookmarks", + ("bp_bookmark_adaptor_get_ids_p error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } PlatformResult result{ErrorCode::NO_ERROR}; @@ -118,8 +111,8 @@ PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, ntv_ret = bp_bookmark_adaptor_get_url(ids[i], &compare_url); if (ntv_ret < 0) { result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to obtain URL", - ("bp_bookmark_adaptor_get_url error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to obtain URL", + ("bp_bookmark_adaptor_get_url error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } else { url_found = (0 == strcmp(url, compare_url)); free(compare_url); @@ -136,48 +129,41 @@ PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, return result; } -PlatformResult BookmarkInstance::BookmarkTitleExistsInParent(const char* title, - int parent, +PlatformResult BookmarkInstance::BookmarkTitleExistsInParent(const char* title, int parent, bool* exists) { - LoggerD("Enter"); int ids_count = 0; int compare_parent = -1; int* ids = nullptr; char* compare_title = nullptr; - int ntv_ret = bp_bookmark_adaptor_get_ids_p( - &ids, // ids - &ids_count, // count - -1, //limit - 0, // offset - -1, //parent - -1, //type - -1, // is_operator - -1, // is_editable - BP_BOOKMARK_O_DATE_CREATED, // order_offset - 0 // ordering ASC - ); + int ntv_ret = bp_bookmark_adaptor_get_ids_p(&ids, // ids + &ids_count, // count + -1, // limit + 0, // offset + -1, // parent + -1, // type + -1, // is_operator + -1, // is_editable + BP_BOOKMARK_O_DATE_CREATED, // order_offset + 0); // ordering ASC if (ntv_ret < 0) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to obtain bookmarks", - ("bp_bookmark_adaptor_get_ids_p error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to obtain bookmarks", + ("bp_bookmark_adaptor_get_ids_p error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } PlatformResult result{ErrorCode::NO_ERROR}; bool title_found = false; for (int i = 0; (i < ids_count) && result && !title_found; ++i) { if ((ntv_ret = bp_bookmark_adaptor_get_parent_id(ids[i], &compare_parent)) < 0) { - result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to obtain parent ID", - ("bp_bookmark_adaptor_get_parent_id error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to obtain parent ID", + ("bp_bookmark_adaptor_get_parent_id error: %d (%s)", ntv_ret, + get_error_message(ntv_ret))); } else if ((ntv_ret = bp_bookmark_adaptor_get_title(ids[i], &compare_title)) < 0) { result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to obtain title", - ("bp_bookmark_adaptor_get_title error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to obtain title", + ("bp_bookmark_adaptor_get_title error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } else { title_found = (parent == compare_parent) && (0 == strcmp(title, compare_title)); free(compare_title); @@ -195,8 +181,7 @@ PlatformResult BookmarkInstance::BookmarkTitleExistsInParent(const char* title, return result; } -void BookmarkInstance::BookmarkGet( - const picojson::value& arg, picojson::object& o) { +void BookmarkInstance::BookmarkGet(const picojson::value& arg, picojson::object& o) { CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkRead, &o); LoggerD("Enter"); @@ -205,7 +190,7 @@ void BookmarkInstance::BookmarkGet( picojson::value::array arr; ctx.shouldGetItems = arg.get("shouldGetItems").get(); - ctx.id = arg.get(kId).get(); + ctx.id = arg.get(kId).get(); if (!bookmark_foreach(ctx, info)) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get bookmark"), &o); @@ -213,29 +198,26 @@ void BookmarkInstance::BookmarkGet( } std::vector::iterator it; - for (it = ctx.folders.begin(); it!= ctx.folders.end(); ++it) { + for (it = ctx.folders.begin(); it != ctx.folders.end(); ++it) { picojson::object obj; BookmarkObject entry = *it; obj[kTitle] = picojson::value(entry.bookmark_info.title); obj[kId] = picojson::value(std::to_string(entry.id)); obj[kType] = picojson::value(std::to_string(entry.bookmark_info.type)); - obj[kParentId] = picojson::value(std::to_string( - entry.bookmark_info.parent)); - if (!entry.bookmark_info.type) - obj[kUrl] = picojson::value(entry.bookmark_info.url); + obj[kParentId] = picojson::value(std::to_string(entry.bookmark_info.parent)); + if (!entry.bookmark_info.type) obj[kUrl] = picojson::value(entry.bookmark_info.url); arr.push_back(picojson::value(obj)); } ReportSuccess(picojson::value(arr), o); } -void BookmarkInstance::BookmarkAdd( - const picojson::value& arg, picojson::object& o) { +void BookmarkInstance::BookmarkAdd(const picojson::value& arg, picojson::object& o) { CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); LoggerD("Enter"); - int saved_id =-1; + int saved_id = -1; const auto& title = arg.get(kTitle).get(); const int parent = static_cast(arg.get(kParentId).get()); @@ -249,7 +231,8 @@ void BookmarkInstance::BookmarkAdd( LogAndReportError(result, &o); return; } else if (exists) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Bookmark already exists"), &o); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Bookmark already exists"), + &o); return; } } @@ -261,7 +244,8 @@ void BookmarkInstance::BookmarkAdd( LogAndReportError(result, &o); return; } else if (exists) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Bookmark already exists"), &o); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Bookmark already exists"), + &o); return; } } @@ -304,13 +288,11 @@ void BookmarkInstance::BookmarkAdd( ReportSuccess(picojson::value(std::to_string(saved_id)), o); } -void BookmarkInstance::BookmarkRemove( - const picojson::value& arg, picojson::object& o) { +void BookmarkInstance::BookmarkRemove(const picojson::value& arg, picojson::object& o) { CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); LoggerD("Enter"); - int id = common::stol( - common::FromJson(arg.get(), kId)); + int id = common::stol(common::FromJson(arg.get(), kId)); int ntv_ret = bp_bookmark_adaptor_delete(id); if (ntv_ret < 0) { @@ -320,8 +302,7 @@ void BookmarkInstance::BookmarkRemove( ReportSuccess(o); } -void BookmarkInstance::BookmarkRemoveAll( - const picojson::value& msg, picojson::object& o) { +void BookmarkInstance::BookmarkRemoveAll(const picojson::value& msg, picojson::object& o) { CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); LoggerD("Enter"); @@ -333,9 +314,7 @@ void BookmarkInstance::BookmarkRemoveAll( ReportSuccess(o); } -void BookmarkInstance::BookmarkGetRootId( - const picojson::value& msg, picojson::object& o) { - +void BookmarkInstance::BookmarkGetRootId(const picojson::value& msg, picojson::object& o) { LoggerD("Enter"); int rootId(0); int ntv_ret = bp_bookmark_adaptor_get_root(&rootId); diff --git a/src/bookmark/bookmark_instance.h b/src/bookmark/bookmark_instance.h old mode 100755 new mode 100644 index 74de11b..f4ee2ad --- a/src/bookmark/bookmark_instance.h +++ b/src/bookmark/bookmark_instance.h @@ -46,8 +46,7 @@ class BookmarkInstance : public common::ParsedInstance { private: bool bookmark_foreach(Context& ctx, bp_bookmark_info_fmt& info); common::PlatformResult BookmarkUrlExists(const char* url, bool* exists); - common::PlatformResult BookmarkTitleExistsInParent(const char* title, - int parent, bool* exists); + common::PlatformResult BookmarkTitleExistsInParent(const char* title, int parent, bool* exists); void BookmarkGet(const picojson::value& arg, picojson::object& o); void BookmarkAdd(const picojson::value& arg, picojson::object& o); void BookmarkRemove(const picojson::value& arg, picojson::object& o); diff --git a/src/calendar/calendar.cc b/src/calendar/calendar.cc old mode 100755 new mode 100644 index 1d2dbfe..0995fdb --- a/src/calendar/calendar.cc +++ b/src/calendar/calendar.cc @@ -16,21 +16,21 @@ #include "calendar.h" -#include "common/platform_exception.h" -#include "common/logger.h" -#include "common/converter.h" -#include "common/task-queue.h" -#include "common/filter-utils.h" +#include "calendar/calendar_instance.h" +#include "calendar/calendar_item.h" #include "calendar/calendar_manager.h" #include "calendar/calendar_privilege.h" -#include "calendar/calendar_item.h" -#include "calendar/calendar_instance.h" +#include "common/converter.h" +#include "common/filter-utils.h" +#include "common/logger.h" +#include "common/platform_exception.h" +#include "common/task-queue.h" namespace extension { namespace calendar { -typedef std::unique_ptr::type, - void (*)(calendar_filter_h)> CalendarFilterPtr; +typedef std::unique_ptr::type, void (*)(calendar_filter_h)> + CalendarFilterPtr; void CalendarFilterDeleter(calendar_filter_h calendar_filter) { if (CALENDAR_ERROR_NONE != calendar_filter_destroy(calendar_filter)) { @@ -40,25 +40,21 @@ void CalendarFilterDeleter(calendar_filter_h calendar_filter) { using namespace common; -Calendar::Calendar(CalendarInstance& instance) - : current_db_version_(0), - instance_(instance) { +Calendar::Calendar(CalendarInstance& instance) : current_db_version_(0), instance_(instance) { } Calendar::~Calendar() { int ret; if (listeners_registered_.find("EVENT") != listeners_registered_.end()) { - ret = calendar_db_remove_changed_cb(_calendar_event._uri, ChangeCallback, - this); + ret = calendar_db_remove_changed_cb(_calendar_event._uri, ChangeCallback, this); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Remove calendar event change callback error"); } } if (listeners_registered_.find("TASK") != listeners_registered_.end()) { - ret = calendar_db_remove_changed_cb(_calendar_todo._uri, ChangeCallback, - this); + ret = calendar_db_remove_changed_cb(_calendar_todo._uri, ChangeCallback, this); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Remove calendar todo change callback error"); } @@ -73,16 +69,13 @@ PlatformResult Calendar::Get(const picojson::object& args, picojson::object& out int calendar_id = common::stol(FromJson(args, "calendarId")); calendar_record_h handle = nullptr; - PlatformResult status = - CalendarRecord::GetById(calendar_id, _calendar_book._uri, &handle); + PlatformResult status = CalendarRecord::GetById(calendar_id, _calendar_book._uri, &handle); if (status.IsError()) return status; - CalendarRecordPtr calendar_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr calendar_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); int type; - status = CalendarRecord::GetInt(calendar_ptr.get(), _calendar_book.store_type, - &type); + status = CalendarRecord::GetInt(calendar_ptr.get(), _calendar_book.store_type, &type); if (status.IsError()) return status; int id; @@ -100,8 +93,7 @@ PlatformResult Calendar::Get(const picojson::object& args, picojson::object& out status = CalendarRecord::GetById(id, uri.c_str(), &handle_uri); if (status.IsError()) return status; - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle_uri, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle_uri, CalendarRecord::Deleter); status = CalendarItem::ToJson(type, record_ptr.get(), &out); if (status.IsError()) return status; @@ -109,8 +101,7 @@ PlatformResult Calendar::Get(const picojson::object& args, picojson::object& out return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::Add(const picojson::object& args, - picojson::object& out) { +PlatformResult Calendar::Add(const picojson::object& args, picojson::object& out) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -122,8 +113,7 @@ PlatformResult Calendar::Add(const picojson::object& args, PlatformResult status = CalendarItem::Create(type, &handle); if (status.IsError()) return status; - CalendarRecordPtr item_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr item_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); status = CalendarItem::FromJson(type, item_ptr.get(), item); if (status.IsError()) return status; @@ -136,8 +126,8 @@ PlatformResult Calendar::Add(const picojson::object& args, if (type == CALENDAR_BOOK_TYPE_EVENT) { std::string rid; - PlatformResult status = CalendarRecord::GetString( - item_ptr.get(), _calendar_event.recurrence_id, &rid); + PlatformResult status = + CalendarRecord::GetString(item_ptr.get(), _calendar_event.recurrence_id, &rid); if (status.IsError()) return status; if (!rid.empty()) { @@ -150,8 +140,7 @@ PlatformResult Calendar::Add(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::AddBatch(const picojson::object& args, - picojson::array& array) { +PlatformResult Calendar::AddBatch(const picojson::object& args, picojson::array& array) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -169,9 +158,8 @@ PlatformResult Calendar::AddBatch(const picojson::object& args, calendar_list_h list = NULL; int ret = calendar_list_create(&list); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not create list for batch operation", - ("calendar_list_create error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create list for batch operation", + ("calendar_list_create error: %d (%s)", ret, get_error_message(ret))); } CalendarListPtr list_ptr = CalendarListPtr(list, CalendarRecord::ListDeleter); @@ -181,18 +169,16 @@ PlatformResult Calendar::AddBatch(const picojson::object& args, ret = calendar_record_create(view_uri.c_str(), &record); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't create platform record", - ("calendar_record_create error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't create platform record", + ("calendar_record_create error: %d (%s)", ret, get_error_message(ret))); } - PlatformResult status = - CalendarItem::FromJson(type, record, item.get()); + PlatformResult status = CalendarItem::FromJson(type, record, item.get()); if (status.IsError()) return status; ret = calendar_list_add(list_ptr.get(), record); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Could not add record to list", - ("calendar_list_add error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Could not add record to list", + ("calendar_list_add error: %d (%s)", ret, get_error_message(ret))); } } @@ -202,12 +188,12 @@ PlatformResult Calendar::AddBatch(const picojson::object& args, if (CALENDAR_ERROR_NONE != ret) { if (CALENDAR_ERROR_INVALID_PARAMETER == ret) { return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Parameter is invalid", - ("calendar_db_insert_records error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Parameter is invalid", + ("calendar_db_insert_records error: %d (%s)", ret, get_error_message(ret))); } else { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "CALENDAR_ERROR_DB_FAILED occurred", - ("calendar_db_insert_records error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "CALENDAR_ERROR_DB_FAILED occurred", + ("calendar_db_insert_records error: %d (%s)", ret, get_error_message(ret))); } } @@ -228,8 +214,7 @@ PlatformResult Calendar::AddBatch(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::Update(const picojson::object& args, - picojson::object& /*out*/) { +PlatformResult Calendar::Update(const picojson::object& args, picojson::object& /*out*/) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -257,45 +242,40 @@ PlatformResult Calendar::Update(const picojson::object& args, status = CalendarRecord::GetById(id, value_str.c_str(), &handle); if (status.IsError()) return status; - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); status = CalendarItem::FromJson(type, record_ptr.get(), item); if (status.IsError()) return status; int ret; - if (type == CALENDAR_BOOK_TYPE_TODO || update_all || - common::IsNull(item, "recurrenceRule")) { + if (type == CALENDAR_BOOK_TYPE_TODO || update_all || common::IsNull(item, "recurrenceRule")) { ret = calendar_db_update_record(record_ptr.get()); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't update calendar item", - ("calendar_db_update_record error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't update calendar item", + ("calendar_db_update_record error: %d (%s)", ret, get_error_message(ret))); } } else { // first update the parent event - std::string exdate = - CalendarItem::ExceptionsFromJson(common::FromJson( - item, "recurrenceRule", "exceptions")); - if (!common::IsNull(common::FromJson(item, "id"), - "rid")) { + std::string exdate = CalendarItem::ExceptionsFromJson( + common::FromJson(item, "recurrenceRule", "exceptions")); + if (!common::IsNull(common::FromJson(item, "id"), "rid")) { exdate.append(common::FromJson(item, "id", "rid")); } - PlatformResult status = CalendarRecord::SetString( - record_ptr.get(), _calendar_event.exdate, exdate); + PlatformResult status = + CalendarRecord::SetString(record_ptr.get(), _calendar_event.exdate, exdate); if (status.IsError()) return status; // don't set the recurrence id for the parent event - status = CalendarRecord::SetString(record_ptr.get(), - _calendar_event.recurrence_id, ""); + status = CalendarRecord::SetString(record_ptr.get(), _calendar_event.recurrence_id, ""); if (status.IsError()) return status; ret = calendar_db_update_record(record_ptr.get()); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't update calendar item", - ("calendar_db_update_record error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't update calendar item", + ("calendar_db_update_record error: %d (%s)", ret, get_error_message(ret))); } // now add the detached child event @@ -303,8 +283,7 @@ PlatformResult Calendar::Update(const picojson::object& args, status = CalendarItem::Create(type, &handle_new); if (status.IsError()) return status; - CalendarRecordPtr item_ptr = - CalendarRecordPtr(handle_new, CalendarRecord::Deleter); + CalendarRecordPtr item_ptr = CalendarRecordPtr(handle_new, CalendarRecord::Deleter); status = CalendarItem::FromJson(type, item_ptr.get(), item); if (status.IsError()) return status; @@ -317,8 +296,7 @@ PlatformResult Calendar::Update(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::UpdateBatch(const picojson::object& args, - picojson::array& array) { +PlatformResult Calendar::UpdateBatch(const picojson::object& args, picojson::array& array) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -341,9 +319,8 @@ PlatformResult Calendar::UpdateBatch(const picojson::object& args, calendar_list_h list = NULL; int ret = calendar_list_create(&list); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not create list for batch operation", - ("calendar_list_create error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not create list for batch operation", + ("calendar_list_create error: %d (%s)", ret, get_error_message(ret))); } CalendarListPtr list_ptr = CalendarListPtr(list, CalendarRecord::ListDeleter); @@ -361,18 +338,16 @@ PlatformResult Calendar::UpdateBatch(const picojson::object& args, ret = calendar_db_get_record(view_uri.c_str(), id, &record); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't get platform record", - ("calendar_db_get_record error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't get platform record", + ("calendar_db_get_record error: %d (%s)", ret, get_error_message(ret))); } - PlatformResult status = - CalendarItem::FromJson(type, record, item.get()); + PlatformResult status = CalendarItem::FromJson(type, record, item.get()); if (status.IsError()) return status; ret = calendar_list_add(list_ptr.get(), record); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Could not add record to list", - ("calendar_list_add error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Could not add record to list", + ("calendar_list_add error: %d (%s)", ret, get_error_message(ret))); } } @@ -380,8 +355,8 @@ PlatformResult Calendar::UpdateBatch(const picojson::object& args, ret = calendar_db_update_records(list_ptr.get()); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't update calendar items", - ("calendar_db_update_records error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't update calendar items", + ("calendar_db_update_records error: %d (%s)", ret, get_error_message(ret))); } } else { // @todo update the exdate for a recurring parent event and add a new @@ -391,8 +366,7 @@ PlatformResult Calendar::UpdateBatch(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::Remove(const picojson::object& args, - picojson::object& out) { +PlatformResult Calendar::Remove(const picojson::object& args, picojson::object& out) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -418,8 +392,8 @@ PlatformResult Calendar::SetDefaultFilter(calendar_query_h* calendar_query, int calendar_filter_h calendar_filter = nullptr; const char* view_uri = (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event._uri : _calendar_todo._uri; - const int book_id = - (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event.calendar_book_id : _calendar_todo.calendar_book_id; + const int book_id = (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event.calendar_book_id + : _calendar_todo.calendar_book_id; const int is_deleted = (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event.is_deleted : _calendar_todo.is_deleted; @@ -455,32 +429,28 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr int calendar_id = common::stol(FromJson(args, "calendarId")); int error_code = 0; calendar_record_h handle = nullptr; - PlatformResult status = - CalendarRecord::GetById(calendar_id, _calendar_book._uri, &handle); + PlatformResult status = CalendarRecord::GetById(calendar_id, _calendar_book._uri, &handle); if (status.IsError()) return status; - CalendarRecordPtr calendar_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr calendar_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); int type; - status = CalendarRecord::GetInt(calendar_ptr.get(), _calendar_book.store_type, - &type); + status = CalendarRecord::GetInt(calendar_ptr.get(), _calendar_book.store_type, &type); if (status.IsError()) return status; - const char* view_uri = (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event._uri : _calendar_todo._uri; + const char* view_uri = + (type == CALENDAR_BOOK_TYPE_EVENT) ? _calendar_event._uri : _calendar_todo._uri; calendar_query_h calendar_query = nullptr; error_code = calendar_query_create(view_uri, &calendar_query); if ((status = ErrorChecker(error_code)).IsError()) return status; - CalendarQueryPtr calendar_query_ptr(calendar_query, - CalendarRecord::QueryDeleter); + CalendarQueryPtr calendar_query_ptr(calendar_query, CalendarRecord::QueryDeleter); std::vector> intermediate_filters(1); if (!IsNull(args, "filter")) { FilterVisitor visitor; - visitor.SetOnAttributeFilter([&](const std::string& name, - AttributeMatchFlag match_flag, + visitor.SetOnAttributeFilter([&](const std::string& name, AttributeMatchFlag match_flag, const picojson::value& match_value) { int value = 0; calendar_filter_h calendar_filter = nullptr; @@ -488,37 +458,33 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr error_code = calendar_filter_create(view_uri, &calendar_filter); if ((status = ErrorChecker(error_code)).IsError()) return status; - CalendarFilterPtr calendar_filter_ptr(calendar_filter, - CalendarFilterDeleter); + CalendarFilterPtr calendar_filter_ptr(calendar_filter, CalendarFilterDeleter); unsigned int propertyId = 0; if (name == "startDate" || name == "endDate" || name == "dueDate") { - PlatformResult status = CalendarItem::GetPlatformProperty( - type, name + "_time", &propertyId); + PlatformResult status = + CalendarItem::GetPlatformProperty(type, name + "_time", &propertyId); if (status.IsError()) return status; } else { - PlatformResult status = - CalendarItem::GetPlatformProperty(type, name, &propertyId); + PlatformResult status = CalendarItem::GetPlatformProperty(type, name, &propertyId); if (status.IsError()) return status; } if (name == "id" || name == "id.uid") { if (type == CALENDAR_BOOK_TYPE_EVENT && name == "id") { - value = common::stol( - FromJson(JsonCast(match_value), "uid")); + value = common::stol(FromJson(JsonCast(match_value), "uid")); } else { if (match_value.is()) { value = common::stol(JsonCast(match_value)); } else if (match_value.is()) { value = static_cast(match_value.get()); } else { - return PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "Match value wrong type"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Match value wrong type"); } } if (value < 0) { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Match value cannot be less than 0"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Match value cannot be less than 0"); } calendar_match_int_flag_e flag; if (AttributeMatchFlag::kExists == match_flag) { @@ -532,14 +498,11 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr } else { flag = CALENDAR_MATCH_EQUAL; } - error_code = - calendar_filter_add_int(calendar_filter, propertyId, flag, value); + error_code = calendar_filter_add_int(calendar_filter, propertyId, flag, value); if ((status = ErrorChecker(error_code)).IsError()) return status; - } else if (name == "startDate" || name == "endDate" || - name == "dueDate") { + } else if (name == "startDate" || name == "endDate" || name == "dueDate") { calendar_match_int_flag_e flag; - Date dateTofilter = - CalendarItem::DateFromJson(JsonCast(match_value)); + Date dateTofilter = CalendarItem::DateFromJson(JsonCast(match_value)); if (AttributeMatchFlag::kExists == match_flag) { flag = CALENDAR_MATCH_GREATER_THAN_OR_EQUAL; value = 0; @@ -552,15 +515,14 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr flag = CALENDAR_MATCH_EQUAL; } - error_code = calendar_filter_add_caltime( - calendar_filter, propertyId, flag, - CalendarItem::DateToPlatform(dateTofilter, false)); + error_code = calendar_filter_add_caltime(calendar_filter, propertyId, flag, + CalendarItem::DateToPlatform(dateTofilter, false)); if ((status = ErrorChecker(error_code)).IsError()) return status; - } else if (name == "isAllDay" || name == "isDetached") { + } else if (name == "isAllDay" || name == "isDetached") { calendar_match_int_flag_e flag = CALENDAR_MATCH_EQUAL; if (match_value.is()) { - if(match_value.get()) { + if (match_value.get()) { value = 1; } else { value = 0; @@ -569,8 +531,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr value = 0; } - error_code = - calendar_filter_add_int(calendar_filter, propertyId, flag, value); + error_code = calendar_filter_add_int(calendar_filter, propertyId, flag, value); if ((status = ErrorChecker(error_code)).IsError()) return status; } else { std::string value = JsonCast(match_value); @@ -589,8 +550,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr flag = CALENDAR_MATCH_EXISTS; value = ""; } - calendar_filter_add_str(calendar_filter, propertyId, flag, - value.c_str()); + calendar_filter_add_str(calendar_filter, propertyId, flag, value.c_str()); } intermediate_filters[intermediate_filters.size() - 1].push_back( std::move(calendar_filter_ptr)); @@ -605,8 +565,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr visitor.SetOnCompositeFilterEnd([&](CompositeFilterType calType) { if (intermediate_filters.size() == 0) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Reached stack size equal to 0!"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Reached stack size equal to 0!"); } calendar_filter_h merged_filter = nullptr; @@ -615,21 +574,18 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr CalendarFilterPtr merged_filter_ptr(merged_filter, CalendarFilterDeleter); for (std::size_t i = 0; i < intermediate_filters.back().size(); ++i) { - error_code = calendar_filter_add_filter( - merged_filter, intermediate_filters.back().at(i).get()); + error_code = + calendar_filter_add_filter(merged_filter, intermediate_filters.back().at(i).get()); if ((status = ErrorChecker(error_code)).IsError()) return status; if (CompositeFilterType::kIntersection == calType) { - error_code = calendar_filter_add_operator( - merged_filter, CALENDAR_FILTER_OPERATOR_AND); + error_code = calendar_filter_add_operator(merged_filter, CALENDAR_FILTER_OPERATOR_AND); if ((status = ErrorChecker(error_code)).IsError()) return status; } else if (CompositeFilterType::kUnion == calType) { - error_code = calendar_filter_add_operator( - merged_filter, CALENDAR_FILTER_OPERATOR_OR); + error_code = calendar_filter_add_operator(merged_filter, CALENDAR_FILTER_OPERATOR_OR); if ((status = ErrorChecker(error_code)).IsError()) return status; } else { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid union type!", - ("Invalid union type: %d", calType)); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid union type!", + ("Invalid union type: %d", calType)); } } intermediate_filters.pop_back(); @@ -638,17 +594,15 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr return PlatformResult(ErrorCode::NO_ERROR); }); - visitor.SetOnAttributeRangeFilter([&](const std::string& name, - const JsonValue& initial_value, + visitor.SetOnAttributeRangeFilter([&](const std::string& name, const JsonValue& initial_value, const JsonValue& end_value) { unsigned int propertyId = 0; if (name == "startDate" || name == "endDate" || name == "dueDate") { - PlatformResult status = CalendarItem::GetPlatformProperty( - type, name + "_time", &propertyId); + PlatformResult status = + CalendarItem::GetPlatformProperty(type, name + "_time", &propertyId); if (status.IsError()) return status; } else { - PlatformResult status = - CalendarItem::GetPlatformProperty(type, name, &propertyId); + PlatformResult status = CalendarItem::GetPlatformProperty(type, name, &propertyId); if (status.IsError()) return status; } @@ -658,8 +612,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr error_code = calendar_filter_create(view_uri, &calendar_filter); if ((status = ErrorChecker(error_code)).IsError()) return status; - CalendarFilterPtr calendar_filter_ptr(calendar_filter, - CalendarFilterDeleter); + CalendarFilterPtr calendar_filter_ptr(calendar_filter, CalendarFilterDeleter); bool initial_value_exists = (!IsNull(initial_value)); bool end_value_exists = (!IsNull(end_value)); @@ -668,10 +621,8 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr int end_value_date = 0; if (initial_value_exists) - initial_value_date = - common::stol(JsonCast(initial_value)); - if (end_value_exists) - end_value_date = common::stol(JsonCast(end_value)); + initial_value_date = common::stol(JsonCast(initial_value)); + if (end_value_exists) end_value_date = common::stol(JsonCast(end_value)); if (initial_value_exists && end_value_exists) { calendar_filter_h sub_filter = NULL; @@ -682,43 +633,37 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr CalendarFilterPtr sub_filter_ptr(sub_filter, CalendarFilterDeleter); error_code = calendar_filter_add_int( - sub_filter, propertyId, CALENDAR_MATCH_GREATER_THAN_OR_EQUAL, - initial_value_date); + sub_filter, propertyId, CALENDAR_MATCH_GREATER_THAN_OR_EQUAL, initial_value_date); if ((status = ErrorChecker(error_code)).IsError()) return status; - error_code = calendar_filter_add_operator( - sub_filter, CALENDAR_FILTER_OPERATOR_AND); + error_code = calendar_filter_add_operator(sub_filter, CALENDAR_FILTER_OPERATOR_AND); if ((status = ErrorChecker(error_code)).IsError()) return status; - error_code = calendar_filter_add_int( - sub_filter, propertyId, CALENDAR_MATCH_LESS_THAN_OR_EQUAL, - end_value_date); + error_code = calendar_filter_add_int(sub_filter, propertyId, + CALENDAR_MATCH_LESS_THAN_OR_EQUAL, end_value_date); if ((status = ErrorChecker(error_code)).IsError()) return status; error_code = calendar_filter_add_filter(calendar_filter, sub_filter); if ((status = ErrorChecker(error_code)).IsError()) return status; } else if (initial_value_exists) { - error_code = calendar_filter_add_int( - calendar_filter, propertyId, CALENDAR_MATCH_GREATER_THAN_OR_EQUAL, - initial_value_date); + error_code = + calendar_filter_add_int(calendar_filter, propertyId, + CALENDAR_MATCH_GREATER_THAN_OR_EQUAL, initial_value_date); if ((status = ErrorChecker(error_code)).IsError()) return status; } else if (end_value_exists) { - error_code = calendar_filter_add_int( - calendar_filter, propertyId, CALENDAR_MATCH_LESS_THAN_OR_EQUAL, - end_value_date); + error_code = calendar_filter_add_int(calendar_filter, propertyId, + CALENDAR_MATCH_LESS_THAN_OR_EQUAL, end_value_date); if ((status = ErrorChecker(error_code)).IsError()) return status; } - } else if (name == "startDate" || name == "dueDate" || - name == "endDate") { + } else if (name == "startDate" || name == "dueDate" || name == "endDate") { Date initial_value_date; Date end_value_date; if (initial_value_exists) - initial_value_date = CalendarItem::DateFromJson( - JsonCast(initial_value)); + initial_value_date = + CalendarItem::DateFromJson(JsonCast(initial_value)); if (end_value_exists) - end_value_date = - CalendarItem::DateFromJson(JsonCast(end_value)); + end_value_date = CalendarItem::DateFromJson(JsonCast(end_value)); calendar_filter_h normal_filter = nullptr; calendar_filter_h all_day_filter = nullptr; @@ -743,11 +688,9 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr } if (initial_value_exists && end_value_exists) { - error_code = calendar_filter_add_operator( - normal_filter, CALENDAR_FILTER_OPERATOR_AND); + error_code = calendar_filter_add_operator(normal_filter, CALENDAR_FILTER_OPERATOR_AND); if ((status = ErrorChecker(error_code)).IsError()) return status; - error_code = calendar_filter_add_operator( - all_day_filter, CALENDAR_FILTER_OPERATOR_AND); + error_code = calendar_filter_add_operator(all_day_filter, CALENDAR_FILTER_OPERATOR_AND); if ((status = ErrorChecker(error_code)).IsError()) return status; } @@ -788,27 +731,22 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr CalendarFilterPtr sub_filter_ptr(sub_filter, CalendarFilterDeleter); - error_code = calendar_filter_add_str(sub_filter, propertyId, - CALENDAR_MATCH_STARTSWITH, + error_code = calendar_filter_add_str(sub_filter, propertyId, CALENDAR_MATCH_STARTSWITH, initial_value_str.c_str()); if ((status = ErrorChecker(error_code)).IsError()) return status; - error_code = calendar_filter_add_operator( - sub_filter, CALENDAR_FILTER_OPERATOR_AND); + error_code = calendar_filter_add_operator(sub_filter, CALENDAR_FILTER_OPERATOR_AND); if ((status = ErrorChecker(error_code)).IsError()) return status; - error_code = calendar_filter_add_str(sub_filter, propertyId, - CALENDAR_MATCH_ENDSWITH, + error_code = calendar_filter_add_str(sub_filter, propertyId, CALENDAR_MATCH_ENDSWITH, end_value_str.c_str()); if ((status = ErrorChecker(error_code)).IsError()) return status; error_code = calendar_filter_add_filter(calendar_filter, sub_filter); if ((status = ErrorChecker(error_code)).IsError()) return status; } else if (initial_value_exists) { - error_code = calendar_filter_add_str(calendar_filter, propertyId, - CALENDAR_MATCH_STARTSWITH, - initial_value_str.c_str()); + error_code = calendar_filter_add_str( + calendar_filter, propertyId, CALENDAR_MATCH_STARTSWITH, initial_value_str.c_str()); if ((status = ErrorChecker(error_code)).IsError()) return status; } else if (end_value_exists) { - error_code = calendar_filter_add_str(calendar_filter, propertyId, - CALENDAR_MATCH_ENDSWITH, + error_code = calendar_filter_add_str(calendar_filter, propertyId, CALENDAR_MATCH_ENDSWITH, end_value_str.c_str()); if ((status = ErrorChecker(error_code)).IsError()) return status; } @@ -819,34 +757,28 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr return PlatformResult(ErrorCode::NO_ERROR); }); visitor.Visit(FromJson(args, "filter")); - if ((intermediate_filters.size() != 1) || - (intermediate_filters[0].size() != 1)) { + if ((intermediate_filters.size() != 1) || (intermediate_filters[0].size() != 1)) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Bad filter evaluation!"); } - error_code = calendar_query_set_filter(calendar_query, - intermediate_filters[0][0].get()); + error_code = calendar_query_set_filter(calendar_query, intermediate_filters[0][0].get()); if ((status = ErrorChecker(error_code)).IsError()) return status; } else { - //filter is not provided so default filter should be set + // filter is not provided so default filter should be set status = SetDefaultFilter(&calendar_query, type, calendar_id); if (status.IsError()) return status; } if (!IsNull(args, "sortMode")) { - picojson::object sortModeObject = - FromJson(args, "sortMode"); + picojson::object sortModeObject = FromJson(args, "sortMode"); unsigned int propertyId = 0; - std::string attributeName = - FromJson(sortModeObject, "attributeName"); + std::string attributeName = FromJson(sortModeObject, "attributeName"); std::string order = FromJson(sortModeObject, "order"); - if (attributeName == "startDate" || attributeName == "dueDate" || - attributeName == "endDate") { - PlatformResult status = CalendarItem::GetPlatformProperty( - type, attributeName + "_time", &propertyId); + if (attributeName == "startDate" || attributeName == "dueDate" || attributeName == "endDate") { + PlatformResult status = + CalendarItem::GetPlatformProperty(type, attributeName + "_time", &propertyId); if (status.IsError()) return status; } else { - PlatformResult status = - CalendarItem::GetPlatformProperty(type, attributeName, &propertyId); + PlatformResult status = CalendarItem::GetPlatformProperty(type, attributeName, &propertyId); if (status.IsError()) return status; } @@ -860,13 +792,11 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr } calendar_list_h record_list = nullptr; - error_code = - calendar_db_get_records_with_query(calendar_query, 0, 0, &record_list); + error_code = calendar_db_get_records_with_query(calendar_query, 0, 0, &record_list); if (CALENDAR_ERROR_NONE != error_code) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "calendar_db_get_records_with_query failed", - ("calendar_db_get_records_with_query error: %d (%s)", - error_code, get_error_message(error_code))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "calendar_db_get_records_with_query failed", + ("calendar_db_get_records_with_query error: %d (%s)", error_code, + get_error_message(error_code))); } CalendarListPtr record_list_ptr(record_list, CalendarRecord::ListDeleter); @@ -874,33 +804,29 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr error_code = calendar_list_get_count(record_list, &record_count); if (CALENDAR_ERROR_NONE != error_code) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "calendar_list_get_count failed", - ("calendar_list_get_count error: %d (%s)", - error_code, get_error_message(error_code))); + ErrorCode::UNKNOWN_ERR, "calendar_list_get_count failed", + ("calendar_list_get_count error: %d (%s)", error_code, get_error_message(error_code))); } error_code = calendar_list_first(record_list); if (CALENDAR_ERROR_NONE != error_code) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "calendar_list_first failed", - ("calendar_list_first error: %d (%s)", - error_code, get_error_message(error_code))); + ErrorCode::UNKNOWN_ERR, "calendar_list_first failed", + ("calendar_list_first error: %d (%s)", error_code, get_error_message(error_code))); } array.reserve(record_count); LoggerD("Found %d records", record_count); for (int i = 0; i < record_count; ++i) { calendar_record_h current_record = NULL; - error_code = - calendar_list_get_current_record_p(record_list, ¤t_record); + error_code = calendar_list_get_current_record_p(record_list, ¤t_record); if (CALENDAR_ERROR_NONE != error_code) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "calendar_list_get_current_record_p failed", - ("calendar_list_get_current_record_p error: %d (%s)", - error_code, get_error_message(error_code))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "calendar_list_get_current_record_p failed", + ("calendar_list_get_current_record_p error: %d (%s)", error_code, + get_error_message(error_code))); } picojson::value record_obj = picojson::value(picojson::object()); - PlatformResult status = CalendarItem::ToJson( - type, current_record, &record_obj.get()); + PlatformResult status = + CalendarItem::ToJson(type, current_record, &record_obj.get()); if (status.IsError()) return status; array.push_back(record_obj); @@ -915,8 +841,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::RemoveBatch(const picojson::object& args, - picojson::array& array) { +PlatformResult Calendar::RemoveBatch(const picojson::object& args, picojson::array& array) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -935,24 +860,20 @@ PlatformResult Calendar::RemoveBatch(const picojson::object& args, int id; for (int i = 0, size = ids.size(); i < size; i++) { if (type == CALENDAR_BOOK_TYPE_EVENT) { - id = common::stol( - FromJson(ids.at(i).get(), "uid")); + id = common::stol(FromJson(ids.at(i).get(), "uid")); } else { id = common::stol(ids.at(i).get()); } calendar_record_h handle = nullptr; - PlatformResult status = - CalendarItem::GetById(id, view_uri.c_str(), &handle); + PlatformResult status = CalendarItem::GetById(id, view_uri.c_str(), &handle); if (status.IsError()) return status; - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); if (type == CALENDAR_BOOK_TYPE_EVENT) { std::string rid; - status = CalendarRecord::GetString(record_ptr.get(), - _calendar_event.recurrence_id, &rid); + status = CalendarRecord::GetString(record_ptr.get(), _calendar_event.recurrence_id, &rid); if (status.IsError()) return status; if (rid.empty()) { @@ -966,19 +887,18 @@ PlatformResult Calendar::RemoveBatch(const picojson::object& args, } if (ids_to_remove.size() > 0) { - int ret = calendar_db_delete_records(view_uri.c_str(), &ids_to_remove[0], - ids_to_remove.size()); + int ret = calendar_db_delete_records(view_uri.c_str(), &ids_to_remove[0], ids_to_remove.size()); if (CALENDAR_ERROR_NONE != ret) { LoggerE("calendar_db_delete_records failed."); if (CALENDAR_ERROR_INVALID_PARAMETER == ret) { return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Parameter is invalid", - ("calendar_db_delete_records error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Parameter is invalid", + ("calendar_db_delete_records error: %d (%s)", ret, get_error_message(ret))); } else { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "UnknownError", - ("calendar_db_delete_records error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "UnknownError", + ("calendar_db_delete_records error: %d (%s)", ret, get_error_message(ret))); } } } @@ -986,8 +906,7 @@ PlatformResult Calendar::RemoveBatch(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::AddChangeListener(const picojson::object& args, - picojson::object& out) { +PlatformResult Calendar::AddChangeListener(const picojson::object& args, picojson::object& out) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -1004,16 +923,16 @@ PlatformResult Calendar::AddChangeListener(const picojson::object& args, if (CALENDAR_ERROR_NONE != ret) { LoggerE("Add calendar change callback error for type %s", type.c_str()); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Add calendar change callback error", - ("calendar_db_add_changed_cb error %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Add calendar change callback error", + ("calendar_db_add_changed_cb error %d (%s)", ret, get_error_message(ret))); } ret = calendar_db_get_current_version(¤t_db_version_); if (CALENDAR_ERROR_NONE != ret) { current_db_version_ = 0; return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't get calendar db version", - ("calendar_db_get_current_version error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't get calendar db version", + ("calendar_db_get_current_version error: %d (%s)", ret, get_error_message(ret))); } listeners_registered_[type] = listener_id; @@ -1022,8 +941,7 @@ PlatformResult Calendar::AddChangeListener(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Calendar::RemoveChangeListener(const picojson::object& args, - picojson::object& out) { +PlatformResult Calendar::RemoveChangeListener(const picojson::object& args, picojson::object& out) { if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -1037,10 +955,9 @@ PlatformResult Calendar::RemoveChangeListener(const picojson::object& args, int ret = calendar_db_remove_changed_cb(view_uri.c_str(), ChangeCallback, this); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Remove calendar change callback error", - ("Remove calendar change callback error for type %s - %d (%s)", - type.c_str(), ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Remove calendar change callback error", + ("Remove calendar change callback error for type %s - %d (%s)", + type.c_str(), ret, get_error_message(ret))); } listeners_registered_.erase(type); } @@ -1056,8 +973,7 @@ void Calendar::ChangeCallback(const char* view_uri, void* user_data) { calendar_list_h list = nullptr; int ret, updated_version; ret = calendar_db_get_changes_by_version(view_uri, CALENDAR_BOOK_FILTER_ALL, - c->current_db_version_, &list, - &updated_version); + c->current_db_version_, &list, &updated_version); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Can't get the changed item list"); return; @@ -1106,25 +1022,22 @@ void Calendar::ChangeCallback(const char* view_uri, void* user_data) { return; } - PlatformResult result = - CalendarRecord::GetInt(update_info, _calendar_updated_info.id, &id); + PlatformResult result = CalendarRecord::GetInt(update_info, _calendar_updated_info.id, &id); if (result.IsError()) return; - result = CalendarRecord::GetInt( - update_info, _calendar_updated_info.modified_status, &status); + result = CalendarRecord::GetInt(update_info, _calendar_updated_info.modified_status, &status); if (result.IsError()) return; if (status == CALENDAR_RECORD_MODIFIED_STATUS_DELETED) { - result = CalendarRecord::GetInt( - update_info, _calendar_updated_info.calendar_book_id, &calendar_id); + result = CalendarRecord::GetInt(update_info, _calendar_updated_info.calendar_book_id, + &calendar_id); if (result.IsError()) return; picojson::value removed_row = picojson::value(picojson::object()); picojson::object& removed_obj = removed_row.get(); + removed_obj.insert(std::make_pair("id", picojson::value(std::to_string(id)))); removed_obj.insert( - std::make_pair("id", picojson::value(std::to_string(id)))); - removed_obj.insert(std::make_pair( - "calendarId", picojson::value(std::to_string(calendar_id)))); + std::make_pair("calendarId", picojson::value(std::to_string(calendar_id)))); removed.push_back(removed_row); @@ -1136,12 +1049,10 @@ void Calendar::ChangeCallback(const char* view_uri, void* user_data) { result = CalendarRecord::GetById(id, view_uri, &handle); if (result.IsError()) return; - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); picojson::value record_obj = picojson::value(picojson::object()); - result = CalendarItem::ToJson(type, record_ptr.get(), - &record_obj.get()); + result = CalendarItem::ToJson(type, record_ptr.get(), &record_obj.get()); if (result.IsError()) { LoggerE("error occured: %s", result.message().c_str()); return; @@ -1179,8 +1090,8 @@ void Calendar::ChangeCallback(const char* view_uri, void* user_data) { PlatformResult Calendar::ErrorChecker(int errorCode) { if (errorCode != CALENDAR_ERROR_NONE) return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "exception occured", - ("Error %d in ErrorChecker (%s)", errorCode, get_error_message(errorCode))); + ErrorCode::UNKNOWN_ERR, "exception occured", + ("Error %d in ErrorChecker (%s)", errorCode, get_error_message(errorCode))); return PlatformResult(ErrorCode::NO_ERROR); } diff --git a/src/calendar/calendar.h b/src/calendar/calendar.h index 2d5db2e..c4a16ed 100644 --- a/src/calendar/calendar.h +++ b/src/calendar/calendar.h @@ -17,8 +17,8 @@ #ifndef CALENDAR_CALENDAR_H_ #define CALENDAR_CALENDAR_H_ -#include #include +#include #include "common/picojson.h" #include "common/platform_result.h" @@ -162,8 +162,7 @@ class Calendar { * {status: 'success'} * @endcode */ - common::PlatformResult AddChangeListener(const JsonObject& args, - JsonObject& out); + common::PlatformResult AddChangeListener(const JsonObject& args, JsonObject& out); /** * Signature: @code void removeChangeListener(); @endcode @@ -176,8 +175,7 @@ class Calendar { * {status: 'success'} * @endcode */ - common::PlatformResult RemoveChangeListener(const JsonObject& args, - JsonObject& out); + common::PlatformResult RemoveChangeListener(const JsonObject& args, JsonObject& out); private: std::map listeners_registered_; diff --git a/src/calendar/calendar_extension.cc b/src/calendar/calendar_extension.cc old mode 100755 new mode 100644 index bb0cf95..aa0d1fd --- a/src/calendar/calendar_extension.cc +++ b/src/calendar/calendar_extension.cc @@ -28,20 +28,19 @@ CalendarExtension::CalendarExtension() { SetExtensionName("tizen.calendar"); SetJavaScriptAPI(kSource_calendar_api); - const char* entry_points[] = { - "tizen.Calendar", - "tizen.CalendarEventId", - "tizen.CalendarEvent", - "tizen.CalendarTask", - "tizen.CalendarAlarm", - "tizen.CalendarAttendee", - "tizen.CalendarRecurrenceRule", - NULL - }; + const char* entry_points[] = {"tizen.Calendar", + "tizen.CalendarEventId", + "tizen.CalendarEvent", + "tizen.CalendarTask", + "tizen.CalendarAlarm", + "tizen.CalendarAttendee", + "tizen.CalendarRecurrenceRule", + NULL}; SetExtraJSEntryPoints(entry_points); } -CalendarExtension::~CalendarExtension() {} +CalendarExtension::~CalendarExtension() { +} common::Instance* CalendarExtension::CreateInstance() { return new extension::calendar::CalendarInstance(); diff --git a/src/calendar/calendar_extension.h b/src/calendar/calendar_extension.h old mode 100755 new mode 100644 index d1caee4..a1f27e5 --- a/src/calendar/calendar_extension.h +++ b/src/calendar/calendar_extension.h @@ -28,4 +28,4 @@ class CalendarExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // CALENDAR_CALENDAR_EXTENSION_H_ +#endif // CALENDAR_CALENDAR_EXTENSION_H_ diff --git a/src/calendar/calendar_instance.cc b/src/calendar/calendar_instance.cc old mode 100755 new mode 100644 index b477388..66c1777 --- a/src/calendar/calendar_instance.cc +++ b/src/calendar/calendar_instance.cc @@ -18,14 +18,14 @@ #include "common/converter.h" -#include "calendar/calendar_manager.h" #include "calendar/calendar.h" +#include "calendar/calendar_manager.h" #include "common/task-queue.h" #include "common/tools.h" -#include -#include #include +#include +#include #include "calendar_record.h" namespace extension { @@ -39,14 +39,12 @@ const std::string kPrivilegeCalendarWrite = "http://tizen.org/privilege/calendar using namespace common; using namespace extension::calendar; -CalendarInstance::CalendarInstance() - : calendar_(*this) { +CalendarInstance::CalendarInstance() : calendar_(*this) { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&CalendarInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&CalendarInstance::x, this, _1, _2)); // Calendar REGISTER_SYNC("Calendar_get", CalendarGet); @@ -59,12 +57,10 @@ CalendarInstance::CalendarInstance() // Calendar Manager REGISTER_SYNC("CalendarManager_addCalendar", CalendarManagerAddCalendar); REGISTER_SYNC("CalendarManager_getCalendar", CalendarManagerGetCalendar); - REGISTER_SYNC("CalendarManager_removeCalendar", - CalendarManagerRemoveCalendar); + REGISTER_SYNC("CalendarManager_removeCalendar", CalendarManagerRemoveCalendar); #undef REGISTER_SYNC -#define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&CalendarInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&CalendarInstance::x, this, _1, _2)); REGISTER_ASYNC("Calendar_addBatch", CalendarAddBatch); REGISTER_ASYNC("Calendar_updateBatch", CalendarUpdateBatch); REGISTER_ASYNC("Calendar_removeBatch", CalendarRemoveBatch); @@ -84,13 +80,11 @@ void CalendarInstance::CalendarGet(const JsonValue& args, JsonObject& out) { JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.Get(common::JsonCast(args), - val.get()); + PlatformResult status = calendar_.Get(common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(val, out); - else - { + } else { LogAndReportError(status, &out); } } @@ -101,18 +95,16 @@ void CalendarInstance::CalendarAdd(const JsonValue& args, JsonObject& out) { JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.Add(common::JsonCast(args), - val.get()); + PlatformResult status = calendar_.Add(common::JsonCast(args), val.get()); if (status.IsSuccess()) { ReportSuccess(val, out); - } else{ + } else { LogAndReportError(status, &out); } } -void CalendarInstance::CalendarAddBatch(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarAddBatch(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); @@ -120,19 +112,17 @@ void CalendarInstance::CalendarAddBatch(const JsonValue& args, auto get = [=](const std::shared_ptr& response) -> void { LoggerD("CalendarAddBatch->get"); JsonValue result = JsonValue(JsonArray()); - PlatformResult status = calendar_.AddBatch( - common::JsonCast(args), result.get()); + PlatformResult status = + calendar_.AddBatch(common::JsonCast(args), result.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(result, response->get()); - else - { + } else { LogAndReportError(status, &response->get()); } }; - auto get_response = - [callback_id, this](const std::shared_ptr& response) -> void { + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { LoggerD("CalendarAddBatch->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -142,8 +132,7 @@ void CalendarInstance::CalendarAddBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } void CalendarInstance::CalendarUpdate(const JsonValue& args, JsonObject& out) { @@ -152,19 +141,17 @@ void CalendarInstance::CalendarUpdate(const JsonValue& args, JsonObject& out) { JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.Update(common::JsonCast(args), - val.get()); + PlatformResult status = + calendar_.Update(common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(val, out); - else - { + } else { LogAndReportError(status, &out); } } -void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); @@ -172,19 +159,17 @@ void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, auto get = [=](const std::shared_ptr& response) -> void { LoggerD("CalendarUpdateBatch->get"); JsonValue result = JsonValue(JsonArray()); - PlatformResult status = calendar_.UpdateBatch( - common::JsonCast(args), result.get()); + PlatformResult status = + calendar_.UpdateBatch(common::JsonCast(args), result.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(result, response->get()); - else - { + } else { LogAndReportError(status, &response->get()); } }; - auto get_response = - [callback_id, this](const std::shared_ptr& response) -> void { + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { LoggerD("CalendarUpdateBatch->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -194,8 +179,7 @@ void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } void CalendarInstance::CalendarRemove(const JsonValue& args, JsonObject& out) { @@ -204,19 +188,17 @@ void CalendarInstance::CalendarRemove(const JsonValue& args, JsonObject& out) { JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.Remove(common::JsonCast(args), - val.get()); + PlatformResult status = + calendar_.Remove(common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(out); - else - { + } else { LogAndReportError(status, &val.get()); } } -void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); @@ -224,19 +206,17 @@ void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, auto get = [=](const std::shared_ptr& response) -> void { LoggerD("CalendarRemoveBatch->get"); JsonValue result = JsonValue(JsonArray()); - PlatformResult status = calendar_.RemoveBatch( - common::JsonCast(args), result.get()); + PlatformResult status = + calendar_.RemoveBatch(common::JsonCast(args), result.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(result, response->get()); - else - { + } else { LogAndReportError(status, &response->get()); } }; - auto get_response = - [callback_id, this](const std::shared_ptr& response) -> void { + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { LoggerD("CalendarRemoveBatch->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -246,8 +226,7 @@ void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { @@ -258,19 +237,17 @@ void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { auto get = [=](const std::shared_ptr& response) -> void { LoggerD("CalendarFind->get"); JsonValue result = JsonValue(JsonArray()); - PlatformResult status = calendar_.Find( - common::JsonCast(args), result.get()); + PlatformResult status = + calendar_.Find(common::JsonCast(args), result.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(result, response->get()); - else - { + } else { LogAndReportError(status, &response->get()); } }; - auto get_response = - [callback_id, this](const std::shared_ptr& response) -> void { + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { LoggerD("CalendarFind->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -280,49 +257,43 @@ void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void CalendarInstance::CalendarAddChangeListener(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarAddChangeListener(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.AddChangeListener( - common::JsonCast(args), val.get()); + PlatformResult status = + calendar_.AddChangeListener(common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(out); - else - { + } else { LogAndReportError(status, &val.get()); } } -void CalendarInstance::CalendarRemoveChangeListener(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarRemoveChangeListener(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = calendar_.RemoveChangeListener( - common::JsonCast(args), val.get()); + PlatformResult status = + calendar_.RemoveChangeListener(common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(out); - else - { + } else { LogAndReportError(status, &val.get()); } } // CalendarManager -void CalendarInstance::CalendarManagerAddCalendar(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarManagerAddCalendar(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); @@ -330,33 +301,29 @@ void CalendarInstance::CalendarManagerAddCalendar(const JsonValue& args, PlatformResult status = CalendarManager::GetInstance().AddCalendar( common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(val, out); - else - { + } else { LogAndReportError(status, &out); } } -void CalendarInstance::CalendarManagerGetCalendar(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarManagerGetCalendar(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = CalendarManager::GetInstance().GetCalendar(common::JsonCast(args), - val.get()); + PlatformResult status = CalendarManager::GetInstance().GetCalendar( + common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(val, out); - else - { + } else { LogAndReportError(status, &out); } } -void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); @@ -368,16 +335,14 @@ void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, PlatformResult status = CalendarManager::GetInstance().GetCalendars( common::JsonCast(args), result.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(result, response->get()); - else - { + } else { LogAndReportError(status, &response->get()); } }; - auto get_response = [ callback_id, this ](const std::shared_ptr & - response)->void { + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { LoggerD("CalendarManagerGetCalendars->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -387,12 +352,10 @@ void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void CalendarInstance::CalendarManagerRemoveCalendar(const JsonValue& args, - JsonObject& out) { +void CalendarInstance::CalendarManagerRemoveCalendar(const JsonValue& args, JsonObject& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); @@ -400,10 +363,9 @@ void CalendarInstance::CalendarManagerRemoveCalendar(const JsonValue& args, PlatformResult status = CalendarManager::GetInstance().RemoveCalendar( common::JsonCast(args), val.get()); - if (status.IsSuccess()) + if (status.IsSuccess()) { ReportSuccess(val, out); - else - { + } else { LogAndReportError(status, &out); } } diff --git a/src/calendar/calendar_instance.h b/src/calendar/calendar_instance.h old mode 100755 new mode 100644 index 1537e69..92bf8a5 --- a/src/calendar/calendar_instance.h +++ b/src/calendar/calendar_instance.h @@ -50,7 +50,7 @@ class CalendarInstance : public common::ParsedInstance { Calendar calendar_; }; -} // namespace calendar -} // namespace extension +} // namespace calendar +} // namespace extension -#endif // CALENDAR_CALENDAR_INSTANCE_H_ +#endif // CALENDAR_CALENDAR_INSTANCE_H_ diff --git a/src/calendar/calendar_item.cc b/src/calendar/calendar_item.cc old mode 100755 new mode 100644 index f761986..be2eda7 --- a/src/calendar/calendar_item.cc +++ b/src/calendar/calendar_item.cc @@ -19,9 +19,9 @@ #include #include -#include "common/logger.h" -#include "common/converter.h" #include +#include "common/converter.h" +#include "common/logger.h" using namespace common; namespace extension { namespace calendar { @@ -48,57 +48,57 @@ const std::string kRecurrenceRuleFrequency = "RecurrenceRuleFrequency"; } const PlatformPropertyMap CalendarItem::platform_property_map_ = { - {"id", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.id}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.id}}}, - {"id.uid", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.id}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.uid}}}, - {"calendar_id", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.calendar_book_id}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.calendar_book_id}}}, - {"description", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.description}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.description}}}, - {"summary", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.summary}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.summary}}}, - {"isAllDay", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.is_allday}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.is_allday}}}, - {"startDate_time", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.start_time}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.start_time}}}, - {"startDate_tzid", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.start_tzid}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.start_tzid}}}, - {"location", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.location}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.location}}}, - {"latitude", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.latitude}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.latitude}}}, - {"longitude", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.longitude}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.longitude}}}, - {"organizer", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.organizer_name}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.organizer_name}}}, - {"visibility", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.sensitivity}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.sensitivity}}}, - {"status", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.event_status}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.todo_status}}}, - {"priority", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.priority}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.priority}}}, - {"categories", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.categories}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.categories}}}, - {"lastModificationDate", { - {CALENDAR_BOOK_TYPE_EVENT, _calendar_event.last_modified_time}, - {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.last_modified_time}}}, + {"id", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.id}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.id}}}, + {"id.uid", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.id}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.uid}}}, + {"calendar_id", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.calendar_book_id}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.calendar_book_id}}}, + {"description", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.description}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.description}}}, + {"summary", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.summary}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.summary}}}, + {"isAllDay", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.is_allday}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.is_allday}}}, + {"startDate_time", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.start_time}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.start_time}}}, + {"startDate_tzid", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.start_tzid}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.start_tzid}}}, + {"location", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.location}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.location}}}, + {"latitude", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.latitude}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.latitude}}}, + {"longitude", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.longitude}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.longitude}}}, + {"organizer", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.organizer_name}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.organizer_name}}}, + {"visibility", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.sensitivity}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.sensitivity}}}, + {"status", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.event_status}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.todo_status}}}, + {"priority", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.priority}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.priority}}}, + {"categories", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.categories}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.categories}}}, + {"lastModificationDate", + {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.last_modified_time}, + {CALENDAR_BOOK_TYPE_TODO, _calendar_todo.last_modified_time}}}, // event only {"endDate_time", {{CALENDAR_BOOK_TYPE_EVENT, _calendar_event.end_time}}}, @@ -113,81 +113,83 @@ const PlatformPropertyMap CalendarItem::platform_property_map_ = { {"progress", {{CALENDAR_BOOK_TYPE_TODO, _calendar_todo.progress}}}}; const PlatformEnumMap CalendarItem::platform_enum_map_ = { - {kItemVisibility, { - {kDefaultEnumKey, CALENDAR_SENSITIVITY_PUBLIC}, - {"PUBLIC", CALENDAR_SENSITIVITY_PUBLIC}, - {"PRIVATE", CALENDAR_SENSITIVITY_PRIVATE}, - {"CONFIDENTIAL", CALENDAR_SENSITIVITY_CONFIDENTIAL}}}, - {kEventAvailability, { - {kDefaultEnumKey, CALENDAR_EVENT_BUSY_STATUS_BUSY}, - {"FREE", CALENDAR_EVENT_BUSY_STATUS_FREE}, - {"BUSY", CALENDAR_EVENT_BUSY_STATUS_BUSY}, - {"BUSY-UNAVAILABLE", CALENDAR_EVENT_BUSY_STATUS_UNAVAILABLE}, - {"BUSY-TENTATIVE", CALENDAR_EVENT_BUSY_STATUS_TENTATIVE}}}, - {kEventAvailability, { - {kDefaultEnumKey, CALENDAR_EVENT_BUSY_STATUS_BUSY}, - {"FREE", CALENDAR_EVENT_BUSY_STATUS_FREE}, - {"BUSY", CALENDAR_EVENT_BUSY_STATUS_BUSY}, - {"BUSY-UNAVAILABLE", CALENDAR_EVENT_BUSY_STATUS_UNAVAILABLE}, - {"BUSY-TENTATIVE", CALENDAR_EVENT_BUSY_STATUS_TENTATIVE}}}, - {kEventPriority, { - {kDefaultEnumKey, CALENDAR_EVENT_PRIORITY_NONE}, - {"NONE", CALENDAR_EVENT_PRIORITY_NONE}, - {"LOW", CALENDAR_EVENT_PRIORITY_LOW}, - {"MEDIUM", CALENDAR_EVENT_PRIORITY_NORMAL}, - {"HIGH", CALENDAR_EVENT_PRIORITY_HIGH}}}, - {kTaskPriority, { - {kDefaultEnumKey, CALENDAR_TODO_PRIORITY_NONE}, - {"NONE", CALENDAR_TODO_PRIORITY_NONE}, - {"LOW", CALENDAR_TODO_PRIORITY_LOW}, - {"MEDIUM", CALENDAR_TODO_PRIORITY_NORMAL}, - {"HIGH", CALENDAR_TODO_PRIORITY_HIGH}}}, - {kEventStatus, { - {kDefaultEnumKey, CALENDAR_EVENT_STATUS_NONE}, - {"NONE", CALENDAR_EVENT_STATUS_NONE}, - {"TENTATIVE", CALENDAR_EVENT_STATUS_TENTATIVE}, - {"CONFIRMED", CALENDAR_EVENT_STATUS_CONFIRMED}, - {"CANCELLED", CALENDAR_EVENT_STATUS_CANCELLED}}}, - {kTaskStatus, { - {kDefaultEnumKey, CALENDAR_TODO_STATUS_NONE}, - {"NONE", CALENDAR_TODO_STATUS_NONE}, - {"NEEDS_ACTION", CALENDAR_TODO_STATUS_NEEDS_ACTION}, - {"COMPLETED", CALENDAR_TODO_STATUS_COMPLETED}, - {"IN_PROCESS", CALENDAR_TODO_STATUS_IN_PROCESS}, - {"CANCELLED", CALENDAR_TODO_STATUS_CANCELED}}}, - {kAttendeeRole, { - {kDefaultEnumKey, CALENDAR_ATTENDEE_ROLE_CHAIR}, - {"REQ_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_REQ_PARTICIPANT}, - {"OPT_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_OPT_PARTICIPANT}, - {"NON_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_NON_PARTICIPANT}, - {"CHAIR", CALENDAR_ATTENDEE_ROLE_CHAIR}}}, - {kAttendeeStatus, { - {kDefaultEnumKey, CALENDAR_ATTENDEE_STATUS_PENDING}, - {"PENDING", CALENDAR_ATTENDEE_STATUS_PENDING}, - {"ACCEPTED", CALENDAR_ATTENDEE_STATUS_ACCEPTED}, - {"DECLINED", CALENDAR_ATTENDEE_STATUS_DECLINED}, - {"TENTATIVE", CALENDAR_ATTENDEE_STATUS_TENTATIVE}, - {"DELEGATED", CALENDAR_ATTENDEE_STATUS_DELEGATED}, - {"COMPLETED", CALENDAR_ATTENDEE_STATUS_COMPLETED}, - {"IN_PROCESS", CALENDAR_ATTENDEE_STATUS_IN_PROCESS}, }}, - {kAttendeeType, { - {kDefaultEnumKey, CALENDAR_ATTENDEE_CUTYPE_INDIVIDUAL}, - {"INDIVIDUAL", CALENDAR_ATTENDEE_CUTYPE_INDIVIDUAL}, - {"GROUP", CALENDAR_ATTENDEE_CUTYPE_GROUP}, - {"RESOURCE", CALENDAR_ATTENDEE_CUTYPE_RESOURCE}, - {"ROOM", CALENDAR_ATTENDEE_CUTYPE_ROOM}, - {"UNKNOWN", CALENDAR_ATTENDEE_CUTYPE_UNKNOWN}}}, - {kAlarmMethod, { - {kDefaultEnumKey, CALENDAR_ALARM_ACTION_AUDIO}, - {"SOUND", CALENDAR_ALARM_ACTION_AUDIO}, - {"DISPLAY", CALENDAR_ALARM_ACTION_DISPLAY}}}, - {kRecurrenceRuleFrequency, { - {kDefaultEnumKey, CALENDAR_RECURRENCE_NONE}, - {"", CALENDAR_RECURRENCE_NONE}, - {"DAILY", CALENDAR_RECURRENCE_DAILY}, - {"WEEKLY", CALENDAR_RECURRENCE_WEEKLY}, - {"MONTHLY", CALENDAR_RECURRENCE_MONTHLY}, - {"YEARLY", CALENDAR_RECURRENCE_YEARLY}}}}; + {kItemVisibility, + {{kDefaultEnumKey, CALENDAR_SENSITIVITY_PUBLIC}, + {"PUBLIC", CALENDAR_SENSITIVITY_PUBLIC}, + {"PRIVATE", CALENDAR_SENSITIVITY_PRIVATE}, + {"CONFIDENTIAL", CALENDAR_SENSITIVITY_CONFIDENTIAL}}}, + {kEventAvailability, + {{kDefaultEnumKey, CALENDAR_EVENT_BUSY_STATUS_BUSY}, + {"FREE", CALENDAR_EVENT_BUSY_STATUS_FREE}, + {"BUSY", CALENDAR_EVENT_BUSY_STATUS_BUSY}, + {"BUSY-UNAVAILABLE", CALENDAR_EVENT_BUSY_STATUS_UNAVAILABLE}, + {"BUSY-TENTATIVE", CALENDAR_EVENT_BUSY_STATUS_TENTATIVE}}}, + {kEventAvailability, + {{kDefaultEnumKey, CALENDAR_EVENT_BUSY_STATUS_BUSY}, + {"FREE", CALENDAR_EVENT_BUSY_STATUS_FREE}, + {"BUSY", CALENDAR_EVENT_BUSY_STATUS_BUSY}, + {"BUSY-UNAVAILABLE", CALENDAR_EVENT_BUSY_STATUS_UNAVAILABLE}, + {"BUSY-TENTATIVE", CALENDAR_EVENT_BUSY_STATUS_TENTATIVE}}}, + {kEventPriority, + {{kDefaultEnumKey, CALENDAR_EVENT_PRIORITY_NONE}, + {"NONE", CALENDAR_EVENT_PRIORITY_NONE}, + {"LOW", CALENDAR_EVENT_PRIORITY_LOW}, + {"MEDIUM", CALENDAR_EVENT_PRIORITY_NORMAL}, + {"HIGH", CALENDAR_EVENT_PRIORITY_HIGH}}}, + {kTaskPriority, + {{kDefaultEnumKey, CALENDAR_TODO_PRIORITY_NONE}, + {"NONE", CALENDAR_TODO_PRIORITY_NONE}, + {"LOW", CALENDAR_TODO_PRIORITY_LOW}, + {"MEDIUM", CALENDAR_TODO_PRIORITY_NORMAL}, + {"HIGH", CALENDAR_TODO_PRIORITY_HIGH}}}, + {kEventStatus, + {{kDefaultEnumKey, CALENDAR_EVENT_STATUS_NONE}, + {"NONE", CALENDAR_EVENT_STATUS_NONE}, + {"TENTATIVE", CALENDAR_EVENT_STATUS_TENTATIVE}, + {"CONFIRMED", CALENDAR_EVENT_STATUS_CONFIRMED}, + {"CANCELLED", CALENDAR_EVENT_STATUS_CANCELLED}}}, + {kTaskStatus, + {{kDefaultEnumKey, CALENDAR_TODO_STATUS_NONE}, + {"NONE", CALENDAR_TODO_STATUS_NONE}, + {"NEEDS_ACTION", CALENDAR_TODO_STATUS_NEEDS_ACTION}, + {"COMPLETED", CALENDAR_TODO_STATUS_COMPLETED}, + {"IN_PROCESS", CALENDAR_TODO_STATUS_IN_PROCESS}, + {"CANCELLED", CALENDAR_TODO_STATUS_CANCELED}}}, + {kAttendeeRole, + {{kDefaultEnumKey, CALENDAR_ATTENDEE_ROLE_CHAIR}, + {"REQ_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_REQ_PARTICIPANT}, + {"OPT_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_OPT_PARTICIPANT}, + {"NON_PARTICIPANT", CALENDAR_ATTENDEE_ROLE_NON_PARTICIPANT}, + {"CHAIR", CALENDAR_ATTENDEE_ROLE_CHAIR}}}, + {kAttendeeStatus, + { + {kDefaultEnumKey, CALENDAR_ATTENDEE_STATUS_PENDING}, + {"PENDING", CALENDAR_ATTENDEE_STATUS_PENDING}, + {"ACCEPTED", CALENDAR_ATTENDEE_STATUS_ACCEPTED}, + {"DECLINED", CALENDAR_ATTENDEE_STATUS_DECLINED}, + {"TENTATIVE", CALENDAR_ATTENDEE_STATUS_TENTATIVE}, + {"DELEGATED", CALENDAR_ATTENDEE_STATUS_DELEGATED}, + {"COMPLETED", CALENDAR_ATTENDEE_STATUS_COMPLETED}, + {"IN_PROCESS", CALENDAR_ATTENDEE_STATUS_IN_PROCESS}, + }}, + {kAttendeeType, + {{kDefaultEnumKey, CALENDAR_ATTENDEE_CUTYPE_INDIVIDUAL}, + {"INDIVIDUAL", CALENDAR_ATTENDEE_CUTYPE_INDIVIDUAL}, + {"GROUP", CALENDAR_ATTENDEE_CUTYPE_GROUP}, + {"RESOURCE", CALENDAR_ATTENDEE_CUTYPE_RESOURCE}, + {"ROOM", CALENDAR_ATTENDEE_CUTYPE_ROOM}, + {"UNKNOWN", CALENDAR_ATTENDEE_CUTYPE_UNKNOWN}}}, + {kAlarmMethod, + {{kDefaultEnumKey, CALENDAR_ALARM_ACTION_AUDIO}, + {"SOUND", CALENDAR_ALARM_ACTION_AUDIO}, + {"DISPLAY", CALENDAR_ALARM_ACTION_DISPLAY}}}, + {kRecurrenceRuleFrequency, + {{kDefaultEnumKey, CALENDAR_RECURRENCE_NONE}, + {"", CALENDAR_RECURRENCE_NONE}, + {"DAILY", CALENDAR_RECURRENCE_DAILY}, + {"WEEKLY", CALENDAR_RECURRENCE_WEEKLY}, + {"MONTHLY", CALENDAR_RECURRENCE_MONTHLY}, + {"YEARLY", CALENDAR_RECURRENCE_YEARLY}}}}; PlatformEnumReverseMap CalendarItem::platform_enum_reverse_map_ = {}; PlatformResult CalendarItem::Create(int type, calendar_record_h* handle) { @@ -219,16 +221,14 @@ PlatformResult CalendarItem::Remove(int type, int id) { if (type == CALENDAR_BOOK_TYPE_EVENT) { std::string rid; - PlatformResult status = - GetString(type, record.get(), "recurrence_id", &rid); + PlatformResult status = GetString(type, record.get(), "recurrence_id", &rid); if (status.IsError()) { return status; } if (rid.length() > 0) { // @todo remove all occurrences - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "TODO: remove all occurrences"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "TODO: remove all occurrences"); } } @@ -236,15 +236,14 @@ PlatformResult CalendarItem::Remove(int type, int id) { if (CALENDAR_ERROR_NONE != ret) { LOGE("Calendar record delete error"); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Record deletion error", - ("calendar_db_delete_record error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Record deletion error", + ("calendar_db_delete_record error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::GetPlatformProperty(int type, - const std::string& property, +PlatformResult CalendarItem::GetPlatformProperty(int type, const std::string& property, unsigned int* value) { LoggerD("Enter"); if (platform_property_map_.find(property) == platform_property_map_.end()) { @@ -255,9 +254,8 @@ PlatformResult CalendarItem::GetPlatformProperty(int type, auto prop = platform_property_map_.at(property); if (prop.find(type) == prop.end()) { return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, - std::string("Property %s not defined for type ", property.c_str()) + - std::to_string(type)); + ErrorCode::INVALID_VALUES_ERR, + std::string("Property %s not defined for type ", property.c_str()) + std::to_string(type)); } *value = prop.at(type); @@ -266,8 +264,7 @@ PlatformResult CalendarItem::GetPlatformProperty(int type, } PlatformResult CalendarItem::StringToPlatformEnum(const std::string& field, - const std::string& value, - int* platform_enum) { + const std::string& value, int* platform_enum) { LoggerD("Enter"); auto iter = platform_enum_map_.find(field); if (iter == platform_enum_map_.end()) { @@ -289,13 +286,11 @@ PlatformResult CalendarItem::StringToPlatformEnum(const std::string& field, return PlatformResult(ErrorCode::NO_ERROR); } - std::string message = - "Platform enum value " + value + " not found for " + field; + std::string message = "Platform enum value " + value + " not found for " + field; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } -PlatformResult CalendarItem::PlatformEnumToString(const std::string& field, - int value, +PlatformResult CalendarItem::PlatformEnumToString(const std::string& field, int value, std::string* platform_str) { LoggerD("Enter"); // @todo can be replaced by Boost.Bimap @@ -324,29 +319,24 @@ PlatformResult CalendarItem::PlatformEnumToString(const std::string& field, return PlatformResult(ErrorCode::NO_ERROR); } - std::string message = "Platform enum value " + std::to_string(value) + - " not found for " + field; + std::string message = "Platform enum value " + std::to_string(value) + " not found for " + field; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } -PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, - const std::string& property, - const picojson::object& in, - bool optional) { +PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const std::string& property, + const picojson::object& in, bool optional) { LoggerD("set: %s", property.c_str()); if (optional && IsNull(in, property.c_str())) { return PlatformResult(ErrorCode::NO_ERROR); } - const std::string& value = - common::FromJson(in, property.c_str()); + const std::string& value = common::FromJson(in, property.c_str()); return SetString(type, rec, property, value); } -PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, - const std::string& property, +PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const std::string& property, const std::string& value) { LoggerD("set: %s", property.c_str()); @@ -366,8 +356,7 @@ PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::GetString(int type, calendar_record_h rec, - const std::string& property, +PlatformResult CalendarItem::GetString(int type, calendar_record_h rec, const std::string& property, std::string* value) { LoggerD("get: %s", property.c_str()); @@ -380,8 +369,7 @@ PlatformResult CalendarItem::GetString(int type, calendar_record_h rec, return CalendarRecord::GetString(rec, prop, value); } -PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, - const std::string& property, +PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std::string& property, const picojson::object& in, bool optional) { LoggerD("set: %s", property.c_str()); @@ -394,8 +382,8 @@ PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, return SetInt(type, rec, property, value); } -PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, - const std::string& property, int value) { +PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std::string& property, + int value) { LoggerD("set: %s", property.c_str()); unsigned int prop; @@ -407,8 +395,8 @@ PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, return CalendarRecord::SetInt(rec, prop, value); } -PlatformResult CalendarItem::GetInt(int type, calendar_record_h rec, - const std::string& property, int* value) { +PlatformResult CalendarItem::GetInt(int type, calendar_record_h rec, const std::string& property, + int* value) { LoggerD("get: %s", property.c_str()); unsigned int prop; @@ -420,10 +408,8 @@ PlatformResult CalendarItem::GetInt(int type, calendar_record_h rec, return CalendarRecord::GetInt(rec, prop, value); } -PlatformResult CalendarItem::SetEnum(int type, calendar_record_h rec, - const std::string& property, - const picojson::object& in, - const std::string& enum_name) { +PlatformResult CalendarItem::SetEnum(int type, calendar_record_h rec, const std::string& property, + const picojson::object& in, const std::string& enum_name) { LoggerD("Enter"); std::string value = common::FromJson(in, property.c_str()); @@ -441,10 +427,8 @@ PlatformResult CalendarItem::SetEnum(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::SetEnum(calendar_record_h rec, - unsigned int property, - const std::string& enum_name, - const std::string& value) { +PlatformResult CalendarItem::SetEnum(calendar_record_h rec, unsigned int property, + const std::string& enum_name, const std::string& value) { LoggerD("Enter"); int value_int; PlatformResult status = StringToPlatformEnum(enum_name, value, &value_int); @@ -460,10 +444,8 @@ PlatformResult CalendarItem::SetEnum(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::GetEnum(int type, calendar_record_h rec, - const std::string& property, - const std::string& enum_name, - std::string* enum_str) { +PlatformResult CalendarItem::GetEnum(int type, calendar_record_h rec, const std::string& property, + const std::string& enum_name, std::string* enum_str) { int value; PlatformResult status = GetInt(type, rec, property, &value); if (status.IsError()) { @@ -473,10 +455,8 @@ PlatformResult CalendarItem::GetEnum(int type, calendar_record_h rec, return PlatformEnumToString(enum_name, value, enum_str); } -PlatformResult CalendarItem::GetEnum(calendar_record_h rec, - unsigned int property, - const std::string& enum_name, - std::string* enum_str) { +PlatformResult CalendarItem::GetEnum(calendar_record_h rec, unsigned int property, + const std::string& enum_name, std::string* enum_str) { LoggerD("Enter"); int value; PlatformResult status = CalendarRecord::GetInt(rec, property, &value); @@ -487,8 +467,8 @@ PlatformResult CalendarItem::GetEnum(calendar_record_h rec, return PlatformEnumToString(enum_name, value, enum_str); } -PlatformResult CalendarItem::SetDouble(int type, calendar_record_h rec, - const std::string& property, double value) { +PlatformResult CalendarItem::SetDouble(int type, calendar_record_h rec, const std::string& property, + double value) { LoggerD("set: %s", property.c_str()); unsigned int prop; @@ -500,15 +480,14 @@ PlatformResult CalendarItem::SetDouble(int type, calendar_record_h rec, int ret = calendar_record_set_double(rec, prop, value); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set double to record failed.", - ("calendar_record_set_double error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Set double to record failed.", + ("calendar_record_set_double error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::GetDouble(int type, calendar_record_h rec, - const std::string& property, +PlatformResult CalendarItem::GetDouble(int type, calendar_record_h rec, const std::string& property, double* value) { LoggerD("get: %s", property.c_str()); @@ -521,16 +500,15 @@ PlatformResult CalendarItem::GetDouble(int type, calendar_record_h rec, int ret = calendar_record_get_double(rec, prop, value); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get int from record failed.", - ("calendar_record_get_double error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Get int from record failed.", + ("calendar_record_get_double error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult CalendarItem::SetCaltime(int type, calendar_record_h rec, - const std::string& property, - calendar_time_s value, + const std::string& property, calendar_time_s value, bool throw_on_error) { LoggerD("Enter"); unsigned int prop; @@ -542,10 +520,8 @@ PlatformResult CalendarItem::SetCaltime(int type, calendar_record_h rec, return SetCaltime(rec, prop, value, throw_on_error); } -PlatformResult CalendarItem::SetCaltime(calendar_record_h rec, - unsigned int property, - calendar_time_s value, - bool throw_on_error) { +PlatformResult CalendarItem::SetCaltime(calendar_record_h rec, unsigned int property, + calendar_time_s value, bool throw_on_error) { LoggerD("Enter"); int ret = calendar_record_set_caltime(rec, property, value); @@ -562,8 +538,7 @@ PlatformResult CalendarItem::SetCaltime(calendar_record_h rec, } PlatformResult CalendarItem::GetCaltime(int type, calendar_record_h rec, - const std::string& property, - calendar_time_s* cal_time, + const std::string& property, calendar_time_s* cal_time, bool throw_on_error) { LoggerD("get: %s", property.c_str()); @@ -576,10 +551,8 @@ PlatformResult CalendarItem::GetCaltime(int type, calendar_record_h rec, return GetCaltime(rec, prop, cal_time, throw_on_error); } -PlatformResult CalendarItem::GetCaltime(calendar_record_h rec, - unsigned int property, - calendar_time_s* cal_time, - bool throw_on_error) { +PlatformResult CalendarItem::GetCaltime(calendar_record_h rec, unsigned int property, + calendar_time_s* cal_time, bool throw_on_error) { LoggerD("Enter"); if (property != -1u) { int ret = calendar_record_get_caltime(rec, property, cal_time); @@ -595,9 +568,8 @@ PlatformResult CalendarItem::GetCaltime(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::SetLli(calendar_record_h rec, - unsigned int property, long long int value, - bool throw_on_error) { +PlatformResult CalendarItem::SetLli(calendar_record_h rec, unsigned int property, + long long int value, bool throw_on_error) { LoggerD("Enter"); int ret = calendar_record_set_lli(rec, property, value); @@ -613,8 +585,7 @@ PlatformResult CalendarItem::SetLli(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::GetLli(int type, calendar_record_h rec, - const std::string& property, +PlatformResult CalendarItem::GetLli(int type, calendar_record_h rec, const std::string& property, long long int* lli) { LoggerD("get: %s", property.c_str()); @@ -627,9 +598,8 @@ PlatformResult CalendarItem::GetLli(int type, calendar_record_h rec, return GetLli(rec, prop, lli); } -PlatformResult CalendarItem::GetLli(calendar_record_h rec, - unsigned int property, long long int* value, - bool throw_on_error) { +PlatformResult CalendarItem::GetLli(calendar_record_h rec, unsigned int property, + long long int* value, bool throw_on_error) { LoggerD("Enter"); int ret = calendar_record_get_lli(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { @@ -648,8 +618,7 @@ Date CalendarItem::DateFromJson(const picojson::object& in) { Date date = {(long long int)common::FromJson(in, "UTCTimestamp"), (int)common::FromJson(in, "year"), - (int)common::FromJson(in, "month"), - (int)common::FromJson(in, "day"), + (int)common::FromJson(in, "month"), (int)common::FromJson(in, "day"), common::FromJson(in, "timezone")}; return date; @@ -666,8 +635,7 @@ picojson::value CalendarItem::DateToJson(Date* date) { picojson::value date_val = picojson::value(picojson::object()); picojson::object& date_obj = date_val.get(); - date_obj["UTCTimestamp"] = - picojson::value(static_cast(date->utc_timestamp_)); + date_obj["UTCTimestamp"] = picojson::value(static_cast(date->utc_timestamp_)); date_obj["year"] = picojson::value(static_cast(date->year_)); date_obj["month"] = picojson::value(static_cast(date->month_)); date_obj["day"] = picojson::value(static_cast(date->day_)); @@ -729,22 +697,19 @@ PlatformResult CalendarItem::AttendeesFromJson(int type, calendar_record_h rec, int ret = calendar_record_create(_calendar_attendee._uri, &attendee); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Fail to create attendee record", - ("Fail to create attendee record, error code: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Fail to create attendee record", + ("Fail to create attendee record, error code: %d (%s)", ret, get_error_message(ret))); } - PlatformResult status = - CalendarRecord::SetString(attendee, _calendar_attendee.email, - common::FromJson(obj, "uri")); + PlatformResult status = CalendarRecord::SetString(attendee, _calendar_attendee.email, + common::FromJson(obj, "uri")); if (status.IsError()) { return status; } if (!IsNull(obj, "name")) { - status = - CalendarRecord::SetString(attendee, _calendar_attendee.name, - common::FromJson(obj, "name")); + status = CalendarRecord::SetString(attendee, _calendar_attendee.name, + common::FromJson(obj, "name")); if (status.IsError()) { return status; } @@ -782,26 +747,24 @@ PlatformResult CalendarItem::AttendeesFromJson(int type, calendar_record_h rec, } } if (!IsNull(obj, "delegatorURI")) { - status = CalendarRecord::SetString( - attendee, _calendar_attendee.delegator_uri, - common::FromJson(obj, "delegatorURI")); + status = CalendarRecord::SetString(attendee, _calendar_attendee.delegator_uri, + common::FromJson(obj, "delegatorURI")); if (status.IsError()) { return status; } } if (!IsNull(obj, "delegateURI")) { - status = CalendarRecord::SetString( - attendee, _calendar_attendee.delegatee_uri, - common::FromJson(obj, "delegateURI")); + status = CalendarRecord::SetString(attendee, _calendar_attendee.delegatee_uri, + common::FromJson(obj, "delegateURI")); if (status.IsError()) { return status; } } if (!IsNull(obj, "contactRef")) { - status = CalendarRecord::SetString( - attendee, _calendar_attendee.uid, - common::FromJson(obj, "contactRef", "contactId")); + status = + CalendarRecord::SetString(attendee, _calendar_attendee.uid, + common::FromJson(obj, "contactRef", "contactId")); if (status.IsError()) { return status; } @@ -851,9 +814,8 @@ PlatformResult CalendarItem::AttendeesToJson(int type, calendar_record_h rec, int ret = calendar_record_clone_child_record_list(rec, property, &list); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't get attendee list", - ("calendar_record_clone_child_record_list error: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Can't get attendee list", + ("calendar_record_clone_child_record_list error: %d (%s)", ret, get_error_message(ret))); } CalendarListPtr(list, CalendarRecord::ListDeleter); @@ -870,66 +832,58 @@ PlatformResult CalendarItem::AttendeesToJson(int type, calendar_record_h rec, picojson::object& attendee_obj = attendee_val.get(); std::string value_str; - PlatformResult status = CalendarRecord::GetString( - attendee, _calendar_attendee.email, &value_str); + PlatformResult status = + CalendarRecord::GetString(attendee, _calendar_attendee.email, &value_str); if (status.IsError()) { return status; } attendee_obj["uri"] = picojson::value(value_str); - status = CalendarRecord::GetString(attendee, _calendar_attendee.name, - &value_str); + status = CalendarRecord::GetString(attendee, _calendar_attendee.name, &value_str); if (status.IsError()) { return status; } attendee_obj["name"] = picojson::value(value_str); std::string enum_str; - status = - GetEnum(attendee, _calendar_attendee.role, kAttendeeRole, &enum_str); + status = GetEnum(attendee, _calendar_attendee.role, kAttendeeRole, &enum_str); if (status.IsError()) { return status; } attendee_obj["role"] = picojson::value(enum_str); - status = GetEnum(attendee, _calendar_attendee.status, kAttendeeStatus, - &enum_str); + status = GetEnum(attendee, _calendar_attendee.status, kAttendeeStatus, &enum_str); if (status.IsError()) { return status; } attendee_obj["status"] = picojson::value(enum_str); int value_int; - status = - CalendarRecord::GetInt(attendee, _calendar_attendee.rsvp, &value_int); + status = CalendarRecord::GetInt(attendee, _calendar_attendee.rsvp, &value_int); if (status.IsError()) { return status; } attendee_obj["RSVP"] = picojson::value(static_cast(value_int)); - status = - GetEnum(attendee, _calendar_attendee.cutype, kAttendeeType, &enum_str); + status = GetEnum(attendee, _calendar_attendee.cutype, kAttendeeType, &enum_str); if (status.IsError()) { return status; } attendee_obj["type"] = picojson::value(enum_str); - status = CalendarRecord::GetString(attendee, _calendar_attendee.group, - &value_str); + status = CalendarRecord::GetString(attendee, _calendar_attendee.group, &value_str); if (status.IsError()) { return status; } attendee_obj["group"] = picojson::value(value_str); - status = CalendarRecord::GetString( - attendee, _calendar_attendee.delegator_uri, &value_str); + status = CalendarRecord::GetString(attendee, _calendar_attendee.delegator_uri, &value_str); if (status.IsError()) { return status; } attendee_obj["delegatorURI"] = picojson::value(value_str); - status = CalendarRecord::GetString( - attendee, _calendar_attendee.delegatee_uri, &value_str); + status = CalendarRecord::GetString(attendee, _calendar_attendee.delegatee_uri, &value_str); if (status.IsError()) { return status; } @@ -937,22 +891,20 @@ PlatformResult CalendarItem::AttendeesToJson(int type, calendar_record_h rec, // contactRef std::string contact_id; - status = CalendarRecord::GetString(attendee, _calendar_attendee.uid, - &contact_id); + status = CalendarRecord::GetString(attendee, _calendar_attendee.uid, &contact_id); if (status.IsError()) { return status; } int book_id; - status = CalendarRecord::GetInt(attendee, _calendar_attendee.person_id, - &book_id); + status = CalendarRecord::GetInt(attendee, _calendar_attendee.person_id, &book_id); if (status.IsError()) { return status; } attendee_obj["contactRef"] = picojson::value( picojson::object{{"contactId", picojson::value(contact_id)}, - {"addressBookId", picojson::value(std::to_string(book_id))}}); + {"addressBookId", picojson::value(std::to_string(book_id))}}); out->push_back(attendee_val); } @@ -979,23 +931,20 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, int ret = calendar_record_create(_calendar_alarm._uri, &alarm); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Fail to create attendee record", - ("Fail to create attendee record, error: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Fail to create attendee record", + ("Fail to create attendee record, error: %d (%s)", ret, get_error_message(ret))); } int tick_unit = CALENDAR_ALARM_TIME_UNIT_SPECIFIC; if (!common::IsNull(obj, "absoluteDate")) { Date absolute = DateFromJson(obj, "absoluteDate"); calendar_time_s absolute_date = DateToPlatform(absolute, false); - PlatformResult status = - SetCaltime(alarm, _calendar_alarm.alarm_time, absolute_date); + PlatformResult status = SetCaltime(alarm, _calendar_alarm.alarm_time, absolute_date); if (status.IsError()) { return status; } - status = - CalendarRecord::SetInt(alarm, _calendar_alarm.tick_unit, tick_unit); + status = CalendarRecord::SetInt(alarm, _calendar_alarm.tick_unit, tick_unit); if (status.IsError()) { return status; } @@ -1003,12 +952,10 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, if (!common::IsNull(obj, "before")) { long long length = common::FromJson(obj, "before", "length"); - const std::string& unit = - common::FromJson(obj, "before", "unit"); + const std::string& unit = common::FromJson(obj, "before", "unit"); long long tick = 0; if (kTimeDurationUnitMilliseconds == unit) { - tick_unit = - CALENDAR_ALARM_TIME_UNIT_MINUTE; // minimum calendar time unit. + tick_unit = CALENDAR_ALARM_TIME_UNIT_MINUTE; // minimum calendar time unit. tick = length / 60000; } else if (kTimeDurationUnitSeconds == unit) { tick_unit = CALENDAR_ALARM_TIME_UNIT_MINUTE; @@ -1026,14 +973,12 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, LoggerW("Wrong alarm time unit: %s", unit.c_str()); } - PlatformResult status = - CalendarRecord::SetInt(alarm, _calendar_alarm.tick, tick); + PlatformResult status = CalendarRecord::SetInt(alarm, _calendar_alarm.tick, tick); if (status.IsError()) { return status; } - status = - CalendarRecord::SetInt(alarm, _calendar_alarm.tick_unit, tick_unit); + status = CalendarRecord::SetInt(alarm, _calendar_alarm.tick_unit, tick_unit); if (status.IsError()) { return status; } @@ -1046,15 +991,13 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, method = it_method->second.get(); } - PlatformResult status = - SetEnum(alarm, _calendar_alarm.action, kAlarmMethod, method); + PlatformResult status = SetEnum(alarm, _calendar_alarm.action, kAlarmMethod, method); if (status.IsError()) { return status; } - status = CalendarRecord::SetString( - alarm, _calendar_alarm.description, - common::FromJson(obj, "description")); + status = CalendarRecord::SetString(alarm, _calendar_alarm.description, + common::FromJson(obj, "description")); if (status.IsError()) { return status; } @@ -1068,8 +1011,7 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, - picojson::array* out) { +PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, picojson::array* out) { LoggerD("Enter"); unsigned int property; if (type == CALENDAR_BOOK_TYPE_EVENT) { @@ -1091,9 +1033,8 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, calendar_list_h list; int ret = calendar_record_clone_child_record_list(rec, property, &list); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Can't get alarms list", - ("Can't get alarms list %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Can't get alarms list", + ("Can't get alarms list %d (%s)", ret, get_error_message(ret))); } CalendarListPtr(list, CalendarRecord::ListDeleter); @@ -1110,8 +1051,7 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, picojson::value alarm_val = picojson::value(picojson::object()); picojson::object& alarm_obj = alarm_val.get(); - PlatformResult status = - CalendarRecord::GetInt(alarm, _calendar_alarm.tick_unit, &tick_unit); + PlatformResult status = CalendarRecord::GetInt(alarm, _calendar_alarm.tick_unit, &tick_unit); if (status.IsError()) { return status; } @@ -1148,9 +1088,9 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, LoggerW("Wrong tick unit: %d", tick_unit); } - alarm_obj["before"] = picojson::value( - picojson::object{{"length", picojson::value(static_cast(length))}, - {"unit", picojson::value(unit)}}); + alarm_obj["before"] = + picojson::value(picojson::object{{"length", picojson::value(static_cast(length))}, + {"unit", picojson::value(unit)}}); } std::string enum_str; @@ -1161,8 +1101,7 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, alarm_obj["method"] = picojson::value(enum_str); std::string value_str; - status = CalendarRecord::GetString(alarm, _calendar_alarm.description, - &value_str); + status = CalendarRecord::GetString(alarm, _calendar_alarm.description, &value_str); alarm_obj["description"] = picojson::value(value_str); if (status.IsError()) { return status; @@ -1174,14 +1113,11 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::RecurrenceRuleFromJson( - calendar_record_h rec, const picojson::object& rrule) { - +PlatformResult CalendarItem::RecurrenceRuleFromJson(calendar_record_h rec, + const picojson::object& rrule) { LoggerD("Enter"); - const std::string& frequency = - common::FromJson(rrule, "frequency"); - PlatformResult status = - SetEnum(rec, _calendar_event.freq, kRecurrenceRuleFrequency, frequency); + const std::string& frequency = common::FromJson(rrule, "frequency"); + PlatformResult status = SetEnum(rec, _calendar_event.freq, kRecurrenceRuleFrequency, frequency); if (status.IsError()) { return status; } @@ -1198,11 +1134,9 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( // are set, recurrence rule's type will be UNTIL // TODO: specify the correct behavior in WIDL, update the code accordingly - const long occurrence_count = - common::FromJson(rrule, "occurrenceCount"); + const long occurrence_count = common::FromJson(rrule, "occurrenceCount"); if (-1 != occurrence_count) { - status = - CalendarRecord::SetInt(rec, _calendar_event.count, occurrence_count); + status = CalendarRecord::SetInt(rec, _calendar_event.count, occurrence_count); if (status.IsError()) { return status; } @@ -1212,8 +1146,7 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( if (!common::IsNull(rrule, "untilDate")) { Date until = DateFromJson(rrule, "untilDate"); - status = SetCaltime(rec, _calendar_event.until_time, - DateToPlatform(until, false)); + status = SetCaltime(rec, _calendar_event.until_time, DateToPlatform(until, false)); if (status.IsError()) { return status; } @@ -1221,14 +1154,12 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( range_type = CALENDAR_RANGE_UNTIL; } - status = CalendarRecord::SetInt(rec, _calendar_event.range_type, - range_type); + status = CalendarRecord::SetInt(rec, _calendar_event.range_type, range_type); if (status.IsError()) { return status; } - const picojson::array& byday_array = - common::FromJson(rrule, "daysOfTheWeek"); + const picojson::array& byday_array = common::FromJson(rrule, "daysOfTheWeek"); std::string byday; for (auto iter = byday_array.begin(); iter != byday_array.end(); ++iter) { if (iter == byday_array.begin()) { @@ -1242,11 +1173,9 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( return status; } - const picojson::array& bysetpos_array = - common::FromJson(rrule, "setPositions"); + const picojson::array& bysetpos_array = common::FromJson(rrule, "setPositions"); std::string bysetpos; - for (auto iter = bysetpos_array.begin(); iter != bysetpos_array.end(); - ++iter) { + for (auto iter = bysetpos_array.begin(); iter != bysetpos_array.end(); ++iter) { if (iter == bysetpos_array.begin()) { bysetpos.append(std::to_string((int)iter->get())); } else { @@ -1260,8 +1189,7 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( status = CalendarRecord::SetString( rec, _calendar_event.exdate, - ExceptionsFromJson( - common::FromJson(rrule, "exceptions"))); + ExceptionsFromJson(common::FromJson(rrule, "exceptions"))); if (status.IsError()) { return status; } @@ -1269,8 +1197,7 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson( return PlatformResult(ErrorCode::NO_ERROR); } -std::string CalendarItem::ExceptionsFromJson(const picojson::array &exceptions) { - +std::string CalendarItem::ExceptionsFromJson(const picojson::array& exceptions) { LoggerD("Enter"); std::string result; Date date; @@ -1296,16 +1223,14 @@ PlatformResult CalendarItem::RecurrenceRuleToJson(calendar_record_h rec, picojson::object& out = *out_ptr; std::string enum_str; - PlatformResult status = - GetEnum(rec, _calendar_event.freq, kRecurrenceRuleFrequency, &enum_str); + PlatformResult status = GetEnum(rec, _calendar_event.freq, kRecurrenceRuleFrequency, &enum_str); if (status.IsError()) { return status; } out["frequency"] = picojson::value(enum_str); int interval; - status = - CalendarRecord::GetInt(rec, _calendar_event.interval, &interval); + status = CalendarRecord::GetInt(rec, _calendar_event.interval, &interval); if (status.IsError()) { return status; } @@ -1335,8 +1260,7 @@ PlatformResult CalendarItem::RecurrenceRuleToJson(calendar_record_h rec, int ret = calendar_record_get_caltime(rec, _calendar_event.until_time, &cal); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get caltime from record failed."); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get caltime from record failed."); } if (cal.time.utime > 0 && CALENDAR_RECORD_NO_UNTIL != cal.time.utime) { @@ -1375,8 +1299,7 @@ PlatformResult CalendarItem::RecurrenceRuleToJson(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -calendar_time_s CalendarItem::DateToPlatform(const Date& date, - bool is_all_day) { +calendar_time_s CalendarItem::DateToPlatform(const Date& date, bool is_all_day) { LoggerD("Enter"); calendar_time_s cal; @@ -1416,8 +1339,7 @@ PlatformResult CalendarItem::DateFromPlatform(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::DateFromPlatform(calendar_record_h rec, - unsigned int property, +PlatformResult CalendarItem::DateFromPlatform(calendar_record_h rec, unsigned int property, Date* date_from_platform) { LoggerD("Enter"); calendar_time_s cal; @@ -1435,12 +1357,10 @@ PlatformResult CalendarItem::DateFromPlatform(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, - const picojson::object& in) { +PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, const picojson::object& in) { LoggerD("Enter"); if (in.empty()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Empty Calendar object."); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Empty Calendar object."); } PlatformResult status = SetString(type, rec, "description", in, true); @@ -1465,12 +1385,10 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, int is_all_day = common::FromJson(in, "isAllDay"); const std::string& start_property = "startDate"; - const std::string& end_property = - (type == CALENDAR_BOOK_TYPE_EVENT) ? "endDate" : "dueDate"; + const std::string& end_property = (type == CALENDAR_BOOK_TYPE_EVENT) ? "endDate" : "dueDate"; std::string start_label = start_property; - if (common::IsNull(in, start_property.c_str()) - && !common::IsNull(in, end_property.c_str())) { + if (common::IsNull(in, start_property.c_str()) && !common::IsNull(in, end_property.c_str())) { // start date is not set, but end date is present, use it instead start_label = end_property; } @@ -1478,8 +1396,7 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, if (!common::IsNull(in, start_label.c_str())) { Date start = DateFromJson(in, start_label.c_str()); - status = SetCaltime(type, rec, "startDate_time", - DateToPlatform(start, is_all_day)); + status = SetCaltime(type, rec, "startDate_time", DateToPlatform(start, is_all_day)); if (status.IsError()) { return status; } @@ -1491,8 +1408,7 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, } std::string end_label = end_property; - if (!common::IsNull(in, start_property.c_str()) - && common::IsNull(in, end_property.c_str())) { + if (!common::IsNull(in, start_property.c_str()) && common::IsNull(in, end_property.c_str())) { // end date is not set, but start date is present, use it instead end_label = start_property; } @@ -1500,8 +1416,7 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, if (!common::IsNull(in, end_label.c_str())) { Date end = DateFromJson(in, end_label.c_str()); - status = SetCaltime(type, rec, end_property + "_time", - DateToPlatform(end, is_all_day)); + status = SetCaltime(type, rec, end_property + "_time", DateToPlatform(end, is_all_day)); if (status.IsError()) { return status; } @@ -1519,34 +1434,29 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, if (!common::IsNull(in, "geolocation")) { PlatformResult status = - SetDouble(type, rec, "latitude", - common::FromJson(in, "geolocation", "latitude")); + SetDouble(type, rec, "latitude", common::FromJson(in, "geolocation", "latitude")); if (status.IsError()) { return status; } status = - SetDouble(type, rec, "longitude", - common::FromJson(in, "geolocation", "longitude")); + SetDouble(type, rec, "longitude", common::FromJson(in, "geolocation", "longitude")); if (status.IsError()) { return status; } } - status = CategoriesFromJson( - type, rec, common::FromJson(in, "categories")); + status = CategoriesFromJson(type, rec, common::FromJson(in, "categories")); if (status.IsError()) { return status; } - status = AttendeesFromJson( - type, rec, common::FromJson(in, "attendees")); + status = AttendeesFromJson(type, rec, common::FromJson(in, "attendees")); if (status.IsError()) { return status; } - status = AlarmsFromJson(type, rec, - common::FromJson(in, "alarms")); + status = AlarmsFromJson(type, rec, common::FromJson(in, "alarms")); if (status.IsError()) { return status; } @@ -1568,8 +1478,8 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, } if (!common::IsNull(in, "recurrenceRule")) { - status = RecurrenceRuleFromJson( - rec, common::FromJson(in, "recurrenceRule")); + status = + RecurrenceRuleFromJson(rec, common::FromJson(in, "recurrenceRule")); if (status.IsError()) { return status; } @@ -1587,9 +1497,8 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, } if (!common::IsNull(in, "completedDate")) { - PlatformResult status = - SetLli(rec, _calendar_todo.completed_time, - DateFromJson(in, "completedDate").utc_timestamp_); + PlatformResult status = SetLli(rec, _calendar_todo.completed_time, + DateFromJson(in, "completedDate").utc_timestamp_); if (status.IsError()) { return status; } @@ -1604,8 +1513,7 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, - picojson::object* out_ptr) { +PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, picojson::object* out_ptr) { LoggerD("Enter"); if (NULL == rec) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Calendar record is null"); @@ -1684,12 +1592,11 @@ PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, // startDate Date date_from_platform; status = DateFromPlatform(type, rec, "startDate", &date_from_platform); - if (status.IsError())return status; + if (status.IsError()) return status; out["startDate"] = DateToJson(&date_from_platform); // endDate / dueDate - const std::string& endProperty = - (type == CALENDAR_BOOK_TYPE_EVENT) ? "endDate" : "dueDate"; + const std::string& endProperty = (type == CALENDAR_BOOK_TYPE_EVENT) ? "endDate" : "dueDate"; status = DateFromPlatform(type, rec, endProperty, &date_from_platform); if (status.IsError()) { return status; @@ -1715,9 +1622,8 @@ PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, return status; } - out["geolocation"] = picojson::value( - picojson::object({{"latitude", picojson::value(latitude)}, - {"longitude", picojson::value(longitude)}})); + out["geolocation"] = picojson::value(picojson::object( + {{"latitude", picojson::value(latitude)}, {"longitude", picojson::value(longitude)}})); std::string enum_str; status = GetEnum(type, rec, "visibility", kItemVisibility, &enum_str); @@ -1796,7 +1702,7 @@ PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, if (status.IsError()) { return status; } - out["priority"] = picojson::value(enum_str); + out["priority"] = picojson::value(enum_str); long long int lli; status = GetLli(rec, _calendar_todo.completed_time, &lli); diff --git a/src/calendar/calendar_item.h b/src/calendar/calendar_item.h index 9666c11..a689a10 100644 --- a/src/calendar/calendar_item.h +++ b/src/calendar/calendar_item.h @@ -34,102 +34,74 @@ struct Date { typedef std::map> PlatformPropertyMap; typedef std::map> PlatformEnumMap; -typedef std::map> - PlatformEnumReverseMap; +typedef std::map> PlatformEnumReverseMap; class CalendarItem : public CalendarRecord { public: - static common::PlatformResult Create(int type, calendar_record_h *handle); + static common::PlatformResult Create(int type, calendar_record_h* handle); static common::PlatformResult Remove(int type, int id); - static common::PlatformResult GetPlatformProperty(int type, - const std::string& property, + static common::PlatformResult GetPlatformProperty(int type, const std::string& property, unsigned int* value); static common::PlatformResult StringToPlatformEnum(const std::string& type, - const std::string& value, - int* platform_enum); - static common::PlatformResult PlatformEnumToString(const std::string& field, - int value, + const std::string& value, int* platform_enum); + static common::PlatformResult PlatformEnumToString(const std::string& field, int value, std::string* platform_str); // string static common::PlatformResult SetString(int type, calendar_record_h rec, - const std::string& property, - const picojson::object& in, + const std::string& property, const picojson::object& in, bool optional = false); static common::PlatformResult SetString(int type, calendar_record_h rec, - const std::string& property, - const std::string& value); + const std::string& property, const std::string& value); static common::PlatformResult GetString(int type, calendar_record_h rec, - const std::string& property, - std::string* value); + const std::string& property, std::string* value); // int - static common::PlatformResult SetInt(int type, calendar_record_h rec, - const std::string& property, - const picojson::object& in, - bool optional = false); - static common::PlatformResult SetInt(int type, calendar_record_h rec, - const std::string& property, int value); - static common::PlatformResult GetInt(int type, calendar_record_h rec, - const std::string& property, int* value); + static common::PlatformResult SetInt(int type, calendar_record_h rec, const std::string& property, + const picojson::object& in, bool optional = false); + static common::PlatformResult SetInt(int type, calendar_record_h rec, const std::string& property, + int value); + static common::PlatformResult GetInt(int type, calendar_record_h rec, const std::string& property, + int* value); // enum static common::PlatformResult SetEnum(int type, calendar_record_h rec, - const std::string& property, - const picojson::object& in, + const std::string& property, const picojson::object& in, const std::string& enum_name); - static common::PlatformResult SetEnum(calendar_record_h rec, - unsigned int property, - const std::string& enum_name, - const std::string& value); + static common::PlatformResult SetEnum(calendar_record_h rec, unsigned int property, + const std::string& enum_name, const std::string& value); static common::PlatformResult GetEnum(int type, calendar_record_h rec, - const std::string& property, - const std::string& enum_name, - std::string* enum_str); - static common::PlatformResult GetEnum(calendar_record_h rec, - unsigned int property, - const std::string& enum_name, + const std::string& property, const std::string& enum_name, std::string* enum_str); + static common::PlatformResult GetEnum(calendar_record_h rec, unsigned int property, + const std::string& enum_name, std::string* enum_str); // double static common::PlatformResult SetDouble(int type, calendar_record_h rec, - const std::string& property, - double value); + const std::string& property, double value); static common::PlatformResult GetDouble(int type, calendar_record_h rec, - const std::string& property, - double *value); + const std::string& property, double* value); // calendar_time_s static common::PlatformResult SetCaltime(int type, calendar_record_h rec, - const std::string& property, - calendar_time_s value, - bool throw_on_error = true); - static common::PlatformResult SetCaltime(calendar_record_h rec, - unsigned int property, - calendar_time_s value, + const std::string& property, calendar_time_s value, bool throw_on_error = true); + static common::PlatformResult SetCaltime(calendar_record_h rec, unsigned int property, + calendar_time_s value, bool throw_on_error = true); static common::PlatformResult GetCaltime(int type, calendar_record_h rec, - const std::string& property, - calendar_time_s * cal_time, - bool throw_on_error = true); - static common::PlatformResult GetCaltime(calendar_record_h rec, - unsigned int property, - calendar_time_s * cal_time, + const std::string& property, calendar_time_s* cal_time, bool throw_on_error = true); + static common::PlatformResult GetCaltime(calendar_record_h rec, unsigned int property, + calendar_time_s* cal_time, bool throw_on_error = true); // long long int - static common::PlatformResult SetLli(calendar_record_h rec, - unsigned int property, - long long int value, - bool throw_on_error = true); - static common::PlatformResult GetLli(int type, calendar_record_h rec, - const std::string& property, + static common::PlatformResult SetLli(calendar_record_h rec, unsigned int property, + long long int value, bool throw_on_error = true); + static common::PlatformResult GetLli(int type, calendar_record_h rec, const std::string& property, long long int* lli); - static common::PlatformResult GetLli(calendar_record_h rec, - unsigned int property, - long long int* value, - bool throw_on_error = true); + static common::PlatformResult GetLli(calendar_record_h rec, unsigned int property, + long long int* value, bool throw_on_error = true); // conversions static common::PlatformResult FromJson(int type, calendar_record_h record, @@ -138,42 +110,36 @@ class CalendarItem : public CalendarRecord { picojson::object* out_ptr); static std::string ExceptionsFromJson(const picojson::array& exceptions); - static Date DateFromJson(const picojson::object& in); - static Date DateFromJson(const picojson::object& in, - const char* obj_name); - static calendar_time_s DateToPlatform(const Date& date, bool is_all_day); + static Date DateFromJson(const picojson::object& in); + static Date DateFromJson(const picojson::object& in, const char* obj_name); + static calendar_time_s DateToPlatform(const Date& date, bool is_all_day); private: // from JSON to platform - static common::PlatformResult CategoriesFromJson( - int type, calendar_record_h rec, const picojson::array& value); - static common::PlatformResult AttendeesFromJson(int type, - calendar_record_h rec, + static common::PlatformResult CategoriesFromJson(int type, calendar_record_h rec, + const picojson::array& value); + static common::PlatformResult AttendeesFromJson(int type, calendar_record_h rec, const picojson::array& value); static common::PlatformResult AlarmsFromJson(int type, calendar_record_h rec, const picojson::array& alarms); - static common::PlatformResult RecurrenceRuleFromJson( - calendar_record_h rec, const picojson::object& rrule); + static common::PlatformResult RecurrenceRuleFromJson(calendar_record_h rec, + const picojson::object& rrule); // from platform to JSON - static picojson::value DateToJson(Date *date); - static common::PlatformResult CategoriesToJson(int type, - calendar_record_h rec, + static picojson::value DateToJson(Date* date); + static common::PlatformResult CategoriesToJson(int type, calendar_record_h rec, picojson::array* value); static common::PlatformResult AttendeesToJson(int type, calendar_record_h rec, picojson::array* out); - static common::PlatformResult AlarmsToJson(int type, calendar_record_h rec, - picojson::array* out); + static common::PlatformResult AlarmsToJson(int type, calendar_record_h rec, picojson::array* out); static common::PlatformResult RecurrenceRuleToJson(calendar_record_h rec, picojson::object* out_ptr); - static common::PlatformResult DateFromPlatform(int type, - calendar_record_h rec, + static common::PlatformResult DateFromPlatform(int type, calendar_record_h rec, const std::string& property, Date* date_from_platform); - static common::PlatformResult DateFromPlatform(calendar_record_h rec, - unsigned int property, + static common::PlatformResult DateFromPlatform(calendar_record_h rec, unsigned int property, Date* date_from_platform); static picojson::array StringToArray(const std::string& string); diff --git a/src/calendar/calendar_manager.cc b/src/calendar/calendar_manager.cc old mode 100755 new mode 100644 index 3a7ed27..5de0579 --- a/src/calendar/calendar_manager.cc +++ b/src/calendar/calendar_manager.cc @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "calendar_manager.h" -#include "calendar_record.h" #include "calendar_privilege.h" +#include "calendar_record.h" -#include -#include #include +#include +#include #include "calendar_record.h" -#include "common/task-queue.h" #include "common/converter.h" #include "common/logger.h" +#include "common/task-queue.h" namespace extension { namespace calendar { @@ -63,10 +63,11 @@ CalendarManager& CalendarManager::GetInstance() { return instance; } -bool CalendarManager::IsConnected() { return is_connected_; } +bool CalendarManager::IsConnected() { + return is_connected_; +} -PlatformResult CalendarManager::GetCalendars(const JsonObject& args, - JsonArray& array) { +PlatformResult CalendarManager::GetCalendars(const JsonObject& args, JsonArray& array) { LoggerD("Enter"); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); @@ -79,8 +80,7 @@ PlatformResult CalendarManager::GetCalendars(const JsonObject& args, calendar_list_h list = NULL; CalendarListPtr list_ptr = CalendarListPtr(list, CalendarRecord::ListDeleter); int ret = calendar_db_get_all_records(_calendar_book._uri, 0, 0, &list); - PlatformResult status = - CalendarRecord::CheckReturn(ret, "Failed to get list"); + PlatformResult status = CalendarRecord::CheckReturn(ret, "Failed to get list"); if (status.IsError()) { return status; } @@ -95,8 +95,7 @@ PlatformResult CalendarManager::GetCalendars(const JsonObject& args, LoggerD("Calendar list count: %d", count); ret = calendar_list_first(list); - status = CalendarRecord::CheckReturn( - ret, "Failed to move list to the first position"); + status = CalendarRecord::CheckReturn(ret, "Failed to move list to the first position"); if (status.IsError()) { return status; } @@ -112,23 +111,22 @@ PlatformResult CalendarManager::GetCalendars(const JsonObject& args, return status; } - PlatformResult status = CalendarRecord::GetInt( - calendar, _calendar_book.store_type, &store_type); + PlatformResult status = + CalendarRecord::GetInt(calendar, _calendar_book.store_type, &store_type); if (status.IsError()) { return status; } if (current_calendar_type != store_type) { - LoggerD("Different store type %d, requested: %d. Skipping...", - store_type, current_calendar_type); + LoggerD("Different store type %d, requested: %d. Skipping...", store_type, + current_calendar_type); calendar_list_next(list); continue; } array.push_back(JsonValue(JsonObject())); - status = CalendarRecord::CalendarToJson(calendar, - &array.back().get()); + status = CalendarRecord::CalendarToJson(calendar, &array.back().get()); if (status.IsError()) { return status; } @@ -139,8 +137,7 @@ PlatformResult CalendarManager::GetCalendars(const JsonObject& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarManager::GetCalendar(const JsonObject& args, - JsonObject& out) { +PlatformResult CalendarManager::GetCalendar(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); @@ -149,27 +146,23 @@ PlatformResult CalendarManager::GetCalendar(const JsonObject& args, int id = common::stol(FromJson(args, "id")); calendar_record_h handle = nullptr; - PlatformResult status = - CalendarRecord::GetById(id, _calendar_book._uri, &handle); + PlatformResult status = CalendarRecord::GetById(id, _calendar_book._uri, &handle); if (status.IsError()) { return status; } - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); int type = CalendarRecord::TypeToInt(FromJson(args, "type")); int calendar_type; - status = CalendarRecord::GetInt(record_ptr.get(), _calendar_book.store_type, - &calendar_type); + status = CalendarRecord::GetInt(record_ptr.get(), _calendar_book.store_type, &calendar_type); if (status.IsError()) { return status; } if (type != calendar_type) { - return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Calendar not found", - ("Calendar type doesn't match requested type %s", type)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Calendar not found", + ("Calendar type doesn't match requested type %s", type)); } status = CalendarRecord::CalendarToJson(record_ptr.get(), &out); @@ -180,8 +173,7 @@ PlatformResult CalendarManager::GetCalendar(const JsonObject& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarManager::AddCalendar(const JsonObject& args, - JsonObject& out) { +PlatformResult CalendarManager::AddCalendar(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); @@ -195,8 +187,7 @@ PlatformResult CalendarManager::AddCalendar(const JsonObject& args, return status; } - CalendarRecordPtr record_ptr = - CalendarRecordPtr(handle, CalendarRecord::Deleter); + CalendarRecordPtr record_ptr = CalendarRecordPtr(handle, CalendarRecord::Deleter); status = CalendarRecord::CalendarFromJson(record_ptr.get(), calendar); if (status.IsError()) { @@ -205,17 +196,15 @@ PlatformResult CalendarManager::AddCalendar(const JsonObject& args, int ret, record_id; ret = calendar_db_insert_record(record_ptr.get(), &record_id); - status = CalendarRecord::CheckReturn( - ret, "Failed to insert calendar record into db"); + status = CalendarRecord::CheckReturn(ret, "Failed to insert calendar record into db"); if (status.IsError()) { return status; -} + } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarManager::RemoveCalendar(const JsonObject& args, - JsonObject& out) { +PlatformResult CalendarManager::RemoveCalendar(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); @@ -224,8 +213,7 @@ PlatformResult CalendarManager::RemoveCalendar(const JsonObject& args, int id = common::stol(FromJson(args, "id")); if (id == kUnifiedCalendardId) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Unified calendar can not be deleted"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Unified calendar can not be deleted"); } else if (id == DEFAULT_EVENT_CALENDAR_BOOK_ID) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Default event calendar can not be deleted"); @@ -235,8 +223,7 @@ PlatformResult CalendarManager::RemoveCalendar(const JsonObject& args, } int ret = calendar_db_delete_record(_calendar_book._uri, id); - PlatformResult status = - CalendarRecord::CheckReturn(ret, "Failed to delete record from db"); + PlatformResult status = CalendarRecord::CheckReturn(ret, "Failed to delete record from db"); if (status.IsError()) { return status; } diff --git a/src/calendar/calendar_manager.h b/src/calendar/calendar_manager.h index 5e8e250..eae1c9e 100644 --- a/src/calendar/calendar_manager.h +++ b/src/calendar/calendar_manager.h @@ -50,8 +50,7 @@ class CalendarManager { common::PlatformResult GetCalendars(const JsonObject& args, JsonArray& array); common::PlatformResult GetCalendar(const JsonObject& args, JsonObject& out); common::PlatformResult AddCalendar(const JsonObject& args, JsonObject& out); - common::PlatformResult RemoveCalendar(const JsonObject& args, - JsonObject& out); + common::PlatformResult RemoveCalendar(const JsonObject& args, JsonObject& out); static CalendarManager& GetInstance(); virtual ~CalendarManager(); diff --git a/src/calendar/calendar_plugin.cc b/src/calendar/calendar_plugin.cc old mode 100755 new mode 100644 index dbe8ec6..cf466e7 --- a/src/calendar/calendar_plugin.cc +++ b/src/calendar/calendar_plugin.cc @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "native-plugin.h" -#include "calendar_manager.h" #include "calendar.h" +#include "calendar_manager.h" +#include "native-plugin.h" namespace webapi { namespace calendar { @@ -40,59 +40,49 @@ CalendarPlugin::CalendarPlugin() { calendar_ = &Calendar::GetInstance(); } -CalendarPlugin::~CalendarPlugin() { manager_ = nullptr; } +CalendarPlugin::~CalendarPlugin() { + manager_ = nullptr; +} void CalendarPlugin::OnLoad() { using std::placeholders::_1; using std::placeholders::_2; - dispatcher_.AddFunction( - "CalendarManager_getCalendars", - std::bind(&CalendarManager::GetCalendars, manager_, _1, _2)); + dispatcher_.AddFunction("CalendarManager_getCalendars", + std::bind(&CalendarManager::GetCalendars, manager_, _1, _2)); - dispatcher_.AddFunction( - "CalendarManager_getCalendar", - std::bind(&CalendarManager::GetCalendar, manager_, _1, _2)); + dispatcher_.AddFunction("CalendarManager_getCalendar", + std::bind(&CalendarManager::GetCalendar, manager_, _1, _2)); - dispatcher_.AddFunction( - "CalendarManager_addCalendar", - std::bind(&CalendarManager::AddCalendar, manager_, _1, _2)); + dispatcher_.AddFunction("CalendarManager_addCalendar", + std::bind(&CalendarManager::AddCalendar, manager_, _1, _2)); - dispatcher_.AddFunction( - "CalendarManager_removeCalendar", - std::bind(&CalendarManager::RemoveCalendar, manager_, _1, _2)); + dispatcher_.AddFunction("CalendarManager_removeCalendar", + std::bind(&CalendarManager::RemoveCalendar, manager_, _1, _2)); - dispatcher_.AddFunction("Calendar_get", - std::bind(&Calendar::Get, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_get", std::bind(&Calendar::Get, calendar_, _1, _2)); - dispatcher_.AddFunction("Calendar_add", - std::bind(&Calendar::Add, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_add", std::bind(&Calendar::Add, calendar_, _1, _2)); - dispatcher_.AddFunction("Calendar_addBatch", - std::bind(&Calendar::AddBatch, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_addBatch", std::bind(&Calendar::AddBatch, calendar_, _1, _2)); - dispatcher_.AddFunction("Calendar_update", - std::bind(&Calendar::Update, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_update", std::bind(&Calendar::Update, calendar_, _1, _2)); dispatcher_.AddFunction("Calendar_updateBatch", std::bind(&Calendar::UpdateBatch, calendar_, _1, _2)); - dispatcher_.AddFunction("Calendar_remove", - std::bind(&Calendar::Remove, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_remove", std::bind(&Calendar::Remove, calendar_, _1, _2)); dispatcher_.AddFunction("Calendar_removeBatch", std::bind(&Calendar::RemoveBatch, calendar_, _1, _2)); - dispatcher_.AddFunction("Calendar_find", - std::bind(&Calendar::Find, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_find", std::bind(&Calendar::Find, calendar_, _1, _2)); - dispatcher_.AddFunction( - "Calendar_addChangeListener", - std::bind(&Calendar::AddChangeListener, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_addChangeListener", + std::bind(&Calendar::AddChangeListener, calendar_, _1, _2)); - dispatcher_.AddFunction( - "Calendar_removeChangeListener", - std::bind(&Calendar::RemoveChangeListener, calendar_, _1, _2)); + dispatcher_.AddFunction("Calendar_removeChangeListener", + std::bind(&Calendar::RemoveChangeListener, calendar_, _1, _2)); } } // namespace calendar diff --git a/src/calendar/calendar_record.cc b/src/calendar/calendar_record.cc old mode 100755 new mode 100644 index 60a76d2..d8e6b98 --- a/src/calendar/calendar_record.cc +++ b/src/calendar/calendar_record.cc @@ -18,8 +18,8 @@ #include -#include "common/logger.h" #include "common/converter.h" +#include "common/logger.h" namespace extension { namespace calendar { @@ -31,13 +31,11 @@ const std::string kCalendarTypeTask = "TASK"; using namespace common; -PlatformResult CalendarRecord::CheckReturn(int ret, - const std::string& error_name) { +PlatformResult CalendarRecord::CheckReturn(int ret, const std::string& error_name) { LoggerD("Enter"); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, error_name, - ("%s : %d (%s)", error_name.c_str(), ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_name, + ("%s : %d (%s)", error_name.c_str(), ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -70,16 +68,13 @@ void CalendarRecord::ListDeleter(calendar_list_h handle) { } } -PlatformResult CalendarRecord::GetString(calendar_record_h rec, - unsigned int property, - std::string* str, - bool throw_on_error) { +PlatformResult CalendarRecord::GetString(calendar_record_h rec, unsigned int property, + std::string* str, bool throw_on_error) { LoggerD("Enter"); char* value = NULL; int ret = calendar_record_get_str(rec, property, &value); if (CALENDAR_ERROR_NONE != ret) { - LoggerE("Can't get string value form record: %d (%s)", - ret, get_error_message(ret)); + LoggerE("Can't get string value form record: %d (%s)", ret, get_error_message(ret)); if (throw_on_error) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get string from record failed."); } @@ -94,55 +89,44 @@ PlatformResult CalendarRecord::GetString(calendar_record_h rec, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::SetString(calendar_record_h record, - unsigned int property, - const std::string& value, - bool throw_on_error) { +PlatformResult CalendarRecord::SetString(calendar_record_h record, unsigned int property, + const std::string& value, bool throw_on_error) { LoggerD("Enter"); - int ret = calendar_record_set_str(record, property, - value.empty() ? NULL : value.c_str()); + int ret = calendar_record_set_str(record, property, value.empty() ? NULL : value.c_str()); if (CALENDAR_ERROR_NONE != ret) { - LoggerE("Can't set string value to record: %d (%s)", - ret, get_error_message(ret)); + LoggerE("Can't set string value to record: %d (%s)", ret, get_error_message(ret)); if (throw_on_error) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set string to record failed."); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set string to record failed."); } } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::GetInt(calendar_record_h rec, - unsigned int property, int* value, +PlatformResult CalendarRecord::GetInt(calendar_record_h rec, unsigned int property, int* value, bool throw_on_error) { LoggerD("Enter"); int ret = calendar_record_get_int(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { - LoggerE("Can't get int value form record: %d (%s)", - ret, get_error_message(ret)); + LoggerE("Can't get int value form record: %d (%s)", ret, get_error_message(ret)); if (throw_on_error) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get int from record failed."); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get int from record failed."); } } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::SetInt(calendar_record_h record, - unsigned int property, int value, +PlatformResult CalendarRecord::SetInt(calendar_record_h record, unsigned int property, int value, bool throw_on_error) { LoggerD("Enter"); int ret = calendar_record_set_int(record, property, value); if (CALENDAR_ERROR_NONE != ret) { - LoggerE("Can't set int value to record: %d (%s)", - ret, get_error_message(ret)); + LoggerE("Can't set int value to record: %d (%s)", ret, get_error_message(ret)); if (throw_on_error) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set int to record failed."); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set int to record failed."); } } @@ -198,17 +182,15 @@ int CalendarRecord::TypeToInt(const char* view_uri) { return CALENDAR_BOOK_TYPE_NONE; } -PlatformResult CalendarRecord::TypeToUri(const std::string& type, - std::string* uri) { +PlatformResult CalendarRecord::TypeToUri(const std::string& type, std::string* uri) { LoggerD("Enter"); if (kCalendarTypeEvent == type) { *uri = _calendar_event._uri; } else if (kCalendarTypeTask == type) { *uri = _calendar_todo._uri; } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Undefined record type", - ("Undefined record type: %s", type.c_str())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Undefined record type", + ("Undefined record type: %s", type.c_str())); } return PlatformResult(ErrorCode::NO_ERROR); @@ -221,23 +203,20 @@ PlatformResult CalendarRecord::TypeToUri(int type, std::string* uri) { } else if (CALENDAR_BOOK_TYPE_TODO == type) { *uri = _calendar_todo._uri; } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Undefined record type", - ("Undefined record type: %d", type)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Undefined record type", + ("Undefined record type: %d", type)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::Create(const char* view_uri, - calendar_record_h* handle) { +PlatformResult CalendarRecord::Create(const char* view_uri, calendar_record_h* handle) { LoggerD("Enter"); int ret = calendar_record_create(view_uri, handle); if (CALENDAR_ERROR_NONE != ret || nullptr == handle) { return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Fail to create calendar record", - ("Fail to create calendar record, error code: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::NOT_FOUND_ERR, "Fail to create calendar record", + ("Fail to create calendar record, error code: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -248,15 +227,13 @@ PlatformResult CalendarRecord::CreateCalendar(calendar_record_h* handle) { return Create(_calendar_book._uri, handle); } -PlatformResult CalendarRecord::GetById(int id, const char* view_uri, - calendar_record_h* handle) { +PlatformResult CalendarRecord::GetById(int id, const char* view_uri, calendar_record_h* handle) { LoggerD("Enter"); int ret = calendar_db_get_record(view_uri, id, handle); if (CALENDAR_ERROR_NONE != ret || nullptr == handle) { - return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Fail to get record with given id", - ("Fail to get calendar record %d for view %s, error code: %d (%s)", - id, view_uri, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Fail to get record with given id", + ("Fail to get calendar record %d for view %s, error code: %d (%s)", + id, view_uri, ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -268,16 +245,14 @@ PlatformResult CalendarRecord::Insert(calendar_record_h rec, int* record_id) { if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Cannot insert record", - ("Cannot insert record, error code: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::NOT_FOUND_ERR, "Cannot insert record", + ("Cannot insert record, error code: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::AddChildRecord(calendar_record_h rec, - unsigned int property, +PlatformResult CalendarRecord::AddChildRecord(calendar_record_h rec, unsigned int property, calendar_record_h child) { LoggerD("Enter"); int ret = calendar_record_add_child_record(rec, property, child); @@ -286,21 +261,18 @@ PlatformResult CalendarRecord::AddChildRecord(calendar_record_h rec, calendar_record_destroy(child, true); } return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, "Cannot add child record", - ("Cannot add child record, error code: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::NOT_FOUND_ERR, "Cannot add child record", + ("Cannot add child record, error code: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -void CalendarRecord::RemoveChildRecords(calendar_record_h rec, - unsigned int property_id) { +void CalendarRecord::RemoveChildRecords(calendar_record_h rec, unsigned int property_id) { LoggerD("Enter"); unsigned int count = 0; - if (CALENDAR_ERROR_NONE != - calendar_record_get_child_record_count(rec, property_id, &count)) { + if (CALENDAR_ERROR_NONE != calendar_record_get_child_record_count(rec, property_id, &count)) { LoggerW("Can't get attendees count"); } @@ -316,48 +288,40 @@ void CalendarRecord::RemoveChildRecords(calendar_record_h rec, continue; } - if (CALENDAR_ERROR_NONE != - calendar_record_remove_child_record(rec, property_id, attendee)) { + if (CALENDAR_ERROR_NONE != calendar_record_remove_child_record(rec, property_id, attendee)) { LoggerW("Can't remove the attendee"); continue; } } } -PlatformResult CalendarRecord::GetChildRecordCount(calendar_record_h rec, - unsigned int property, - bool throw_on_error, - unsigned int* value) { +PlatformResult CalendarRecord::GetChildRecordCount(calendar_record_h rec, unsigned int property, + bool throw_on_error, unsigned int* value) { LoggerD("Enter"); int ret = calendar_record_get_child_record_count(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Can't get child record count: %d (%s)", ret, get_error_message(ret)); if (throw_on_error) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get child record count failed."); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get child record count failed."); } } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::GetChildRecordAt(calendar_record_h rec, - unsigned int property, - calendar_record_h* result, - int index) { +PlatformResult CalendarRecord::GetChildRecordAt(calendar_record_h rec, unsigned int property, + calendar_record_h* result, int index) { LoggerD("Enter"); int ret = calendar_record_get_child_record_at_p(rec, property, index, result); if (CALENDAR_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get child record at failed.", - ("Can't get child record at: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get child record at failed.", + ("Can't get child record at: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::CalendarToJson(calendar_record_h rec, - picojson::object* out_ptr) { +PlatformResult CalendarRecord::CalendarToJson(calendar_record_h rec, picojson::object* out_ptr) { LoggerD("Enter"); picojson::object& out = *out_ptr; @@ -381,20 +345,17 @@ PlatformResult CalendarRecord::CalendarToJson(calendar_record_h rec, std::string type = TypeToString(value); out.insert(std::make_pair("id", picojson::value(std::to_string(id)))); - out.insert( - std::make_pair("accountId", picojson::value(std::to_string(account_id)))); + out.insert(std::make_pair("accountId", picojson::value(std::to_string(account_id)))); out.insert(std::make_pair("name", picojson::value(name))); out.insert(std::make_pair("type", picojson::value(type))); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CalendarRecord::CalendarFromJson(calendar_record_h rec, - const picojson::object& in) { +PlatformResult CalendarRecord::CalendarFromJson(calendar_record_h rec, const picojson::object& in) { LoggerD("Enter"); if (in.empty()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Empty Calendar object."); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Empty Calendar object."); } const std::string& name = FromJson(in, "name"); diff --git a/src/calendar/calendar_record.h b/src/calendar/calendar_record.h index 8228b67..4adf9b6 100644 --- a/src/calendar/calendar_record.h +++ b/src/calendar/calendar_record.h @@ -16,23 +16,23 @@ #ifndef WEBAPI_PLUGINS_CALENDAR_RECORD_H_ #define WEBAPI_PLUGINS_CALENDAR_RECORD_H_ -#include -#include -#include #include +#include +#include +#include -#include "common/platform_result.h" #include "common/picojson.h" +#include "common/platform_result.h" namespace extension { namespace calendar { -typedef std::unique_ptr::type, - void (*)(calendar_query_h)> CalendarQueryPtr; -typedef std::unique_ptr::type, - void (*)(calendar_record_h)> CalendarRecordPtr; -typedef std::unique_ptr::type, - void (*)(calendar_list_h)> CalendarListPtr; +typedef std::unique_ptr::type, void (*)(calendar_query_h)> + CalendarQueryPtr; +typedef std::unique_ptr::type, void (*)(calendar_record_h)> + CalendarRecordPtr; +typedef std::unique_ptr::type, void (*)(calendar_list_h)> + CalendarListPtr; class CalendarRecord { public: @@ -40,60 +40,41 @@ class CalendarRecord { static void Deleter(calendar_record_h handle); static void ListDeleter(calendar_list_h handle); - static common::PlatformResult GetString(calendar_record_h rec, - unsigned int property, - std::string* str, - bool throw_on_error = true); - static common::PlatformResult SetString(calendar_record_h rec, - unsigned int property, - const std::string& value, - bool throw_on_error = true); + static common::PlatformResult GetString(calendar_record_h rec, unsigned int property, + std::string* str, bool throw_on_error = true); + static common::PlatformResult SetString(calendar_record_h rec, unsigned int property, + const std::string& value, bool throw_on_error = true); - static common::PlatformResult GetInt(calendar_record_h rec, - unsigned int property, - int* value, + static common::PlatformResult GetInt(calendar_record_h rec, unsigned int property, int* value, bool throw_on_error = true); - static common::PlatformResult SetInt(calendar_record_h rec, - unsigned int property, int value, + static common::PlatformResult SetInt(calendar_record_h rec, unsigned int property, int value, bool throw_on_error = true); static std::string TypeToString(int type); static std::string TypeToString(const char* view_uri); static int TypeToInt(const std::string& type); static int TypeToInt(const char* view_uri); - static common::PlatformResult TypeToUri(const std::string& type, - std::string* uri); + static common::PlatformResult TypeToUri(const std::string& type, std::string* uri); static common::PlatformResult TypeToUri(int type, std::string* uri); static common::PlatformResult Insert(calendar_record_h rec, int* record_id); - static common::PlatformResult AddChildRecord(calendar_record_h rec, - unsigned int property, + static common::PlatformResult AddChildRecord(calendar_record_h rec, unsigned int property, calendar_record_h child); - static void RemoveChildRecords(calendar_record_h rec, - unsigned int property_id); - static common::PlatformResult GetChildRecordCount(calendar_record_h rec, - unsigned int property, - bool throw_on_error, - unsigned int* value); - static common::PlatformResult GetChildRecordAt(calendar_record_h rec, - unsigned int property, - calendar_record_h* result, - int index); + static void RemoveChildRecords(calendar_record_h rec, unsigned int property_id); + static common::PlatformResult GetChildRecordCount(calendar_record_h rec, unsigned int property, + bool throw_on_error, unsigned int* value); + static common::PlatformResult GetChildRecordAt(calendar_record_h rec, unsigned int property, + calendar_record_h* result, int index); - static common::PlatformResult GetById(int id, const char* view_uri, - calendar_record_h *handle); - static common::PlatformResult Create(const char* view_uri, - calendar_record_h *calendar); + static common::PlatformResult GetById(int id, const char* view_uri, calendar_record_h* handle); + static common::PlatformResult Create(const char* view_uri, calendar_record_h* calendar); static common::PlatformResult CreateCalendar(calendar_record_h* handle); - static common::PlatformResult CalendarToJson(calendar_record_h rec, - picojson::object* out_ptr); - static common::PlatformResult CalendarFromJson(calendar_record_h rec, - const picojson::object& in); + static common::PlatformResult CalendarToJson(calendar_record_h rec, picojson::object* out_ptr); + static common::PlatformResult CalendarFromJson(calendar_record_h rec, const picojson::object& in); - static common::PlatformResult CheckReturn(int ret, - const std::string& error_name); + static common::PlatformResult CheckReturn(int ret, const std::string& error_name); }; } // namespace calendar diff --git a/src/callhistory/callhistory.cc b/src/callhistory/callhistory.cc old mode 100755 new mode 100644 index d6fc1f6..7352237 --- a/src/callhistory/callhistory.cc +++ b/src/callhistory/callhistory.cc @@ -18,9 +18,9 @@ #include -#include #include #include +#include #include "common/logger.h" #include "common/platform_exception.h" @@ -38,16 +38,15 @@ namespace extension { namespace callhistory { namespace { -static void get_sim_msisdn_cb(TapiHandle *handle, int result, void *data, void *user_data) -{ +static void get_sim_msisdn_cb(TapiHandle* handle, int result, void* data, void* user_data) { LoggerD("Entered"); - TelSimMsisdnList_t *list; - std::promise *prom = reinterpret_cast *>(user_data); - char *number = NULL; + TelSimMsisdnList_t* list; + std::promise* prom = reinterpret_cast*>(user_data); + char* number = NULL; if (TAPI_SIM_ACCESS_SUCCESS == result) { - list = static_cast(data); + list = static_cast(data); if (list->count) { number = list->list[0].num; } @@ -62,9 +61,7 @@ static void get_sim_msisdn_cb(TapiHandle *handle, int result, void *data, void * } CallHistory::CallHistory(CallHistoryInstance& instance) - : m_is_listener_set(false), - instance_(instance), - utils_(*this) { + : m_is_listener_set(false), instance_(instance), utils_(*this) { LoggerD("Entered"); if (CONTACTS_ERROR_NONE == contacts_connect()) { LoggerD("Successful to connect Call history DB"); @@ -73,13 +70,12 @@ CallHistory::CallHistory(CallHistoryInstance& instance) } } -CallHistory::~CallHistory() -{ +CallHistory::~CallHistory() { LoggerD("Entered"); if (m_is_listener_set) { - int ret = contacts_db_remove_changed_cb_with_info(_contacts_phone_log._uri, - changeListenerCB, NULL); + int ret = + contacts_db_remove_changed_cb_with_info(_contacts_phone_log._uri, changeListenerCB, NULL); if (CONTACTS_ERROR_NONE != ret) { LoggerW("Failed to remove ChangeListener"); @@ -93,8 +89,7 @@ CallHistory::~CallHistory() } } -void CallHistory::FindThread(const picojson::object& args, CallHistory* call_history) -{ +void CallHistory::FindThread(const picojson::object& args, CallHistory* call_history) { LoggerD("Entered"); std::shared_ptr response{new picojson::value(picojson::object())}; @@ -108,20 +103,18 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his if (0 == phone_numbers_size) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Phone numbers list is empty."), - &response->get()); + &response->get()); } else { const auto it_args_end = args.end(); const auto it_filter = args.find("filter"); picojson::object filter_obj; - if (it_filter != it_args_end && - it_filter->second.is()) { + if (it_filter != it_args_end && it_filter->second.is()) { filter_obj = it_filter->second.get(); } const auto it_sort_mode = args.find("sortMode"); picojson::object sort_mode; - if (it_sort_mode != it_args_end && - it_sort_mode->second.is()) { + if (it_sort_mode != it_args_end && it_sort_mode->second.is()) { sort_mode = it_sort_mode->second.get(); } @@ -130,29 +123,25 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his if (!sort_mode.empty()) { const auto it_sort_end = sort_mode.end(); const auto it_sort_attr_name = sort_mode.find("attributeName"); - if (it_sort_attr_name != it_sort_end && - it_sort_attr_name->second.is()) { + if (it_sort_attr_name != it_sort_end && it_sort_attr_name->second.is()) { sort_attr_name = it_sort_attr_name->second.get(); } const auto it_sort_order = sort_mode.find("order"); - if (it_sort_order != it_sort_end && - it_sort_order->second.is()) { + if (it_sort_order != it_sort_end && it_sort_order->second.is()) { sort_order = it_sort_order->second.get(); } } const auto it_limit = args.find("limit"); int limit = 0; - if (it_limit != it_args_end && - it_limit->second.is()) { + if (it_limit != it_args_end && it_limit->second.is()) { limit = static_cast(it_limit->second.get()); } const auto it_offset = args.find("offset"); int offset = 0; - if (it_offset != it_args_end && - it_offset->second.is()) { + if (it_offset != it_args_end && it_offset->second.is()) { offset = static_cast(it_offset->second.get()); } @@ -181,7 +170,7 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his LoggerW("contacts_filter_create failed"); } - //filter + // filter CallHistoryUtils& utils = call_history->getUtils(); if (!filter_obj.empty()) { LoggerD("Filter is set"); @@ -193,7 +182,8 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his } ret = contacts_filter_add_int(filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); + CONTACTS_MATCH_LESS_THAN_OR_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); if (CONTACTS_ERROR_NONE != ret) { LoggerW("contacts_filter_add_int failed"); } @@ -203,7 +193,7 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his LoggerW("contacts_query_set_filter failed"); } - //sort mode + // sort mode bool is_asc = false; if (!sort_order.empty()) { if (STR_ORDER_ASC == sort_order) { @@ -219,15 +209,16 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his LoggerW("contacts_query_set_sort failed"); } - //get records with limit and offset + // get records with limit and offset ret = contacts_db_get_records_with_query(query, offset, limit, &record_list); if (CONTACTS_ERROR_NONE != ret) { LoggerW("contacts_db_get_records_with_query failed"); } picojson::object& obj = response->get(); - picojson::array& array = obj.insert(std::make_pair(STR_DATA, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& array = + obj.insert(std::make_pair(STR_DATA, picojson::value(picojson::array()))) + .first->second.get(); if (record_list) { utils.parseRecordList(&record_list, array); } @@ -240,7 +231,8 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his ReportSuccess(response->get()); } - auto find_response = [call_history, callback_id](const std::shared_ptr& response) -> void { + auto find_response = [call_history, + callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&call_history->instance_, response->serialize().c_str()); @@ -249,16 +241,15 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his TaskQueue::GetInstance().Async(find_response, response); } -void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* call_history) -{ +void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* call_history) { LoggerD("Entered"); CallHistory::LockedVector phone_numbers = call_history->getPhoneNumbers(); if (0 != phone_numbers.size()) { LoggerD("m_phone_numbers is already filled. Returning."); return; } - char** cp_list = tel_get_cp_name_list(); - if (nullptr == cp_list){ + char** cp_list = tel_get_cp_name_list(); + if (nullptr == cp_list) { LoggerE("Failed to get cp_list"); } @@ -300,7 +291,7 @@ void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* ca fut.wait(); n = fut.get(); LoggerD("Phone number [%d] : %s", modem_num, n.c_str()); - } while(false); + } while (false); phone_numbers.push_back(n); tel_deinit(handle); @@ -317,49 +308,41 @@ void CallHistory::find(const picojson::object& args) { std::thread(FindThread, args, this).detach(); } -PlatformResult CallHistory::remove(const picojson::object& args) -{ +PlatformResult CallHistory::remove(const picojson::object& args) { LoggerD("Entered"); const auto it_uid = args.find("uid"); const auto it_args_end = args.end(); - if (it_uid == it_args_end || - !it_uid->second.is()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid parameter was passed."); + if (it_uid == it_args_end || !it_uid->second.is()) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed."); } int uid = atoi((it_uid->second.get()).c_str()); int ret = contacts_db_delete_record(_contacts_phone_log._uri, (int)uid); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to delete log record.", - ("Failed to delete log record [%d] with error: %d", uid, ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to delete log record.", + ("Failed to delete log record [%d] with error: %d", uid, ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -common::PlatformResult CallHistory::removeBatch(const picojson::object& args) -{ +common::PlatformResult CallHistory::removeBatch(const picojson::object& args) { LoggerD("Entered"); const auto it_uid = args.find("uid"); const auto it_args_end = args.end(); - if (it_uid == it_args_end || - !it_uid->second.is()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid parameter was passed."); + if (it_uid == it_args_end || !it_uid->second.is()) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter was passed."); } const picojson::array& uids = it_uid->second.get(); const double callback_id = args.find("callbackId")->second.get(); auto remove_batch = [uids](const std::shared_ptr& response) -> void { if (uids.size() == 0) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Object is null."), - &response->get()); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Object is null."), + &response->get()); return; } @@ -368,17 +351,17 @@ common::PlatformResult CallHistory::removeBatch(const picojson::object& args) int uid = atoi(uids[i].get().c_str()); ret = contacts_db_delete_record(_contacts_phone_log._uri, (int)uid); if (CONTACTS_ERROR_NONE != ret) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Remove record failed."), - &response->get(), - ("Failed to delete log [%d] with code %d", uid, ret)); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Remove record failed."), + &response->get(), + ("Failed to delete log [%d] with code %d", uid, ret)); return; } } ReportSuccess(response->get()); }; - auto remove_batch_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto remove_batch_response = + [this, callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -386,21 +369,16 @@ common::PlatformResult CallHistory::removeBatch(const picojson::object& args) auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - remove_batch, - remove_batch_response, - data); + TaskQueue::GetInstance().Queue(remove_batch, remove_batch_response, data); return PlatformResult(ErrorCode::NO_ERROR); } -void CallHistory::removeAll(const picojson::object& args) -{ +void CallHistory::removeAll(const picojson::object& args) { LoggerD("Entered"); const double callback_id = args.find("callbackId")->second.get(); auto remove_all = [](const std::shared_ptr& response) -> void { - contacts_list_h record_list = nullptr; int* list = NULL; SCOPE_EXIT { @@ -420,9 +398,8 @@ void CallHistory::removeAll(const picojson::object& args) ret = contacts_db_get_all_records(_contacts_phone_log._uri, 0, 0, &record_list); if (CONTACTS_ERROR_NONE != ret || !record_list) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get all records list."), - &response->get()); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get all records list."), + &response->get()); return; } @@ -442,17 +419,16 @@ void CallHistory::removeAll(const picojson::object& args) if (!record) { ret = contacts_list_next(record_list); if (CONTACTS_ERROR_NONE != ret && CONTACTS_ERROR_NO_DATA != ret) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Get next record from list failed."), - &response->get(),\ - ("contacts_list_next function failed")); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Get next record from list failed."), + &response->get(), ("contacts_list_next function failed")); return; } continue; } if (CONTACTS_ERROR_NONE == ret) { - ret = contacts_record_get_int(record, _contacts_phone_log.id , &value); + ret = contacts_record_get_int(record, _contacts_phone_log.id, &value); if (CONTACTS_ERROR_NONE == ret) { list[cnt++] = value; } @@ -461,10 +437,9 @@ void CallHistory::removeAll(const picojson::object& args) value = 0; ret = contacts_list_next(record_list); if (CONTACTS_ERROR_NONE != ret && CONTACTS_ERROR_NO_DATA != ret) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Get next record from list failed."), - &response->get(), - ("contacts_list_next function failed")); + LogAndReportError( + PlatformResult(ErrorCode::UNKNOWN_ERR, "Get next record from list failed."), + &response->get(), ("contacts_list_next function failed")); return; } } @@ -472,10 +447,9 @@ void CallHistory::removeAll(const picojson::object& args) if (cnt > 0) { ret = contacts_db_delete_records(_contacts_phone_log._uri, list, cnt); if (CONTACTS_ERROR_NONE != ret) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, - "Delete records function failed."), - &response->get(), - ("contacts_db_delete_records function failed")); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Delete records function failed."), + &response->get(), + ("contacts_db_delete_records function failed")); return; } } @@ -492,7 +466,8 @@ void CallHistory::removeAll(const picojson::object& args) ReportSuccess(response->get()); }; - auto remove_all_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto remove_all_response = + [this, callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -500,24 +475,18 @@ void CallHistory::removeAll(const picojson::object& args) auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - remove_all, - remove_all_response, - data); + TaskQueue::GetInstance().Queue(remove_all, remove_all_response, data); } -CallHistory::LockedVector CallHistory::getPhoneNumbers() -{ +CallHistory::LockedVector CallHistory::getPhoneNumbers() { return std::move(CallHistory::LockedVector{m_phone_numbers, m_phone_numbers_mutex}); } -CallHistoryUtils& CallHistory::getUtils() -{ +CallHistoryUtils& CallHistory::getUtils() { return utils_; } -void CallHistory::changeListenerCB(const char* view_uri, char *changes, void* user_data) -{ +void CallHistory::changeListenerCB(const char* view_uri, char* changes, void* user_data) { LoggerD("Entered"); CallHistory* h = static_cast(user_data); @@ -537,18 +506,21 @@ void CallHistory::changeListenerCB(const char* view_uri, char *changes, void* us picojson::value added = picojson::value(picojson::object()); picojson::object& added_obj = added.get(); - picojson::array& added_array = added_obj.insert(std::make_pair(STR_DATA, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& added_array = + added_obj.insert(std::make_pair(STR_DATA, picojson::value(picojson::array()))) + .first->second.get(); picojson::value changed = picojson::value(picojson::object()); picojson::object& changed_obj = changed.get(); - picojson::array& changed_array = changed_obj.insert(std::make_pair(STR_DATA, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& changed_array = + changed_obj.insert(std::make_pair(STR_DATA, picojson::value(picojson::array()))) + .first->second.get(); picojson::value removed = picojson::value(picojson::object()); picojson::object& removed_obj = removed.get(); - picojson::array& removed_array = removed_obj.insert(std::make_pair(STR_DATA, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& removed_array = + removed_obj.insert(std::make_pair(STR_DATA, picojson::value(picojson::array()))) + .first->second.get(); char* saveptr = nullptr; @@ -599,7 +571,7 @@ void CallHistory::changeListenerCB(const char* view_uri, char *changes, void* us contacts_query_destroy(query); contacts_filter_destroy(filter); - token_type = strtok_r( NULL, seps, &saveptr); + token_type = strtok_r(NULL, seps, &saveptr); } if (added_array.size() > 0) { @@ -616,17 +588,15 @@ void CallHistory::changeListenerCB(const char* view_uri, char *changes, void* us } } -PlatformResult CallHistory::startCallHistoryChangeListener() -{ +PlatformResult CallHistory::startCallHistoryChangeListener() { LoggerD("Entered"); if (!m_is_listener_set) { - int ret = contacts_db_add_changed_cb_with_info(_contacts_phone_log._uri, - changeListenerCB, this); + int ret = + contacts_db_add_changed_cb_with_info(_contacts_phone_log._uri, changeListenerCB, this); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to add ChangeListener"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to add ChangeListener"); } } @@ -634,24 +604,21 @@ PlatformResult CallHistory::startCallHistoryChangeListener() return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CallHistory::stopCallHistoryChangeListener() -{ +PlatformResult CallHistory::stopCallHistoryChangeListener() { LoggerD("Entered"); if (m_is_listener_set) { - int ret = contacts_db_remove_changed_cb_with_info(_contacts_phone_log._uri, - changeListenerCB, this); + int ret = + contacts_db_remove_changed_cb_with_info(_contacts_phone_log._uri, changeListenerCB, this); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to remove ChangeListener"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to remove ChangeListener"); } } m_is_listener_set = false; return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CallHistory::setMissedDirection(int uid) -{ +PlatformResult CallHistory::setMissedDirection(int uid) { LoggerD("Entered"); contacts_record_h record = nullptr; @@ -670,15 +637,15 @@ PlatformResult CallHistory::setMissedDirection(int uid) ret = contacts_record_get_int(record, _contacts_phone_log.log_type, &log_type); if (CONTACTS_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get log type", - ("Failed to get log type [%d]", ret)); + ("Failed to get log type [%d]", ret)); } if (CONTACTS_PLOG_TYPE_VOICE_INCOMING_UNSEEN == log_type) { - ret = contacts_record_set_int( - record, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); + ret = contacts_record_set_int(record, _contacts_phone_log.log_type, + CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); } else if (CONTACTS_PLOG_TYPE_VIDEO_INCOMING_UNSEEN == log_type) { - ret = contacts_record_set_int( - record, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); + ret = contacts_record_set_int(record, _contacts_phone_log.log_type, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); } else { return PlatformResult(ErrorCode::NO_ERROR); } @@ -691,11 +658,11 @@ PlatformResult CallHistory::setMissedDirection(int uid) ret = contacts_db_update_record(record); if (CONTACTS_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to update record", - ("Failed to update record [%d]", ret)); + ("Failed to update record [%d]", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension diff --git a/src/callhistory/callhistory.h b/src/callhistory/callhistory.h old mode 100755 new mode 100644 index 651f749..da156b5 --- a/src/callhistory/callhistory.h +++ b/src/callhistory/callhistory.h @@ -17,11 +17,11 @@ #ifndef CALLHISTORY_CALLHISTORY_H_ #define CALLHISTORY_CALLHISTORY_H_ -#include -#include #include #include +#include #include +#include #include #include @@ -36,26 +36,33 @@ namespace callhistory { class CallHistoryInstance; -class CallHistory -{ +class CallHistory { public: explicit CallHistory(CallHistoryInstance& instance); ~CallHistory(); class LockedVector; LockedVector getPhoneNumbers(); - //You can access m_phone_numbers only by getPhoneNumbers(). It will be available and locked in current scope. - //All section since calling getPhoneNumbers until end of scope will be critical section. + // You can access m_phone_numbers only by getPhoneNumbers(). It will be available and locked in + // current scope. + // All section since calling getPhoneNumbers until end of scope will be critical section. class LockedVector { std::unique_lock guard; typedef std::vector StringVector; StringVector& vector; - LockedVector( StringVector& vector, std::mutex& lock ) : guard(lock), vector(vector) {}; + LockedVector(StringVector& vector, std::mutex& lock) : guard(lock), vector(vector){}; friend LockedVector CallHistory::getPhoneNumbers(); - public: - StringVector::size_type size() { return vector.size(); } - StringVector::value_type at(StringVector::size_type i) { return vector.at(i); } - void push_back(const StringVector::value_type& value) { vector.push_back(value); } + + public: + StringVector::size_type size() { + return vector.size(); + } + StringVector::value_type at(StringVector::size_type i) { + return vector.at(i); + } + void push_back(const StringVector::value_type& value) { + vector.push_back(value); + } }; CallHistoryUtils& getUtils(); @@ -68,18 +75,18 @@ class CallHistory common::PlatformResult setMissedDirection(int uid); private: - static void changeListenerCB(const char* view_uri, char *changes, void* user_data); + static void changeListenerCB(const char* view_uri, char* changes, void* user_data); static void FindThread(const picojson::object& args, CallHistory* call_history); static void LoadPhoneNumbers(const picojson::object& args, CallHistory* call_history); bool m_is_listener_set; std::mutex m_phone_numbers_mutex; - std::vector m_phone_numbers; //See LockedVector + std::vector m_phone_numbers; // See LockedVector CallHistoryInstance& instance_; CallHistoryUtils utils_; }; -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension -#endif // CALLHISTORY_CALLHISTORY_H_ +#endif // CALLHISTORY_CALLHISTORY_H_ diff --git a/src/callhistory/callhistory_extension.cc b/src/callhistory/callhistory_extension.cc old mode 100755 new mode 100644 index 2d37fd6..aed7200 --- a/src/callhistory/callhistory_extension.cc +++ b/src/callhistory/callhistory_extension.cc @@ -29,7 +29,8 @@ CallHistoryExtension::CallHistoryExtension() { SetJavaScriptAPI(kSource_callhistory_api); } -CallHistoryExtension::~CallHistoryExtension() {} +CallHistoryExtension::~CallHistoryExtension() { +} common::Instance* CallHistoryExtension::CreateInstance() { return new extension::callhistory::CallHistoryInstance(); diff --git a/src/callhistory/callhistory_extension.h b/src/callhistory/callhistory_extension.h old mode 100755 new mode 100644 index 12abb6d..a6413a8 --- a/src/callhistory/callhistory_extension.h +++ b/src/callhistory/callhistory_extension.h @@ -28,4 +28,4 @@ class CallHistoryExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // CALLHISTORY_CALLHISTORY_EXTENSION_H_ +#endif // CALLHISTORY_CALLHISTORY_EXTENSION_H_ diff --git a/src/callhistory/callhistory_instance.cc b/src/callhistory/callhistory_instance.cc old mode 100755 new mode 100644 index 7ceec76..64d8166 --- a/src/callhistory/callhistory_instance.cc +++ b/src/callhistory/callhistory_instance.cc @@ -16,10 +16,10 @@ #include "callhistory/callhistory_instance.h" -#include "common/picojson.h" #include "common/logger.h" -#include "common/tools.h" +#include "common/picojson.h" #include "common/platform_exception.h" +#include "common/tools.h" namespace extension { namespace callhistory { @@ -37,15 +37,15 @@ CallHistoryInstance::CallHistoryInstance() : history_(*this) { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&CallHistoryInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) \ + RegisterSyncHandler(c, std::bind(&CallHistoryInstance::x, this, _1, _2)); REGISTER_SYNC("CallHistory_remove", Remove); REGISTER_SYNC("CallHistory_addChangeListener", AddChangeListener); REGISTER_SYNC("CallHistory_removeChangeListener", RemoveChangeListener); REGISTER_SYNC("CallHistory_setMissedDirection", SetMissedDirection); #undef REGISTER_SYNC -#define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&CallHistoryInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) \ + RegisterSyncHandler(c, std::bind(&CallHistoryInstance::x, this, _1, _2)); REGISTER_ASYNC("CallHistory_find", Find); REGISTER_ASYNC("CallHistory_removeBatch", RemoveBatch); REGISTER_ASYNC("CallHistory_removeAll", RemoveAll); @@ -141,5 +141,5 @@ void CallHistoryInstance::CallHistoryChange(picojson::object& data) { Instance::PostMessage(this, event.serialize().c_str()); } -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension diff --git a/src/callhistory/callhistory_instance.h b/src/callhistory/callhistory_instance.h index a7e9f30..06e93f7 100644 --- a/src/callhistory/callhistory_instance.h +++ b/src/callhistory/callhistory_instance.h @@ -5,8 +5,8 @@ #ifndef CALLHISTORY_CALLHISTORY_INSTANCE_H_ #define CALLHISTORY_CALLHISTORY_INSTANCE_H_ -#include "common/extension.h" #include "callhistory.h" +#include "common/extension.h" namespace extension { namespace callhistory { @@ -17,19 +17,20 @@ class CallHistoryInstance : public common::ParsedInstance { virtual ~CallHistoryInstance(); void CallHistoryChange(picojson::object& data); + private: void Find(const picojson::value& args, picojson::object& out); void Remove(const picojson::value& args, picojson::object& out); void RemoveBatch(const picojson::value& args, picojson::object& out); void RemoveAll(const picojson::value& args, picojson::object& out); - void AddChangeListener (const picojson::value& args, picojson::object& out); + void AddChangeListener(const picojson::value& args, picojson::object& out); void RemoveChangeListener(const picojson::value& args, picojson::object& out); void SetMissedDirection(const picojson::value& args, picojson::object& out); CallHistory history_; }; -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension -#endif // CALLHISTORY_CALLHISTORY_INSTANCE_H_ +#endif // CALLHISTORY_CALLHISTORY_INSTANCE_H_ diff --git a/src/callhistory/callhistory_types.h b/src/callhistory/callhistory_types.h old mode 100755 new mode 100644 index b2a6d7a..03b96d9 --- a/src/callhistory/callhistory_types.h +++ b/src/callhistory/callhistory_types.h @@ -62,7 +62,7 @@ namespace callhistory { #define STR_FILTER_ENDSWITH "ENDSWITH" #define STR_FILTER_EXISTS "EXISTS" -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension -#endif // CALLHISTORY_CALLHISTORY_TYPES_H_ +#endif // CALLHISTORY_CALLHISTORY_TYPES_H_ diff --git a/src/callhistory/callhistory_utils.cc b/src/callhistory/callhistory_utils.cc old mode 100755 new mode 100644 index 23fddb2..9b67c74 --- a/src/callhistory/callhistory_utils.cc +++ b/src/callhistory/callhistory_utils.cc @@ -16,11 +16,11 @@ #include "callhistory_utils.h" -#include #include +#include -#include "callhistory_types.h" #include "callhistory.h" +#include "callhistory_types.h" #include "common/logger.h" namespace extension { @@ -34,19 +34,13 @@ enum FilterTypeEnum { FILTER_UNKNOWN = 3 }; -enum CompositeTypeEnum { - UNION = 0, - INTERSECTION = 1, - NONE = 2 -}; +enum CompositeTypeEnum { UNION = 0, INTERSECTION = 1, NONE = 2 }; } -CallHistoryUtils::CallHistoryUtils(CallHistory& history) - : history_(history) { +CallHistoryUtils::CallHistoryUtils(CallHistory& history) : history_(history) { } -void CallHistoryUtils::parseRecordList(contacts_list_h *record_list, picojson::array& array) -{ +void CallHistoryUtils::parseRecordList(contacts_list_h* record_list, picojson::array& array) { LoggerD("Entered"); contacts_record_h record = NULL; @@ -79,8 +73,7 @@ void CallHistoryUtils::parseRecordList(contacts_list_h *record_list, picojson::a } } -void CallHistoryUtils::parseRecord(contacts_record_h *record, picojson::object& obj) -{ +void CallHistoryUtils::parseRecord(contacts_record_h* record, picojson::object& obj) { LoggerD("Entered"); int int_data; @@ -117,14 +110,13 @@ void CallHistoryUtils::parseRecord(contacts_record_h *record, picojson::object& parseCallingParty(record, obj); } -void CallHistoryUtils::parseLogType(contacts_phone_log_type_e log_type, picojson::object& obj) -{ +void CallHistoryUtils::parseLogType(contacts_phone_log_type_e log_type, picojson::object& obj) { LoggerD("Entered"); picojson::value val = picojson::value(picojson::array()); picojson::array& features = val.get(); - switch(log_type) { + switch (log_type) { case CONTACTS_PLOG_TYPE_VOICE_INCOMING: obj[STR_CALL_TYPE] = picojson::value(STR_CALLTYPE_TEL); obj[STR_DIRECTION] = picojson::value(STR_RECEIVED); @@ -195,15 +187,15 @@ void CallHistoryUtils::parseLogType(contacts_phone_log_type_e log_type, picojson } } -void CallHistoryUtils::parseRemoteParties(contacts_record_h *record, picojson::object& obj) -{ +void CallHistoryUtils::parseRemoteParties(contacts_record_h* record, picojson::object& obj) { LoggerD("Entered"); - char * char_data = NULL; + char* char_data = NULL; int int_data; - picojson::array& remote_parties = obj.insert(std::make_pair(STR_REMOTE_PARTIES, picojson::value( - picojson::array()))).first->second.get(); + picojson::array& remote_parties = + obj.insert(std::make_pair(STR_REMOTE_PARTIES, picojson::value(picojson::array()))) + .first->second.get(); remote_parties.push_back(picojson::value(picojson::object())); picojson::object& parties_obj = remote_parties.back().get(); @@ -222,8 +214,7 @@ void CallHistoryUtils::parseRemoteParties(contacts_record_h *record, picojson::o } } -void CallHistoryUtils::parseCallingParty(contacts_record_h *record, picojson::object& obj) -{ +void CallHistoryUtils::parseCallingParty(contacts_record_h* record, picojson::object& obj) { LoggerD("Entered"); int sim_count = 0; @@ -246,8 +237,7 @@ void CallHistoryUtils::parseCallingParty(contacts_record_h *record, picojson::ob } } -unsigned int CallHistoryUtils::convertAttributeName(const std::string& attribute_name) -{ +unsigned int CallHistoryUtils::convertAttributeName(const std::string& attribute_name) { LoggerD("Entered"); if (STR_RP_REMOTEPARTY == attribute_name) { @@ -265,8 +255,7 @@ unsigned int CallHistoryUtils::convertAttributeName(const std::string& attribute } } -static FilterTypeEnum getFilterType(const picojson::object &filter) -{ +static FilterTypeEnum getFilterType(const picojson::object& filter) { LoggerD("Entered"); const auto it_end = filter.end(); @@ -291,8 +280,7 @@ static FilterTypeEnum getFilterType(const picojson::object &filter) return type; } -static CompositeTypeEnum getCompositeType(const picojson::object &filter) -{ +static CompositeTypeEnum getCompositeType(const picojson::object& filter) { LoggerD("Entered"); CompositeTypeEnum type = NONE; const std::string& str_type = filter.find("type")->second.get(); @@ -305,8 +293,7 @@ static CompositeTypeEnum getCompositeType(const picojson::object &filter) return type; } -static contacts_match_str_flag_e getMatchFlag(const std::string& match_flag) -{ +static contacts_match_str_flag_e getMatchFlag(const std::string& match_flag) { LoggerD("Entered"); if (STR_FILTER_FULLSTRING == match_flag) { return CONTACTS_MATCH_FULLSTRING; @@ -323,8 +310,7 @@ static contacts_match_str_flag_e getMatchFlag(const std::string& match_flag) } } -static std::time_t toTimeT(const std::string &value) -{ +static std::time_t toTimeT(const std::string& value) { LoggerD("Entered"); struct tm date; if (nullptr == strptime(value.c_str(), "%Y-%m-%dT%H:%M:%S", &date)) { @@ -333,8 +319,7 @@ static std::time_t toTimeT(const std::string &value) return mktime(&date); } -static void visitAttribute(std::stack& stack, const picojson::object filter) -{ +static void visitAttribute(std::stack& stack, const picojson::object filter) { LoggerD("Entered"); contacts_filter_h filter_top = stack.top(); @@ -342,10 +327,10 @@ static void visitAttribute(std::stack& stack, const picojson: contacts_filter_create(_contacts_phone_log._uri, &sub_filter); const auto it_attr_name = filter.find("attributeName"); - const std::string &attr_name = it_attr_name->second.get(); + const std::string& attr_name = it_attr_name->second.get(); const auto it_match_flag = filter.find("matchFlag"); - const std::string &match_flag = it_match_flag->second.get(); + const std::string& match_flag = it_match_flag->second.get(); contacts_match_str_flag_e c_match_flag = getMatchFlag(match_flag); const auto it_match_value = filter.find("matchValue"); @@ -360,59 +345,52 @@ static void visitAttribute(std::stack& stack, const picojson: if (STR_DIRECTION == attr_name) { if (STR_RECEIVED == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_DIALED == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_OUTGOING); + } else if (STR_DIALED == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_OUTGOING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_OUTGOING); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_OUTGOING); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_MISSED == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); + } else if (STR_MISSED == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_MISSED_NEW == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING_UNSEEN); + } else if (STR_MISSED_NEW == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING_UNSEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING_UNSEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING_UNSEEN); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_REJECTED == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_REJECT); + } else if (STR_REJECTED == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_REJECT); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_REJECT); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_REJECT); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_BLOCKED == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_BLOCKED); + } else if (STR_BLOCKED == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_BLOCKED); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); contacts_filter_add_filter(filter_top, sub_filter); + } else { + contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_NONE); } - else { - contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_NONE); - } - } - else if (STR_TAGS == attr_name) { + } else if (STR_TAGS == attr_name) { if (STR_CALL == match_value_str) { contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, @@ -421,74 +399,65 @@ static void visitAttribute(std::stack& stack, const picojson: contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_CALL_VOICE == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING); + } else if (STR_CALL_VOICE == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_OUTGOING); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_OUTGOING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING_UNSEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING_UNSEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_INCOMING_SEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_REJECT); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_REJECT); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VOICE_BLOCKED); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VOICE_BLOCKED); contacts_filter_add_filter(filter_top, sub_filter); - } - else if (STR_CALL_VIDEO == match_value_str) { - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING); + } else if (STR_CALL_VIDEO == match_value_str) { + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_OUTGOING); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_OUTGOING); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING_UNSEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING_UNSEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_INCOMING_SEEN); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_REJECT); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_REJECT); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_OR); - contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); + contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); contacts_filter_add_filter(filter_top, sub_filter); + } else if (STR_CALL_EMERGENCY == match_value_str) { + contacts_filter_add_str(filter_top, _contacts_phone_log.extra_data2, CONTACTS_MATCH_EXACTLY, + "001"); + } else { + contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_NONE); } - else if (STR_CALL_EMERGENCY == match_value_str) { - contacts_filter_add_str(filter_top, _contacts_phone_log.extra_data2, - CONTACTS_MATCH_EXACTLY, "001"); - } - else { - contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_NONE); - } - } - else if (STR_RP_REMOTEPARTY == attr_name) { + } else if (STR_RP_REMOTEPARTY == attr_name) { contacts_filter_add_str(filter_top, _contacts_phone_log.address, c_match_flag, match_value_str.c_str()); - } - else if (STR_RP_PERSONID == attr_name) { + } else if (STR_RP_PERSONID == attr_name) { contacts_filter_add_str(filter_top, _contacts_phone_log.person_id, c_match_flag, match_value_str.c_str()); - } - else if (STR_START_TIME == attr_name) { + } else if (STR_START_TIME == attr_name) { LoggerD("DATE _____>>>>>>>>> %s", match_value_str.c_str()); - contacts_filter_add_int(filter_top, _contacts_phone_log.log_time, - CONTACTS_MATCH_EQUAL, static_cast(toTimeT(match_value_str))); - } - else if (STR_DURATION == attr_name) { + contacts_filter_add_int(filter_top, _contacts_phone_log.log_time, CONTACTS_MATCH_EQUAL, + static_cast(toTimeT(match_value_str))); + } else if (STR_DURATION == attr_name) { contacts_filter_add_str(filter_top, _contacts_phone_log.extra_data1, c_match_flag, match_value_str.c_str()); - } - else if (STR_CALL_TYPE == attr_name) { + } else if (STR_CALL_TYPE == attr_name) { if (STR_CALLTYPE_TEL == match_value_str) { contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, @@ -497,31 +466,28 @@ static void visitAttribute(std::stack& stack, const picojson: contacts_filter_add_int(sub_filter, _contacts_phone_log.log_type, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, CONTACTS_PLOG_TYPE_VIDEO_BLOCKED); contacts_filter_add_filter(filter_top, sub_filter); + } else { + contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_NONE); } - else { - contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_NONE); - } - } - else if (STR_ENTRY_ID == attr_name) { + } else if (STR_ENTRY_ID == attr_name) { contacts_filter_add_str(filter_top, _contacts_phone_log.id, c_match_flag, match_value_str.c_str()); - } - else { - contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, - CONTACTS_MATCH_EQUAL, CONTACTS_PLOG_TYPE_NONE); + } else { + contacts_filter_add_int(filter_top, _contacts_phone_log.log_type, CONTACTS_MATCH_EQUAL, + CONTACTS_PLOG_TYPE_NONE); } contacts_filter_destroy(sub_filter); } -static void visitAttributeRange(std::stack& stack, const picojson::object filter) -{ +static void visitAttributeRange(std::stack& stack, + const picojson::object filter) { LoggerD("Entered"); unsigned int prop_id = 0; const auto it_attr_name = filter.find("attributeName"); - const std::string &attr_name = it_attr_name->second.get(); + const std::string& attr_name = it_attr_name->second.get(); if (STR_RP_REMOTEPARTY == attr_name) { prop_id = _contacts_phone_log.address; @@ -568,32 +534,25 @@ static void visitAttributeRange(std::stack& stack, const pico if (_contacts_phone_log.address == prop_id) { if (!is_i_val_null && is_e_val_null) { - contacts_filter_add_str(filter_top, prop_id, CONTACTS_MATCH_STARTSWITH,i_val.c_str()); - } - else if (is_i_val_null && !is_e_val_null) { + contacts_filter_add_str(filter_top, prop_id, CONTACTS_MATCH_STARTSWITH, i_val.c_str()); + } else if (is_i_val_null && !is_e_val_null) { contacts_filter_add_str(filter_top, prop_id, CONTACTS_MATCH_ENDSWITH, e_val.c_str()); - } - else if (!is_i_val_null && !is_e_val_null) { + } else if (!is_i_val_null && !is_e_val_null) { contacts_filter_add_str(sub_filter, prop_id, CONTACTS_MATCH_STARTSWITH, i_val.c_str()); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); contacts_filter_add_str(sub_filter, prop_id, CONTACTS_MATCH_ENDSWITH, e_val.c_str()); contacts_filter_add_filter(filter_top, sub_filter); } - } - else { + } else { int i_val_int = atoi(i_val.c_str()); int e_val_int = atoi(e_val.c_str()); if (!is_i_val_null && is_e_val_null) { - contacts_filter_add_int(filter_top, prop_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, i_val_int); - } - else if (is_i_val_null && !is_e_val_null) { + contacts_filter_add_int(filter_top, prop_id, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, i_val_int); + } else if (is_i_val_null && !is_e_val_null) { contacts_filter_add_int(filter_top, prop_id, CONTACTS_MATCH_LESS_THAN, e_val_int); - } - else if (!is_i_val_null && !is_e_val_null) { - contacts_filter_add_int(sub_filter, prop_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, i_val_int); + } else if (!is_i_val_null && !is_e_val_null) { + contacts_filter_add_int(sub_filter, prop_id, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, i_val_int); contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); contacts_filter_add_int(sub_filter, prop_id, CONTACTS_MATCH_LESS_THAN, e_val_int); contacts_filter_add_filter(filter_top, sub_filter); @@ -602,10 +561,8 @@ static void visitAttributeRange(std::stack& stack, const pico contacts_filter_destroy(sub_filter); } -static void generateFilter(std::stack& stack, - const picojson::object filter, - CompositeTypeEnum type) -{ +static void generateFilter(std::stack& stack, const picojson::object filter, + CompositeTypeEnum type) { LoggerD("Entered"); switch (getFilterType(filter)) { case FILTER_ATTRIBUTE: { @@ -618,8 +575,7 @@ static void generateFilter(std::stack& stack, contacts_filter_add_operator(top_filter, CONTACTS_FILTER_OPERATOR_AND); } } - } - break; + } break; case FILTER_ATTRIBUTE_RANGE: { visitAttributeRange(stack, filter); if (type != NONE) { @@ -630,8 +586,7 @@ static void generateFilter(std::stack& stack, contacts_filter_add_operator(top_filter, CONTACTS_FILTER_OPERATOR_AND); } } - } - break; + } break; case FILTER_COMPOSITE: { contacts_filter_h contact_filter = NULL; contacts_filter_create(_contacts_phone_log._uri, &contact_filter); @@ -640,8 +595,7 @@ static void generateFilter(std::stack& stack, } CompositeTypeEnum composite_type = getCompositeType(filter); - const picojson::array& filters = - filter.find("filters")->second.get(); + const picojson::array& filters = filter.find("filters")->second.get(); for (auto it = filters.begin(); it != filters.end(); ++it) { generateFilter(stack, it->get(), composite_type); @@ -654,21 +608,19 @@ static void generateFilter(std::stack& stack, contacts_filter_add_filter(parent_filter, top_filter); contacts_filter_destroy(top_filter); } - } - break; + } break; case FILTER_UNKNOWN: return; break; } } -void CallHistoryUtils::createFilter(contacts_filter_h filter, const picojson::object filter_obj) -{ +void CallHistoryUtils::createFilter(contacts_filter_h filter, const picojson::object filter_obj) { LoggerD("Entered"); std::stack filter_stack; filter_stack.push(filter); generateFilter(filter_stack, filter_obj, CompositeTypeEnum::NONE); } -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension diff --git a/src/callhistory/callhistory_utils.h b/src/callhistory/callhistory_utils.h old mode 100755 new mode 100644 index 9c9699c..471f9b9 --- a/src/callhistory/callhistory_utils.h +++ b/src/callhistory/callhistory_utils.h @@ -31,11 +31,11 @@ class CallHistoryUtils { public: explicit CallHistoryUtils(CallHistory& history); - void parseRecordList(contacts_list_h *record_list, picojson::array& array); - void parseRecord(contacts_record_h *record, picojson::object& obj); + void parseRecordList(contacts_list_h* record_list, picojson::array& array); + void parseRecord(contacts_record_h* record, picojson::object& obj); void parseLogType(contacts_phone_log_type_e log_type, picojson::object& obj); - void parseRemoteParties(contacts_record_h *record, picojson::object& obj); - void parseCallingParty(contacts_record_h *record, picojson::object& obj); + void parseRemoteParties(contacts_record_h* record, picojson::object& obj); + void parseCallingParty(contacts_record_h* record, picojson::object& obj); unsigned int convertAttributeName(const std::string& attribute_name); void createFilter(contacts_filter_h filter, const picojson::object filter_obj); @@ -43,7 +43,7 @@ class CallHistoryUtils { CallHistory& history_; }; -} // namespace callhistory -} // namespace extension +} // namespace callhistory +} // namespace extension -#endif // CALLHISTORY_CALLHISTORY_UTILS_H_ +#endif // CALLHISTORY_CALLHISTORY_UTILS_H_ diff --git a/src/common/GDBus/auto_gen_interface.h b/src/common/GDBus/auto_gen_interface.h index 14e4dd9..04a0a07 100644 --- a/src/common/GDBus/auto_gen_interface.h +++ b/src/common/GDBus/auto_gen_interface.h @@ -11,315 +11,246 @@ G_BEGIN_DECLS - /* ------------------------------------------------------------------------ */ /* Declarations for org.tizen.system.deviced.display */ -#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY (_auto_gen_org_tizen_system_deviced_display_get_type ()) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY, _auto_genOrgTizenSystemDevicedDisplay)) -#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY)) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY, _auto_genOrgTizenSystemDevicedDisplayIface)) +#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY \ + (_auto_gen_org_tizen_system_deviced_display_get_type()) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY(o) \ + (G_TYPE_CHECK_INSTANCE_CAST((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY, \ + _auto_genOrgTizenSystemDevicedDisplay)) +#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY(o) \ + (G_TYPE_CHECK_INSTANCE_TYPE((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY)) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_GET_IFACE(o) \ + (G_TYPE_INSTANCE_GET_INTERFACE((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY, \ + _auto_genOrgTizenSystemDevicedDisplayIface)) struct __auto_genOrgTizenSystemDevicedDisplay; typedef struct __auto_genOrgTizenSystemDevicedDisplay _auto_genOrgTizenSystemDevicedDisplay; -typedef struct __auto_genOrgTizenSystemDevicedDisplayIface _auto_genOrgTizenSystemDevicedDisplayIface; +typedef struct __auto_genOrgTizenSystemDevicedDisplayIface + _auto_genOrgTizenSystemDevicedDisplayIface; -struct __auto_genOrgTizenSystemDevicedDisplayIface -{ +struct __auto_genOrgTizenSystemDevicedDisplayIface { GTypeInterface parent_iface; - gboolean (*handle_current_brightness) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation); - - gboolean (*handle_custom_brightness) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation); - - gboolean (*handle_hold_brightness) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint arg_brightness); - - gboolean (*handle_lockstate) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - const gchar *arg_state, - const gchar *arg_option1, - const gchar *arg_option2, - gint arg_timeout); - - gboolean (*handle_release_brightness) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation); - - gboolean (*handle_unlockstate) ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - const gchar *arg_state, - const gchar *arg_option); + gboolean (*handle_current_brightness)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation); -}; + gboolean (*handle_custom_brightness)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation); -GType _auto_gen_org_tizen_system_deviced_display_get_type (void) G_GNUC_CONST; + gboolean (*handle_hold_brightness)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation, gint arg_brightness); -GDBusInterfaceInfo *_auto_gen_org_tizen_system_deviced_display_interface_info (void); -guint _auto_gen_org_tizen_system_deviced_display_override_properties (GObjectClass *klass, guint property_id_begin); + gboolean (*handle_lockstate)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation, const gchar *arg_state, + const gchar *arg_option1, const gchar *arg_option2, + gint arg_timeout); + gboolean (*handle_release_brightness)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation); -/* D-Bus method call completion functions: */ -void _auto_gen_org_tizen_system_deviced_display_complete_lockstate ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); + gboolean (*handle_unlockstate)(_auto_genOrgTizenSystemDevicedDisplay *object, + GDBusMethodInvocation *invocation, const gchar *arg_state, + const gchar *arg_option); +}; + +GType _auto_gen_org_tizen_system_deviced_display_get_type(void) G_GNUC_CONST; -void _auto_gen_org_tizen_system_deviced_display_complete_unlockstate ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); +GDBusInterfaceInfo *_auto_gen_org_tizen_system_deviced_display_interface_info(void); +guint _auto_gen_org_tizen_system_deviced_display_override_properties(GObjectClass *klass, + guint property_id_begin); -void _auto_gen_org_tizen_system_deviced_display_complete_release_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); +/* D-Bus method call completion functions: */ +void _auto_gen_org_tizen_system_deviced_display_complete_lockstate( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); -void _auto_gen_org_tizen_system_deviced_display_complete_hold_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); +void _auto_gen_org_tizen_system_deviced_display_complete_unlockstate( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); -void _auto_gen_org_tizen_system_deviced_display_complete_current_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); +void _auto_gen_org_tizen_system_deviced_display_complete_release_brightness( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); -void _auto_gen_org_tizen_system_deviced_display_complete_custom_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *object, - GDBusMethodInvocation *invocation, - gint result); +void _auto_gen_org_tizen_system_deviced_display_complete_hold_brightness( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); +void _auto_gen_org_tizen_system_deviced_display_complete_current_brightness( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); +void _auto_gen_org_tizen_system_deviced_display_complete_custom_brightness( + _auto_genOrgTizenSystemDevicedDisplay *object, GDBusMethodInvocation *invocation, gint result); /* D-Bus method calls: */ -void _auto_gen_org_tizen_system_deviced_display_call_lockstate ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - const gchar *arg_state, - const gchar *arg_option1, - const gchar *arg_option2, - gint arg_timeout, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -gboolean _auto_gen_org_tizen_system_deviced_display_call_lockstate_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, - GError **error); +void _auto_gen_org_tizen_system_deviced_display_call_lockstate( + _auto_genOrgTizenSystemDevicedDisplay *proxy, const gchar *arg_state, const gchar *arg_option1, + const gchar *arg_option2, gint arg_timeout, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); -gboolean _auto_gen_org_tizen_system_deviced_display_call_lockstate_nopt_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - const gchar *arg_state, - const gchar *arg_option1, - const gchar *arg_option2, - gint arg_timeout, - gint *out_result, - GCancellable *cancellable, +gboolean _auto_gen_org_tizen_system_deviced_display_call_lockstate_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -void _auto_gen_org_tizen_system_deviced_display_call_unlockstate ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - const gchar *arg_state, - const gchar *arg_option, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -gboolean _auto_gen_org_tizen_system_deviced_display_call_unlockstate_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, +gboolean _auto_gen_org_tizen_system_deviced_display_call_lockstate_nopt_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, const gchar *arg_state, const gchar *arg_option1, + const gchar *arg_option2, gint arg_timeout, gint *out_result, GCancellable *cancellable, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_unlockstate_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - const gchar *arg_state, - const gchar *arg_option, - gint *out_result, - GCancellable *cancellable, +void _auto_gen_org_tizen_system_deviced_display_call_unlockstate( + _auto_genOrgTizenSystemDevicedDisplay *proxy, const gchar *arg_state, const gchar *arg_option, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); + +gboolean _auto_gen_org_tizen_system_deviced_display_call_unlockstate_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -void _auto_gen_org_tizen_system_deviced_display_call_release_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); +gboolean _auto_gen_org_tizen_system_deviced_display_call_unlockstate_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, const gchar *arg_state, const gchar *arg_option, + gint *out_result, GCancellable *cancellable, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_release_brightness_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, - GError **error); +void _auto_gen_org_tizen_system_deviced_display_call_release_brightness( + _auto_genOrgTizenSystemDevicedDisplay *proxy, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); -gboolean _auto_gen_org_tizen_system_deviced_display_call_release_brightness_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GCancellable *cancellable, +gboolean _auto_gen_org_tizen_system_deviced_display_call_release_brightness_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -void _auto_gen_org_tizen_system_deviced_display_call_hold_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint arg_brightness, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -gboolean _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, +gboolean _auto_gen_org_tizen_system_deviced_display_call_release_brightness_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GCancellable *cancellable, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint arg_brightness, - gint *out_result, - GCancellable *cancellable, +void _auto_gen_org_tizen_system_deviced_display_call_hold_brightness( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint arg_brightness, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + +gboolean _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -void _auto_gen_org_tizen_system_deviced_display_call_current_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); +gboolean _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint arg_brightness, gint *out_result, + GCancellable *cancellable, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_current_brightness_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, +void _auto_gen_org_tizen_system_deviced_display_call_current_brightness( + _auto_genOrgTizenSystemDevicedDisplay *proxy, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + +gboolean _auto_gen_org_tizen_system_deviced_display_call_current_brightness_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_current_brightness_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GCancellable *cancellable, +gboolean _auto_gen_org_tizen_system_deviced_display_call_current_brightness_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GCancellable *cancellable, GError **error); -void _auto_gen_org_tizen_system_deviced_display_call_custom_brightness ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); +void _auto_gen_org_tizen_system_deviced_display_call_custom_brightness( + _auto_genOrgTizenSystemDevicedDisplay *proxy, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); -gboolean _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_finish ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GAsyncResult *res, +gboolean _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_finish( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GAsyncResult *res, GError **error); -gboolean _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_sync ( - _auto_genOrgTizenSystemDevicedDisplay *proxy, - gint *out_result, - GCancellable *cancellable, +gboolean _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_sync( + _auto_genOrgTizenSystemDevicedDisplay *proxy, gint *out_result, GCancellable *cancellable, GError **error); - - /* ---- */ -#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY (_auto_gen_org_tizen_system_deviced_display_proxy_get_type ()) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, _auto_genOrgTizenSystemDevicedDisplayProxy)) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, _auto_genOrgTizenSystemDevicedDisplayProxyClass)) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, _auto_genOrgTizenSystemDevicedDisplayProxyClass)) -#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY)) -#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY)) - -typedef struct __auto_genOrgTizenSystemDevicedDisplayProxy _auto_genOrgTizenSystemDevicedDisplayProxy; -typedef struct __auto_genOrgTizenSystemDevicedDisplayProxyClass _auto_genOrgTizenSystemDevicedDisplayProxyClass; -typedef struct __auto_genOrgTizenSystemDevicedDisplayProxyPrivate _auto_genOrgTizenSystemDevicedDisplayProxyPrivate; - -struct __auto_genOrgTizenSystemDevicedDisplayProxy -{ +#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY \ + (_auto_gen_org_tizen_system_deviced_display_proxy_get_type()) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY(o) \ + (G_TYPE_CHECK_INSTANCE_CAST((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, \ + _auto_genOrgTizenSystemDevicedDisplayProxy)) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_CLASS(k) \ + (G_TYPE_CHECK_CLASS_CAST((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, \ + _auto_genOrgTizenSystemDevicedDisplayProxyClass)) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_GET_CLASS(o) \ + (G_TYPE_INSTANCE_GET_CLASS((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY, \ + _auto_genOrgTizenSystemDevicedDisplayProxyClass)) +#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY(o) \ + (G_TYPE_CHECK_INSTANCE_TYPE((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY)) +#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY_CLASS(k) \ + (G_TYPE_CHECK_CLASS_TYPE((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_PROXY)) + +typedef struct __auto_genOrgTizenSystemDevicedDisplayProxy + _auto_genOrgTizenSystemDevicedDisplayProxy; +typedef struct __auto_genOrgTizenSystemDevicedDisplayProxyClass + _auto_genOrgTizenSystemDevicedDisplayProxyClass; +typedef struct __auto_genOrgTizenSystemDevicedDisplayProxyPrivate + _auto_genOrgTizenSystemDevicedDisplayProxyPrivate; + +struct __auto_genOrgTizenSystemDevicedDisplayProxy { /*< private >*/ GDBusProxy parent_instance; _auto_genOrgTizenSystemDevicedDisplayProxyPrivate *priv; }; -struct __auto_genOrgTizenSystemDevicedDisplayProxyClass -{ +struct __auto_genOrgTizenSystemDevicedDisplayProxyClass { GDBusProxyClass parent_class; }; -GType _auto_gen_org_tizen_system_deviced_display_proxy_get_type (void) G_GNUC_CONST; - -void _auto_gen_org_tizen_system_deviced_display_proxy_new ( - GDBusConnection *connection, - GDBusProxyFlags flags, - const gchar *name, - const gchar *object_path, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); -_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_finish ( - GAsyncResult *res, - GError **error); -_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_sync ( - GDBusConnection *connection, - GDBusProxyFlags flags, - const gchar *name, - const gchar *object_path, - GCancellable *cancellable, - GError **error); - -void _auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus ( - GBusType bus_type, - GDBusProxyFlags flags, - const gchar *name, - const gchar *object_path, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); -_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus_finish ( - GAsyncResult *res, - GError **error); -_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus_sync ( - GBusType bus_type, - GDBusProxyFlags flags, - const gchar *name, - const gchar *object_path, - GCancellable *cancellable, - GError **error); - +GType _auto_gen_org_tizen_system_deviced_display_proxy_get_type(void) G_GNUC_CONST; + +void _auto_gen_org_tizen_system_deviced_display_proxy_new( + GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_finish( + GAsyncResult *res, GError **error); +_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_proxy_new_sync( + GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, + GCancellable *cancellable, GError **error); + +void _auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus( + GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +_auto_genOrgTizenSystemDevicedDisplay * +_auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus_finish(GAsyncResult *res, + GError **error); +_auto_genOrgTizenSystemDevicedDisplay * +_auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus_sync( + GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, + GCancellable *cancellable, GError **error); /* ---- */ -#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON (_auto_gen_org_tizen_system_deviced_display_skeleton_get_type ()) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, _auto_genOrgTizenSystemDevicedDisplaySkeleton)) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, _auto_genOrgTizenSystemDevicedDisplaySkeletonClass)) -#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, _auto_genOrgTizenSystemDevicedDisplaySkeletonClass)) -#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON)) -#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON)) - -typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeleton _auto_genOrgTizenSystemDevicedDisplaySkeleton; -typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeletonClass _auto_genOrgTizenSystemDevicedDisplaySkeletonClass; -typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeletonPrivate _auto_genOrgTizenSystemDevicedDisplaySkeletonPrivate; - -struct __auto_genOrgTizenSystemDevicedDisplaySkeleton -{ +#define _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON \ + (_auto_gen_org_tizen_system_deviced_display_skeleton_get_type()) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON(o) \ + (G_TYPE_CHECK_INSTANCE_CAST((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, \ + _auto_genOrgTizenSystemDevicedDisplaySkeleton)) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_CLASS(k) \ + (G_TYPE_CHECK_CLASS_CAST((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, \ + _auto_genOrgTizenSystemDevicedDisplaySkeletonClass)) +#define _AUTO_GEN_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_GET_CLASS(o) \ + (G_TYPE_INSTANCE_GET_CLASS((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON, \ + _auto_genOrgTizenSystemDevicedDisplaySkeletonClass)) +#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON(o) \ + (G_TYPE_CHECK_INSTANCE_TYPE((o), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON)) +#define _AUTO_GEN_IS_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON_CLASS(k) \ + (G_TYPE_CHECK_CLASS_TYPE((k), _AUTO_GEN_TYPE_ORG_TIZEN_SYSTEM_DEVICED_DISPLAY_SKELETON)) + +typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeleton + _auto_genOrgTizenSystemDevicedDisplaySkeleton; +typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeletonClass + _auto_genOrgTizenSystemDevicedDisplaySkeletonClass; +typedef struct __auto_genOrgTizenSystemDevicedDisplaySkeletonPrivate + _auto_genOrgTizenSystemDevicedDisplaySkeletonPrivate; + +struct __auto_genOrgTizenSystemDevicedDisplaySkeleton { /*< private >*/ GDBusInterfaceSkeleton parent_instance; _auto_genOrgTizenSystemDevicedDisplaySkeletonPrivate *priv; }; -struct __auto_genOrgTizenSystemDevicedDisplaySkeletonClass -{ +struct __auto_genOrgTizenSystemDevicedDisplaySkeletonClass { GDBusInterfaceSkeletonClass parent_class; }; -GType _auto_gen_org_tizen_system_deviced_display_skeleton_get_type (void) G_GNUC_CONST; - -_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_skeleton_new (void); +GType _auto_gen_org_tizen_system_deviced_display_skeleton_get_type(void) G_GNUC_CONST; +_auto_genOrgTizenSystemDevicedDisplay *_auto_gen_org_tizen_system_deviced_display_skeleton_new( + void); G_END_DECLS diff --git a/src/common/GDBus/connection.cpp b/src/common/GDBus/connection.cpp index c5a115d..1cf69e8 100644 --- a/src/common/GDBus/connection.cpp +++ b/src/common/GDBus/connection.cpp @@ -16,37 +16,33 @@ // #include "common/GDBus/connection.h" -#include "common/logger.h" #include +#include "common/logger.h" namespace common { namespace dbus { -Connection& Connection::getInstance() -{ - LoggerD("Entered"); - static Connection instance; - return instance; +Connection& Connection::getInstance() { + LoggerD("Entered"); + static Connection instance; + return instance; } -GDBusConnection* Connection::getDBus() -{ - return m_dbus; +GDBusConnection* Connection::getDBus() { + return m_dbus; } -Connection::Connection() -{ - m_dbus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &m_error); - if (!m_dbus || m_error) { - LoggerE("Could not get connection"); - } - LoggerD("Connection set"); +Connection::Connection() { + m_dbus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &m_error); + if (!m_dbus || m_error) { + LoggerE("Could not get connection"); + } + LoggerD("Connection set"); } -Connection::~Connection() -{ - g_object_unref(m_dbus); +Connection::~Connection() { + g_object_unref(m_dbus); } -} //namespace dbus -} //namespace common +} // namespace dbus +} // namespace common diff --git a/src/common/GDBus/connection.h b/src/common/GDBus/connection.h index 29475fb..8ec275b 100644 --- a/src/common/GDBus/connection.h +++ b/src/common/GDBus/connection.h @@ -24,22 +24,22 @@ namespace common { namespace dbus { class Connection { -public: - static Connection& getInstance(); + public: + static Connection& getInstance(); - GDBusConnection* getDBus(); + GDBusConnection* getDBus(); -private: - Connection(); - Connection(const Connection&); - void operator=(const Connection&); - virtual ~Connection(); + private: + Connection(); + Connection(const Connection&); + void operator=(const Connection&); + virtual ~Connection(); - GDBusConnection* m_dbus; - GError* m_error; + GDBusConnection* m_dbus; + GError* m_error; }; -} //namespace dbus -} //namespace common +} // namespace dbus +} // namespace common #endif diff --git a/src/common/GDBus/gdbus_powerwrapper.cc b/src/common/GDBus/gdbus_powerwrapper.cc index b86bf12..d17a75d 100644 --- a/src/common/GDBus/gdbus_powerwrapper.cc +++ b/src/common/GDBus/gdbus_powerwrapper.cc @@ -1,11 +1,12 @@ #include "common/GDBus/gdbus_powerwrapper.h" -#include "common/logger.h" #include +#include "common/logger.h" -namespace common{ -namespace gdbus{ +namespace common { +namespace gdbus { -GDBusWrapperError::GDBusWrapperError() {} +GDBusWrapperError::GDBusWrapperError() { +} void GDBusWrapperError::ReportError(GError *error) { InitError(); @@ -42,25 +43,22 @@ std::string GDBusWrapperError::Error() { } const std::string GDBusPowerWrapper::kDefaultBusName = "org.tizen.system.deviced"; -const std::string GDBusPowerWrapper::kDefaultObjectPath = - "/Org/Tizen/System/DeviceD/Display"; +const std::string GDBusPowerWrapper::kDefaultObjectPath = "/Org/Tizen/System/DeviceD/Display"; -GDBusPowerWrapper::GDBusPowerWrapper(const std::string &bus_name, - const std::string &object_path, - GBusType bus_type, - GDBusProxyFlags bus_proxy_flags) +GDBusPowerWrapper::GDBusPowerWrapper(const std::string &bus_name, const std::string &object_path, + GBusType bus_type, GDBusProxyFlags bus_proxy_flags) : bus_type_(bus_type), bus_proxy_flags_(bus_proxy_flags), bus_name_(bus_name), object_path_(object_path), proxy_(nullptr), - err_(new GDBusWrapperError()) {} + err_(new GDBusWrapperError()) { +} bool GDBusPowerWrapper::Connect() { GError *error = nullptr; proxy_ = _auto_gen_org_tizen_system_deviced_display_proxy_new_for_bus_sync( - bus_type_, bus_proxy_flags_, bus_name_.c_str(), object_path_.c_str(), - NULL, &error); + bus_type_, bus_proxy_flags_, bus_name_.c_str(), object_path_.c_str(), NULL, &error); if (!proxy_) { err_->ReportError(error); return false; @@ -70,8 +68,7 @@ bool GDBusPowerWrapper::Connect() { bool GDBusPowerWrapper::CurrentBrightness(int *result) { if (!result) { - err_->ReportError( - "Null pointer function CurrentBrightness, parameter: result"); + err_->ReportError("Null pointer function CurrentBrightness, parameter: result"); return false; } if (!IsConnected()) { @@ -80,9 +77,8 @@ bool GDBusPowerWrapper::CurrentBrightness(int *result) { } GError *error = nullptr; gint out_result; - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_current_brightness_sync( - proxy_, &out_result, NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_current_brightness_sync( + proxy_, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -93,8 +89,7 @@ bool GDBusPowerWrapper::CurrentBrightness(int *result) { bool GDBusPowerWrapper::CustomBrightness(int *result) { if (!result) { - err_->ReportError( - "Null pointer in function CustomBrightness, parameter result"); + err_->ReportError("Null pointer in function CustomBrightness, parameter result"); return false; } if (!IsConnected()) { @@ -103,9 +98,8 @@ bool GDBusPowerWrapper::CustomBrightness(int *result) { } GError *error = nullptr; gint out_result; - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_sync( - proxy_, &out_result, NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_custom_brightness_sync( + proxy_, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -116,8 +110,7 @@ bool GDBusPowerWrapper::CustomBrightness(int *result) { bool GDBusPowerWrapper::HoldBrightness(const int brightness, int *result) { if (!result) { - err_->ReportError( - "Null pointer in function HoldBrightness, parameter result"); + err_->ReportError("Null pointer in function HoldBrightness, parameter result"); return false; } if (!IsConnected()) { @@ -128,9 +121,8 @@ bool GDBusPowerWrapper::HoldBrightness(const int brightness, int *result) { GError *error = nullptr; gint out_result; gint in_brightness = static_cast(brightness); - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_sync( - proxy_, in_brightness, &out_result, NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_hold_brightness_sync( + proxy_, in_brightness, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -144,8 +136,7 @@ bool GDBusPowerWrapper::LockState(int *result) { } bool GDBusPowerWrapper::LockStateRaw(const std::string &state, const std::string &option1, - const std::string &option2, const int timeout, - int *result) { + const std::string &option2, const int timeout, int *result) { if (!result) { err_->ReportError("Null pointer in function LockState, parameter result"); return false; @@ -162,10 +153,8 @@ bool GDBusPowerWrapper::LockStateRaw(const std::string &state, const std::string const gint _timeout = static_cast(timeout); gint out_result; - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_lockstate_nopt_sync( - proxy_, arg_state, arg_option1, arg_option2, _timeout, &out_result, - NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_lockstate_nopt_sync( + proxy_, arg_state, arg_option1, arg_option2, _timeout, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -176,8 +165,7 @@ bool GDBusPowerWrapper::LockStateRaw(const std::string &state, const std::string bool GDBusPowerWrapper::ReleaseBrightness(int *result) { if (!result) { - err_->ReportError( - "Null pointer in function ReleaseBrightness, parameter result"); + err_->ReportError("Null pointer in function ReleaseBrightness, parameter result"); return false; } if (!IsConnected()) { @@ -186,9 +174,8 @@ bool GDBusPowerWrapper::ReleaseBrightness(int *result) { } GError *error = nullptr; gint out_result; - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_release_brightness_sync( - proxy_, &out_result, NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_release_brightness_sync( + proxy_, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -201,8 +188,8 @@ bool GDBusPowerWrapper::UnlockState(int *result) { return UnlockStateRaw("lcddim", "keeptimer", result); } -bool GDBusPowerWrapper::UnlockStateRaw(const std::string &state, - const std::string &option, int *result) { +bool GDBusPowerWrapper::UnlockStateRaw(const std::string &state, const std::string &option, + int *result) { if (!result) { err_->ReportError("Null pointer in function UnlockState, parameter result"); return false; @@ -216,9 +203,8 @@ bool GDBusPowerWrapper::UnlockStateRaw(const std::string &state, gint out_result; const gchar *arg_state = static_cast(state.c_str()); const gchar *arg_option = static_cast(option.c_str()); - gboolean ret = - _auto_gen_org_tizen_system_deviced_display_call_unlockstate_sync( - proxy_, arg_state, arg_option, &out_result, NULL, &error); + gboolean ret = _auto_gen_org_tizen_system_deviced_display_call_unlockstate_sync( + proxy_, arg_state, arg_option, &out_result, NULL, &error); if (!ret) { err_->ReportError(error); return false; @@ -227,7 +213,9 @@ bool GDBusPowerWrapper::UnlockStateRaw(const std::string &state, return true; } -std::string GDBusPowerWrapper::GetLastError() { return err_->Error(); } +std::string GDBusPowerWrapper::GetLastError() { + return err_->Error(); +} bool GDBusPowerWrapper::IsConnected() { if (!proxy_) { @@ -243,6 +231,5 @@ GDBusPowerWrapper::~GDBusPowerWrapper() { } } -} //namespace gdbus -} //namespace common - +} // namespace gdbus +} // namespace common diff --git a/src/common/GDBus/gdbus_powerwrapper.h b/src/common/GDBus/gdbus_powerwrapper.h index 0e5f8d9..4aa678d 100644 --- a/src/common/GDBus/gdbus_powerwrapper.h +++ b/src/common/GDBus/gdbus_powerwrapper.h @@ -2,12 +2,12 @@ #define GDBUSWRAPPER_H #include -#include #include +#include #include "auto_gen_interface.h" -namespace common{ -namespace gdbus{ +namespace common { +namespace gdbus { class GDBusWrapperError { public: @@ -59,11 +59,10 @@ class GDBusPowerWrapper { bool LockStateRaw(const std::string &state, const std::string &option1, const std::string &option2, const int timeout, int *result); - bool UnlockStateRaw(const std::string &state, const std::string &option, - int *result); + bool UnlockStateRaw(const std::string &state, const std::string &option, int *result); }; -} //namespace gdbus -} //namespace common +} // namespace gdbus +} // namespace common #endif // GDBUSWRAPPER_H diff --git a/src/common/GDBus/proxy.cpp b/src/common/GDBus/proxy.cpp index 4f6eedd..936a10e 100644 --- a/src/common/GDBus/proxy.cpp +++ b/src/common/GDBus/proxy.cpp @@ -20,123 +20,104 @@ */ #include "common/GDBus/proxy.h" +#include #include "common/logger.h" #include "common/platform_result.h" -#include namespace common { namespace dbus { using namespace common; -Proxy::Proxy(const std::string& proxy_path, - const std::string& proxy_iface, - const std::string& signal_name, - const std::string& signal_path, - const std::string& signal_iface) : - m_conn(Connection::getInstance()), - m_sub_id(0), - m_path(proxy_path), - m_iface(proxy_iface), - m_signal_name(signal_name), - m_signal_path(signal_path), - m_signal_iface(signal_iface), - m_error(NULL), - m_dbus_signal_subscribed(false) -{ - LoggerD("Proxy:\n" - " proxy_path: %s\n proxy_iface: %s" - " signal_name: %s\n signal_path:%s\n signal_iface:%s", - m_path.c_str(), m_iface.c_str(), - m_signal_name.c_str(), m_signal_path.c_str(), m_signal_iface.c_str()); - - const gchar* unique_name = g_dbus_connection_get_unique_name(m_conn.getDBus()); - LoggerD("Generated unique name: %d", unique_name); - - // path and interface are not obligatory to receive, but - // they should be set to send the signals. - m_proxy = g_dbus_proxy_new_sync(m_conn.getDBus(), - G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, - NULL, unique_name, m_path.c_str(), m_iface.c_str(), NULL, &m_error); +Proxy::Proxy(const std::string& proxy_path, const std::string& proxy_iface, + const std::string& signal_name, const std::string& signal_path, + const std::string& signal_iface) + : m_conn(Connection::getInstance()), + m_sub_id(0), + m_path(proxy_path), + m_iface(proxy_iface), + m_signal_name(signal_name), + m_signal_path(signal_path), + m_signal_iface(signal_iface), + m_error(NULL), + m_dbus_signal_subscribed(false) { + LoggerD( + "Proxy:\n" + " proxy_path: %s\n proxy_iface: %s" + " signal_name: %s\n signal_path:%s\n signal_iface:%s", + m_path.c_str(), m_iface.c_str(), m_signal_name.c_str(), m_signal_path.c_str(), + m_signal_iface.c_str()); + + const gchar* unique_name = g_dbus_connection_get_unique_name(m_conn.getDBus()); + LoggerD("Generated unique name: %d", unique_name); + + // path and interface are not obligatory to receive, but + // they should be set to send the signals. + m_proxy = g_dbus_proxy_new_sync(m_conn.getDBus(), G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, NULL, + unique_name, m_path.c_str(), m_iface.c_str(), NULL, &m_error); } -Proxy::~Proxy() -{ - signalUnsubscribe(); +Proxy::~Proxy() { + signalUnsubscribe(); } -void Proxy::signalCallbackProxy(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters, - gpointer user_data) -{ - Proxy* this_ptr = static_cast(user_data); - if (!this_ptr) { - LoggerW("Proxy is null, nothing to do"); - return; - } - - //It is better to log this only when subclass is responsible of handling - //passed signal. If you need it put it into your signalCallback(...) method - //LoggerD("signal: %s from: %s path: %s interface: %s", - // signal_name, sender_name, object_path, interface_name); - this_ptr->signalCallback(connection, sender_name, object_path, interface_name, - signal_name, parameters); +void Proxy::signalCallbackProxy(GDBusConnection* connection, const gchar* sender_name, + const gchar* object_path, const gchar* interface_name, + const gchar* signal_name, GVariant* parameters, + gpointer user_data) { + Proxy* this_ptr = static_cast(user_data); + if (!this_ptr) { + LoggerW("Proxy is null, nothing to do"); + return; + } + + // It is better to log this only when subclass is responsible of handling + // passed signal. If you need it put it into your signalCallback(...) method + // LoggerD("signal: %s from: %s path: %s interface: %s", + // signal_name, sender_name, object_path, interface_name); + this_ptr->signalCallback(connection, sender_name, object_path, interface_name, signal_name, + parameters); } -void Proxy::signalSubscribe() -{ - if(m_dbus_signal_subscribed) { - LoggerW("Proxy has already subscribed for listening DBus signal"); - return; - } - - const char* sender = NULL; - m_sub_id = g_dbus_connection_signal_subscribe(m_conn.getDBus(), - sender, - m_signal_iface.c_str(), - m_signal_name.c_str(), - m_signal_path.c_str(), - NULL, - G_DBUS_SIGNAL_FLAGS_NONE, - signalCallbackProxy, - static_cast(this), - NULL); - LoggerD("g_dbus_connection_signal_subscribe returned id: %d", m_sub_id); - - m_dbus_signal_subscribed = true; +void Proxy::signalSubscribe() { + if (m_dbus_signal_subscribed) { + LoggerW("Proxy has already subscribed for listening DBus signal"); + return; + } + + const char* sender = NULL; + m_sub_id = g_dbus_connection_signal_subscribe(m_conn.getDBus(), sender, m_signal_iface.c_str(), + m_signal_name.c_str(), m_signal_path.c_str(), NULL, + G_DBUS_SIGNAL_FLAGS_NONE, signalCallbackProxy, + static_cast(this), NULL); + LoggerD("g_dbus_connection_signal_subscribe returned id: %d", m_sub_id); + + m_dbus_signal_subscribed = true; } -void Proxy::signalUnsubscribe() -{ - if (!m_dbus_signal_subscribed) { - LoggerW("Proxy hasn't subscribed for listening DBus signal"); - return; - } +void Proxy::signalUnsubscribe() { + if (!m_dbus_signal_subscribed) { + LoggerW("Proxy hasn't subscribed for listening DBus signal"); + return; + } - g_dbus_connection_signal_unsubscribe(m_conn.getDBus(), m_sub_id); - LoggerD("g_dbus_connection_signal_unsubscribe finished"); + g_dbus_connection_signal_unsubscribe(m_conn.getDBus(), m_sub_id); + LoggerD("g_dbus_connection_signal_unsubscribe finished"); - m_dbus_signal_subscribed = false; + m_dbus_signal_subscribed = false; } -const std::string& Proxy::getSignalName() const -{ - return m_signal_name; +const std::string& Proxy::getSignalName() const { + return m_signal_name; } -const std::string& Proxy::getSignalPath() const -{ - return m_signal_path; +const std::string& Proxy::getSignalPath() const { + return m_signal_path; } -const std::string& Proxy::getSignalInterfaceName() const -{ - return m_signal_iface; +const std::string& Proxy::getSignalInterfaceName() const { + return m_signal_iface; } -} //namespace dbus -} //namespace common +} // namespace dbus +} // namespace common diff --git a/src/common/GDBus/proxy.h b/src/common/GDBus/proxy.h index b394974..38125dc 100644 --- a/src/common/GDBus/proxy.h +++ b/src/common/GDBus/proxy.h @@ -22,18 +22,17 @@ #ifndef __TIZEN_DBUS_PROXY_H__ #define __TIZEN_DBUS_PROXY_H__ -#include "common/GDBus/connection.h" +#include #include -#include #include -#include +#include +#include "common/GDBus/connection.h" #include "common/picojson.h" #include "common/platform_result.h" namespace common { namespace dbus { - class Proxy; typedef std::shared_ptr ProxyPtr; @@ -41,74 +40,67 @@ typedef std::shared_ptr ProxyPtr; * This is generic dbus signal listener proxy. */ class Proxy { -public: - - virtual ~Proxy(); - bool isNotProxyGot() { return !m_proxy || m_error; }; - - void signalSubscribe(); - void signalUnsubscribe(); - - const std::string& getSignalName() const; - const std::string& getSignalPath() const; - const std::string& getSignalInterfaceName() const; - -protected: - /** - * @param proxy_path - path of this proxy - * @param proxy_iface - interface name of this proxy - * - * @param signal_name - expected signal name - * @param signal_path - expected signal path - * @param signal_iface - expected signal interface name - */ - Proxy(const std::string& proxy_path, - const std::string& proxy_iface, - const std::string& signal_name, - const std::string& signal_path, - const std::string& signal_iface); - /** - * Please implement this method in subclass to handle signal. - * Executed by static void signalCallbackProxy(...). - */ - virtual void signalCallback(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters) = 0; - -private: - /** - * This method (registered with g_dbus_connection_signal_subscribe) is executed by - * DBus when signal is received. It calls - * (static_cast(user_data))->signalCallback(...) - */ - - static void signalCallbackProxy(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters, - gpointer user_data); - - Connection& m_conn; - guint m_sub_id; - - std::string m_path; - std::string m_iface; - - std::string m_signal_name; - std::string m_signal_path; - std::string m_signal_iface; - - GError* m_error; - GDBusProxy* m_proxy; - bool m_dbus_signal_subscribed; + public: + virtual ~Proxy(); + bool isNotProxyGot() { + return !m_proxy || m_error; + }; + + void signalSubscribe(); + void signalUnsubscribe(); + + const std::string &getSignalName() const; + const std::string &getSignalPath() const; + const std::string &getSignalInterfaceName() const; + + protected: + /** + * @param proxy_path - path of this proxy + * @param proxy_iface - interface name of this proxy + * + * @param signal_name - expected signal name + * @param signal_path - expected signal path + * @param signal_iface - expected signal interface name + */ + Proxy(const std::string &proxy_path, const std::string &proxy_iface, + const std::string &signal_name, const std::string &signal_path, + const std::string &signal_iface); + /** + * Please implement this method in subclass to handle signal. + * Executed by static void signalCallbackProxy(...). + */ + virtual void signalCallback(GDBusConnection *connection, const gchar *sender_name, + const gchar *object_path, const gchar *interface_name, + const gchar *signal_name, GVariant *parameters) = 0; + + private: + /** + * This method (registered with g_dbus_connection_signal_subscribe) is executed by + * DBus when signal is received. It calls + * (static_cast(user_data))->signalCallback(...) + */ + + static void signalCallbackProxy(GDBusConnection *connection, const gchar *sender_name, + const gchar *object_path, const gchar *interface_name, + const gchar *signal_name, GVariant *parameters, + gpointer user_data); + + Connection &m_conn; + guint m_sub_id; + + std::string m_path; + std::string m_iface; + + std::string m_signal_name; + std::string m_signal_path; + std::string m_signal_iface; + + GError *m_error; + GDBusProxy *m_proxy; + bool m_dbus_signal_subscribed; }; -} //namespace dbus -} //namespace common +} // namespace dbus +} // namespace common -#endif // __TIZEN_DBUS_PROXY_H__ +#endif // __TIZEN_DBUS_PROXY_H__ diff --git a/src/common/XW_Extension.cc b/src/common/XW_Extension.cc old mode 100755 new mode 100644 index 7517791..cee62c7 --- a/src/common/XW_Extension.cc +++ b/src/common/XW_Extension.cc @@ -5,15 +5,15 @@ // This file is compiled into each plugin, hence its size should be minimized. -#include "common/extension.h" #include "common/assert.h" +#include "common/extension.h" #include "common/logger.h" namespace { common::Extension* g_extension = nullptr; -} // namespace +} // namespace namespace common { @@ -24,8 +24,7 @@ Extension* GetCurrentExtension() { class Extension::Detail { private: - friend int32_t (::XW_Initialize)(XW_Extension extension, - XW_GetInterface get_interface); + friend int32_t(::XW_Initialize)(XW_Extension extension, XW_GetInterface get_interface); static int32_t XW_Initialize(XW_Extension extension, XW_GetInterface get_interface); @@ -62,12 +61,11 @@ void Extension::Detail::OnShutdown(XW_Extension) { g_extension = nullptr; } -} // namespace common +} // namespace common // Entry point for CrossWalk plugin extern "C" int32_t XW_Initialize(XW_Extension extension, XW_GetInterface get_interface) { - return common::Extension::XW_Initialize(extension, get_interface, - common::Extension::Detail::XW_Initialize, - common::Extension::Detail::OnInstanceCreated, - common::Extension::Detail::OnShutdown); + return common::Extension::XW_Initialize( + extension, get_interface, common::Extension::Detail::XW_Initialize, + common::Extension::Detail::OnInstanceCreated, common::Extension::Detail::OnShutdown); } diff --git a/src/common/XW_Extension.h b/src/common/XW_Extension.h old mode 100755 new mode 100644 index 4543b92..5e6dd9a --- a/src/common/XW_Extension.h +++ b/src/common/XW_Extension.h @@ -29,14 +29,13 @@ extern "C" { #endif #if __GNUC__ >= 4 -#define XW_EXPORT __attribute__ ((visibility("default"))) +#define XW_EXPORT __attribute__((visibility("default"))) #elif defined(_MSC_VER) #define XW_EXPORT __declspec(dllexport) #endif #include - // XW_Extension is used to identify your extension when calling functions from // the API. You should always use the XW_Extension received at XW_Initialize(). // @@ -51,10 +50,7 @@ extern "C" { typedef int32_t XW_Extension; typedef int32_t XW_Instance; -enum { - XW_OK = 0, - XW_ERROR = -1 -}; +enum { XW_OK = 0, XW_ERROR = -1 }; // Returns a struct containing functions to be used by the extension. Those // structs can be stored statically and used until the extension is unloaded. @@ -63,9 +59,7 @@ enum { // interface is not supported. typedef const void* (*XW_GetInterface)(const char* interface_name); - -typedef int32_t (*XW_Initialize_Func)(XW_Extension extension, - XW_GetInterface get_interface); +typedef int32_t (*XW_Initialize_Func)(XW_Extension extension, XW_GetInterface get_interface); // XW_Initialize is called after the extension code is loaded. The 'extension' // value should be used in further calls that expect XW_Extension argument. @@ -76,9 +70,7 @@ typedef int32_t (*XW_Initialize_Func)(XW_Extension extension, // // This function should return XW_OK when the extension was succesfully // loaded, otherwise XW_ERROR. -XW_EXPORT int32_t XW_Initialize(XW_Extension extension, - XW_GetInterface get_interface); - +XW_EXPORT int32_t XW_Initialize(XW_Extension extension, XW_GetInterface get_interface); // // XW_CORE_INTERFACE: Basic functionality for Crosswalk Extensions. All @@ -127,15 +119,13 @@ struct XW_CoreInterface_1 { // get a new associated instance. // // This function should be called only during XW_Initialize(). - void (*RegisterInstanceCallbacks)(XW_Extension extension, - XW_CreatedInstanceCallback created, + void (*RegisterInstanceCallbacks)(XW_Extension extension, XW_CreatedInstanceCallback created, XW_DestroyedInstanceCallback destroyed); // Register a callback to be executed when the extension will be unloaded. // // This function should be called only during XW_Initialize(). - void (*RegisterShutdownCallback)(XW_Extension extension, - XW_ShutdownCallback shutdown_callback); + void (*RegisterShutdownCallback)(XW_Extension extension, XW_ShutdownCallback shutdown_callback); // These two functions are conveniences used to associated arbitrary data // with a given XW_Instance. They can be used only with instances that were @@ -148,7 +138,6 @@ struct XW_CoreInterface_1 { typedef struct XW_CoreInterface_1 XW_CoreInterface; - // // XW_MESSAGING_INTERFACE: Exchange asynchronous messages with JavaScript // code provided by extension. @@ -157,16 +146,14 @@ typedef struct XW_CoreInterface_1 XW_CoreInterface; #define XW_MESSAGING_INTERFACE_1 "XW_MessagingInterface_1" #define XW_MESSAGING_INTERFACE XW_MESSAGING_INTERFACE_1 -typedef void (*XW_HandleMessageCallback)(XW_Instance instance, - const char* message); +typedef void (*XW_HandleMessageCallback)(XW_Instance instance, const char* message); struct XW_MessagingInterface_1 { // Register a callback to be called when the JavaScript code associated // with the extension posts a message. Note that the callback will be called // with the XW_Instance that posted the message as well as the message // contents. - void (*Register)(XW_Extension extension, - XW_HandleMessageCallback handle_message); + void (*Register)(XW_Extension extension, XW_HandleMessageCallback handle_message); // Post a message to the web content associated with the instance. To // receive this message the extension's JavaScript code should set a diff --git a/src/common/XW_Extension_EntryPoints.h b/src/common/XW_Extension_EntryPoints.h old mode 100755 new mode 100644 index b8a3ef4..b64ba4d --- a/src/common/XW_Extension_EntryPoints.h +++ b/src/common/XW_Extension_EntryPoints.h @@ -17,10 +17,8 @@ extern "C" { #endif -#define XW_INTERNAL_ENTRY_POINTS_INTERFACE_1 \ - "XW_Internal_EntryPointsInterface_1" -#define XW_INTERNAL_ENTRY_POINTS_INTERFACE \ - XW_INTERNAL_ENTRY_POINTS_INTERFACE_1 +#define XW_INTERNAL_ENTRY_POINTS_INTERFACE_1 "XW_Internal_EntryPointsInterface_1" +#define XW_INTERNAL_ENTRY_POINTS_INTERFACE XW_INTERNAL_ENTRY_POINTS_INTERFACE_1 // // XW_INTERNAL_ENTRY_POINTS_INTERFACE: provides a way for extensions to add @@ -35,16 +33,13 @@ struct XW_Internal_EntryPointsInterface_1 { // be loaded when they are touched. // // This function should be called only during XW_Initialize(). - void (*SetExtraJSEntryPoints)(XW_Extension extension, - const char** entry_points); + void (*SetExtraJSEntryPoints)(XW_Extension extension, const char** entry_points); }; -typedef struct XW_Internal_EntryPointsInterface_1 - XW_Internal_EntryPointsInterface; +typedef struct XW_Internal_EntryPointsInterface_1 XW_Internal_EntryPointsInterface; #ifdef __cplusplus } // extern "C" #endif #endif // XWALK_EXTENSIONS_PUBLIC_XW_EXTENSION_ENTRYPOINTS_H_ - diff --git a/src/common/XW_Extension_Permissions.h b/src/common/XW_Extension_Permissions.h old mode 100755 new mode 100644 index 781e3a9..2cd4945 --- a/src/common/XW_Extension_Permissions.h +++ b/src/common/XW_Extension_Permissions.h @@ -17,10 +17,8 @@ extern "C" { #endif -#define XW_INTERNAL_PERMISSIONS_INTERFACE_1 \ - "XW_Internal_PermissionsInterface_1" -#define XW_INTERNAL_PERMISSIONS_INTERFACE \ - XW_INTERNAL_PERMISSIONS_INTERFACE_1 +#define XW_INTERNAL_PERMISSIONS_INTERFACE_1 "XW_Internal_PermissionsInterface_1" +#define XW_INTERNAL_PERMISSIONS_INTERFACE XW_INTERNAL_PERMISSIONS_INTERFACE_1 // // XW_INTERNAL_PERMISSIONS_INTERFACE: provides a way for extensions @@ -32,8 +30,7 @@ struct XW_Internal_PermissionsInterface_1 { int (*RegisterPermissions)(XW_Extension extension, const char* perm_table); }; -typedef struct XW_Internal_PermissionsInterface_1 - XW_Internal_PermissionsInterface; +typedef struct XW_Internal_PermissionsInterface_1 XW_Internal_PermissionsInterface; #ifdef __cplusplus } // extern "C" diff --git a/src/common/XW_Extension_Runtime.h b/src/common/XW_Extension_Runtime.h old mode 100755 new mode 100644 index 1c33557..37c1e12 --- a/src/common/XW_Extension_Runtime.h +++ b/src/common/XW_Extension_Runtime.h @@ -17,10 +17,8 @@ extern "C" { #endif -#define XW_INTERNAL_RUNTIME_INTERFACE_1 \ - "XW_Internal_RuntimeInterface_1" -#define XW_INTERNAL_RUNTIME_INTERFACE \ - XW_INTERNAL_RUNTIME_INTERFACE_1 +#define XW_INTERNAL_RUNTIME_INTERFACE_1 "XW_Internal_RuntimeInterface_1" +#define XW_INTERNAL_RUNTIME_INTERFACE XW_INTERNAL_RUNTIME_INTERFACE_1 // // XW_INTERNAL_RUNTIME_INTERFACE: allow extensions to gather information @@ -28,18 +26,14 @@ extern "C" { // struct XW_Internal_RuntimeInterface_1 { - void (*GetRuntimeVariableString)(XW_Extension extension, - const char* key, - char* value, + void (*GetRuntimeVariableString)(XW_Extension extension, const char* key, char* value, size_t value_len); }; -typedef struct XW_Internal_RuntimeInterface_1 - XW_Internal_RuntimeInterface; +typedef struct XW_Internal_RuntimeInterface_1 XW_Internal_RuntimeInterface; #ifdef __cplusplus } // extern "C" #endif #endif // XWALK_EXTENSIONS_PUBLIC_XW_EXTENSION_RUNTIME_H_ - diff --git a/src/common/XW_Extension_SyncMessage.h b/src/common/XW_Extension_SyncMessage.h old mode 100755 new mode 100644 index caa46df..c2d17b3 --- a/src/common/XW_Extension_SyncMessage.h +++ b/src/common/XW_Extension_SyncMessage.h @@ -25,22 +25,17 @@ extern "C" { // handler. // -#define XW_INTERNAL_SYNC_MESSAGING_INTERFACE_1 \ - "XW_InternalSyncMessagingInterface_1" -#define XW_INTERNAL_SYNC_MESSAGING_INTERFACE \ - XW_INTERNAL_SYNC_MESSAGING_INTERFACE_1 +#define XW_INTERNAL_SYNC_MESSAGING_INTERFACE_1 "XW_InternalSyncMessagingInterface_1" +#define XW_INTERNAL_SYNC_MESSAGING_INTERFACE XW_INTERNAL_SYNC_MESSAGING_INTERFACE_1 -typedef void (*XW_HandleSyncMessageCallback)(XW_Instance instance, - const char* message); +typedef void (*XW_HandleSyncMessageCallback)(XW_Instance instance, const char* message); struct XW_Internal_SyncMessagingInterface_1 { - void (*Register)(XW_Extension extension, - XW_HandleSyncMessageCallback handle_sync_message); + void (*Register)(XW_Extension extension, XW_HandleSyncMessageCallback handle_sync_message); void (*SetSyncReply)(XW_Instance instance, const char* reply); }; -typedef struct XW_Internal_SyncMessagingInterface_1 - XW_Internal_SyncMessagingInterface; +typedef struct XW_Internal_SyncMessagingInterface_1 XW_Internal_SyncMessagingInterface; #ifdef __cplusplus } // extern "C" diff --git a/src/common/assert.h b/src/common/assert.h old mode 100755 new mode 100644 index 1e0fd39..f752bbd --- a/src/common/assert.h +++ b/src/common/assert.h @@ -21,14 +21,14 @@ #include "common/logger.h" -#define AssertMsg(condition, message) \ - do { \ - std::string msg(message); \ - if (!(condition)) \ - LoggerE("assert(%s)%s", #condition, \ - !msg.empty() ? std::string(", message: " + msg).c_str() : ""); \ - assert(!!(condition) && message); \ - } while(0) +#define AssertMsg(condition, message) \ + do { \ + std::string msg(message); \ + if (!(condition)) \ + LoggerE("assert(%s)%s", #condition, \ + !msg.empty() ? std::string(", message: " + msg).c_str() : ""); \ + assert(!!(condition) && message); \ + } while (0) #define Assert(condition) AssertMsg(condition, "") diff --git a/src/common/converter.cc b/src/common/converter.cc old mode 100755 new mode 100644 index edb62bf..583ce3d --- a/src/common/converter.cc +++ b/src/common/converter.cc @@ -15,19 +15,18 @@ */ #include "common/converter.h" -#include "common/logger.h" #include #include +#include "common/logger.h" namespace common { -const picojson::value& FindValue(const picojson::object& in, - const char* name) { +const picojson::value& FindValue(const picojson::object& in, const char* name) { LoggerD("Enter"); auto it = in.find(name); if (it == in.end()) { - throw common::UnknownException( - std::string("Failed to find required JSON property: ") + name + "."); + throw common::UnknownException(std::string("Failed to find required JSON property: ") + name + + "."); } return it->second; } @@ -35,12 +34,10 @@ const picojson::value& FindValue(const picojson::object& in, long stol(const std::string& str, std::size_t* pos, int base) { try { return std::stol(str, pos, base); - } - catch (const std::invalid_argument& e) { + } catch (const std::invalid_argument& e) { LoggerE("invalid_argument"); throw common::InvalidValuesException(e.what()); - } - catch (const std::out_of_range& e) { + } catch (const std::out_of_range& e) { LoggerE("InvalidValuesException"); throw common::InvalidValuesException(e.what()); } diff --git a/src/common/converter.h b/src/common/converter.h index 1b9a30d..35b9e1f 100644 --- a/src/common/converter.h +++ b/src/common/converter.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef COMMON_CONVERTER_H_ #define COMMON_CONVERTER_H_ @@ -51,12 +51,10 @@ const T &FromJson(const picojson::object &in, const char *name) { } template -const T &FromJson(const picojson::object &in, const char *name, - Names... names) { +const T &FromJson(const picojson::object &in, const char *name, Names... names) { const picojson::value &v = FindValue(in, name); if (!v.is()) { - throw common::UnknownException( - std::string("Invalid JSON type for property: ") + name + "."); + throw common::UnknownException(std::string("Invalid JSON type for property: ") + name + "."); } return FromJson(v.get(), names...); } diff --git a/src/common/current_application.cc b/src/common/current_application.cc old mode 100755 new mode 100644 index 2720182..c2da8c0 --- a/src/common/current_application.cc +++ b/src/common/current_application.cc @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "common/current_application.h" +#include #include #include -#include #include #include "common/logger.h" @@ -52,11 +52,11 @@ std::string CurrentApplication::GetRoot() const { return root_; } -CurrentApplication::CurrentApplication() : - pid_(getpid()), - app_id_(FetchApplicationId()), - package_id_(FetchPackageId()), - root_(FetchRoot()) { +CurrentApplication::CurrentApplication() + : pid_(getpid()), + app_id_(FetchApplicationId()), + package_id_(FetchPackageId()), + root_(FetchRoot()) { LoggerD("Enter"); } @@ -84,8 +84,8 @@ std::string CurrentApplication::FetchPackageId() const { app_info_h app_info; int err = app_info_create(app_id_.c_str(), &app_info); if (APP_MANAGER_ERROR_NONE != err) { - LoggerE("Can't create app info handle from appId %s: %d (%s)", - app_id_.c_str(), err, get_error_message(err)); + LoggerE("Can't create app info handle from appId %s: %d (%s)", app_id_.c_str(), err, + get_error_message(err)); return std::string(); } SCOPE_EXIT { @@ -95,8 +95,7 @@ std::string CurrentApplication::FetchPackageId() const { char* package = nullptr; err = app_info_get_package(app_info, &package); if (APP_MANAGER_ERROR_NONE != err) { - LoggerE("Can't get package name from app info: %d (%s)", err, - get_error_message(err)); + LoggerE("Can't get package name from app info: %d (%s)", err, get_error_message(err)); } else { package_id = package; } @@ -110,7 +109,7 @@ std::string CurrentApplication::FetchRoot() const { LoggerD("Enter"); char* path = nullptr; - path = app_get_data_path(); + path = app_get_data_path(); if (nullptr == path) { LoggerE("Can't get path from app_get_data_path"); return std::string(); @@ -119,7 +118,7 @@ std::string CurrentApplication::FetchRoot() const { std::string ret(path); free(path); int index = ret.rfind("data"); - ret = ret .substr(0, index-1); + ret = ret.substr(0, index - 1); LoggerD("Exit"); return ret; } diff --git a/src/common/current_application.h b/src/common/current_application.h old mode 100755 new mode 100644 index 9665881..87258d6 --- a/src/common/current_application.h +++ b/src/common/current_application.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef COMMON_CURRENT_APPLICATION_H_ #define COMMON_CURRENT_APPLICATION_H_ diff --git a/src/common/deleter.h b/src/common/deleter.h old mode 100755 new mode 100644 index ce20f79..7db1642 --- a/src/common/deleter.h +++ b/src/common/deleter.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef COMMON_DELETER_H_ #define COMMON_DELETER_H_ @@ -21,33 +21,43 @@ namespace common { -template -struct Deleter -{ - typedef std::function Function; +template +struct Deleter { + typedef std::function Function; - Deleter() : function_(NoDelete) {} - explicit Deleter(Function const& function) : function_(function) {} + Deleter() : function_(NoDelete) { + } + explicit Deleter(Function const &function) : function_(function) { + } - void operator()(T* ptr) const { + void operator()(T *ptr) const { function_(ptr); } - static void CallArrayDelete(T *ptr) { delete[] ptr; }; - static void CallDelete(T *ptr) { delete ptr; } - static void CallFree(T *ptr) { free(ptr); } - static void NoDelete(T *) {} + static void CallArrayDelete(T *ptr) { + delete[] ptr; + }; + static void CallDelete(T *ptr) { + delete ptr; + } + static void CallFree(T *ptr) { + free(ptr); + } + static void NoDelete(T *) { + } -private: + private: Function function_; }; -struct FileDeleter : public Deleter -{ - FileDeleter() : Deleter(CloseFile) {} - explicit FileDeleter(Function const& function) : Deleter(function) {}; +struct FileDeleter : public Deleter { + FileDeleter() : Deleter(CloseFile) { + } + explicit FileDeleter(Function const &function) : Deleter(function){}; - static void CloseFile(FILE *file) { fclose(file); } + static void CloseFile(FILE *file) { + fclose(file); + } }; } // namespace common diff --git a/src/common/extension.cc b/src/common/extension.cc index 93e8c1c..983c73a 100644 --- a/src/common/extension.cc +++ b/src/common/extension.cc @@ -6,16 +6,16 @@ #include "common/extension.h" #include -#include -#include #include +#include +#include #include "common/assert.h" #include "common/logger.h" #include "common/tools.h" // This function is hidden, because each plugin needs to have own implementation. -__attribute__ ((visibility ("hidden"))) common::Extension* CreateExtension() { +__attribute__((visibility("hidden"))) common::Extension* CreateExtension() { common::Extension* e = new common::Extension(); e->SetExtensionName("common"); return e; @@ -40,23 +40,21 @@ bool InitializeInterfaces(XW_GetInterface get_interface) { static bool initialized = false; if (!initialized) { - g_core = reinterpret_cast( - get_interface(XW_CORE_INTERFACE)); + g_core = reinterpret_cast(get_interface(XW_CORE_INTERFACE)); if (!g_core) { LoggerE("Can't initialize extension: error getting Core interface."); return false; } - g_messaging = reinterpret_cast( - get_interface(XW_MESSAGING_INTERFACE)); + g_messaging = + reinterpret_cast(get_interface(XW_MESSAGING_INTERFACE)); if (!g_messaging) { LoggerE("Can't initialize extension: error getting Messaging interface."); return false; } - g_sync_messaging = - reinterpret_cast( - get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE)); + g_sync_messaging = reinterpret_cast( + get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE)); if (!g_sync_messaging) { LoggerE("Can't initialize extension: error getting SyncMessaging interface."); return false; @@ -65,22 +63,25 @@ bool InitializeInterfaces(XW_GetInterface get_interface) { g_entry_points = reinterpret_cast( get_interface(XW_INTERNAL_ENTRY_POINTS_INTERFACE)); if (!g_entry_points) { - LoggerE("NOTE: Entry points interface not available in this version " - "of runtime, ignoring entry point data for extensions."); + LoggerE( + "NOTE: Entry points interface not available in this version " + "of runtime, ignoring entry point data for extensions."); } g_runtime = reinterpret_cast( get_interface(XW_INTERNAL_RUNTIME_INTERFACE)); if (!g_runtime) { - LoggerE("NOTE: runtime interface not available in this version " - "of runtime, ignoring runtime variables for extensions."); + LoggerE( + "NOTE: runtime interface not available in this version " + "of runtime, ignoring runtime variables for extensions."); } g_permission = reinterpret_cast( get_interface(XW_INTERNAL_PERMISSIONS_INTERFACE)); if (!g_permission) { - LoggerE("NOTE: permission interface not available in this version " - "of runtime, ignoring permission for extensions."); + LoggerE( + "NOTE: permission interface not available in this version " + "of runtime, ignoring permission for extensions."); } initialized = true; @@ -113,21 +114,18 @@ void Extension::SetJavaScriptAPI(const char* api) { void Extension::SetExtraJSEntryPoints(const char** entry_points) { LoggerD("Enter"); - if (g_entry_points) - g_entry_points->SetExtraJSEntryPoints(xw_extension_, entry_points); + if (g_entry_points) g_entry_points->SetExtraJSEntryPoints(xw_extension_, entry_points); } bool Extension::RegisterPermissions(const char* perm_table) { LoggerD("Enter"); - if (g_permission) - return g_permission->RegisterPermissions(xw_extension_, perm_table); + if (g_permission) return g_permission->RegisterPermissions(xw_extension_, perm_table); return false; } bool Extension::CheckAPIAccessControl(const char* api_name) { LoggerD("Enter"); - if (g_permission) - return g_permission->CheckAPIAccessControl(xw_extension_, api_name); + if (g_permission) return g_permission->CheckAPIAccessControl(xw_extension_, api_name); return false; } @@ -138,8 +136,7 @@ Instance* Extension::CreateInstance() { std::string Extension::GetRuntimeVariable(const char* var_name, unsigned len) { LoggerD("Enter"); - if (!g_runtime) - return ""; + if (!g_runtime) return ""; std::vector res(len + 1, 0); g_runtime->GetRuntimeVariableString(xw_extension_, var_name, &res[0], len); @@ -149,9 +146,8 @@ std::string Extension::GetRuntimeVariable(const char* var_name, unsigned len) { // To keep compatibilities, two case of formats should be considered in webapi-plugins. // removing double quote to keep compatibilities with new and old wrt std::string value = std::string(res.data()); - if (0 == strncmp(var_name, "app_id", 6) && value.find('"', 0) != std::string::npos - && value.find('"', value.size() -1) != std::string::npos) { - + if (0 == strncmp(var_name, "app_id", 6) && value.find('"', 0) != std::string::npos && + value.find('"', value.size() - 1) != std::string::npos) { value = value.erase(0, 1); value = value.erase(value.size() - 1, 1); } @@ -163,8 +159,7 @@ std::string Extension::GetRuntimeVariable(const char* var_name, unsigned len) { void Extension::OnInstanceCreated(XW_Instance xw_instance, Instance* instance) { LoggerD("Enter"); Assert(!g_core->GetInstanceData(xw_instance)); - if (!instance) - return; + if (!instance) return; instance->xw_instance_ = xw_instance; g_core->SetInstanceData(xw_instance, instance); instance->Initialize(); @@ -173,10 +168,8 @@ void Extension::OnInstanceCreated(XW_Instance xw_instance, Instance* instance) { // static void Extension::OnInstanceDestroyed(XW_Instance xw_instance) { LoggerD("Enter"); - Instance* instance = - reinterpret_cast(g_core->GetInstanceData(xw_instance)); - if (!instance) - return; + Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); + if (!instance) return; instance->xw_instance_ = 0; delete instance; } @@ -184,26 +177,21 @@ void Extension::OnInstanceDestroyed(XW_Instance xw_instance) { // static void Extension::HandleMessage(XW_Instance xw_instance, const char* msg) { LoggerD("Enter"); - Instance* instance = - reinterpret_cast(g_core->GetInstanceData(xw_instance)); - if (!instance) - return; + Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); + if (!instance) return; instance->HandleMessage(msg); } // static void Extension::HandleSyncMessage(XW_Instance xw_instance, const char* msg) { LoggerD("Enter"); - Instance* instance = - reinterpret_cast(g_core->GetInstanceData(xw_instance)); - if (!instance) - return; + Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); + if (!instance) return; instance->HandleSyncMessage(msg); } -//static -int32_t Extension::XW_Initialize(XW_Extension extension, - XW_GetInterface get_interface, +// static +int32_t Extension::XW_Initialize(XW_Extension extension, XW_GetInterface get_interface, XW_Initialize_Func initialize, XW_CreatedInstanceCallback created_instance, XW_ShutdownCallback shutdown) { @@ -224,8 +212,7 @@ int32_t Extension::XW_Initialize(XW_Extension extension, using common::Extension; g_core->RegisterShutdownCallback(extension, shutdown); - g_core->RegisterInstanceCallbacks(extension, created_instance, - Extension::OnInstanceDestroyed); + g_core->RegisterInstanceCallbacks(extension, created_instance, Extension::OnInstanceDestroyed); g_messaging->Register(extension, Extension::HandleMessage); g_sync_messaging->Register(extension, Extension::HandleSyncMessage); return XW_OK; @@ -233,20 +220,14 @@ int32_t Extension::XW_Initialize(XW_Extension extension, std::unordered_set Instance::all_instances_; -Instance::Instance() : - xw_instance_(0) -{ +Instance::Instance() : xw_instance_(0) { LoggerD("Enter"); - { - all_instances_.insert(this); - } + { all_instances_.insert(this); } } Instance::~Instance() { LoggerD("Enter"); - { - all_instances_.erase(this); - } + { all_instances_.erase(this); } Assert(xw_instance_ == 0); } @@ -255,16 +236,16 @@ void Instance::PostMessage(Instance* that, const char* msg) { if (that && all_instances_.end() != all_instances_.find(that)) { that->PostMessage(msg); } else { - LoggerE("Trying to post message to non-existing instance: [%p], ignoring", - that); + LoggerE("Trying to post message to non-existing instance: [%p], ignoring", that); } } void Instance::PostMessage(const char* msg) { LoggerD("Enter"); if (!xw_instance_) { - LoggerE("Ignoring PostMessage() in the constructor or after the " - "instance was destroyed."); + LoggerE( + "Ignoring PostMessage() in the constructor or after the " + "instance was destroyed."); return; } g_messaging->PostMessage(xw_instance_, msg); @@ -273,14 +254,14 @@ void Instance::PostMessage(const char* msg) { void Instance::SendSyncReply(const char* reply) { LoggerD("Enter"); if (!xw_instance_) { - LoggerE("Ignoring SendSyncReply() in the constructor or after the " - "instance was destroyed."); + LoggerE( + "Ignoring SendSyncReply() in the constructor or after the " + "instance was destroyed."); return; } g_sync_messaging->SetSyncReply(xw_instance_, reply); } - ParsedInstance::ParsedInstance() { LoggerD("Enter"); } @@ -368,9 +349,7 @@ void ParsedInstance::HandleMessage(const char* msg, bool is_sync) { picojson::value result = picojson::value(picojson::object()); func(args, result.get()); - if (is_sync) - SendSyncReply(result.serialize().c_str()); - + if (is_sync) SendSyncReply(result.serialize().c_str()); } catch (const PlatformException& e) { return HandleException(e); } catch (const PlatformException* e) { diff --git a/src/common/extension.h b/src/common/extension.h index 0d2b194..907d1df 100644 --- a/src/common/extension.h +++ b/src/common/extension.h @@ -19,18 +19,18 @@ #include -#include -#include #include +#include +#include #include -#include "common/platform_exception.h" -#include "common/platform_result.h" #include "common/XW_Extension.h" #include "common/XW_Extension_EntryPoints.h" #include "common/XW_Extension_Permissions.h" #include "common/XW_Extension_Runtime.h" #include "common/XW_Extension_SyncMessage.h" +#include "common/platform_exception.h" +#include "common/platform_result.h" namespace common { @@ -39,7 +39,6 @@ class Extension; } // namespace common - // This function should be implemented by each extension and should return // an appropriate Extension subclass. common::Extension* CreateExtension(); @@ -70,17 +69,15 @@ class Extension { std::string GetRuntimeVariable(const char* var_name, unsigned len); private: - friend int32_t (::XW_Initialize)(XW_Extension extension, - XW_GetInterface get_interface); + friend int32_t(::XW_Initialize)(XW_Extension extension, XW_GetInterface get_interface); - static int32_t XW_Initialize(XW_Extension extension, - XW_GetInterface get_interface, + static int32_t XW_Initialize(XW_Extension extension, XW_GetInterface get_interface, XW_Initialize_Func initialize, XW_CreatedInstanceCallback created_instance, XW_ShutdownCallback shutdown); // XW_Extension callbacks. - static void OnInstanceCreated(XW_Instance xw_instance, Instance* instance); // modified + static void OnInstanceCreated(XW_Instance xw_instance, Instance* instance); // modified static void OnInstanceDestroyed(XW_Instance xw_instance); static void HandleMessage(XW_Instance xw_instance, const char* msg); static void HandleSyncMessage(XW_Instance xw_instance, const char* msg); @@ -99,11 +96,15 @@ class Instance { void PostMessage(const char* msg); void SendSyncReply(const char* reply); - virtual void Initialize() {} + virtual void Initialize() { + } virtual void HandleMessage(const char* msg) = 0; - virtual void HandleSyncMessage(const char* msg) {} + virtual void HandleSyncMessage(const char* msg) { + } - XW_Instance xw_instance() const { return xw_instance_; } + XW_Instance xw_instance() const { + return xw_instance_; + } private: friend class Extension; @@ -113,8 +114,7 @@ class Instance { XW_Instance xw_instance_; }; -typedef std::function - NativeHandler; +typedef std::function NativeHandler; class ParsedInstance : public Instance { public: diff --git a/src/common/filesystem/filesystem_provider.cc b/src/common/filesystem/filesystem_provider.cc index ff6c26e..882f3f9 100644 --- a/src/common/filesystem/filesystem_provider.cc +++ b/src/common/filesystem/filesystem_provider.cc @@ -22,17 +22,13 @@ namespace common { IFilesystemProvider::IFilesystemProvider() { LoggerD("enter"); - } IFilesystemProvider::~IFilesystemProvider() { LoggerD("enter"); } - -FilesystemProvider::FilesystemProvider() : - provider_ (FilesystemProviderDeviced::Create()) -{ +FilesystemProvider::FilesystemProvider() : provider_(FilesystemProviderDeviced::Create()) { } FilesystemProvider& FilesystemProvider::Create() { @@ -45,8 +41,7 @@ FilesystemProvider::~FilesystemProvider() { LoggerD("Entered"); } -void FilesystemProvider::RegisterDeviceChangeState( - DeviceChangeStateFun callback) { +void FilesystemProvider::RegisterDeviceChangeState(DeviceChangeStateFun callback) { LoggerD("Entered"); provider_.RegisterDeviceChangeState(callback); } @@ -71,14 +66,12 @@ VirtualStorages FilesystemProvider::GetAllStorages() { return provider_.GetAllStorages(); } -std::string FilesystemProvider::GetRealPath( - const std::string& path_or_uri) { +std::string FilesystemProvider::GetRealPath(const std::string& path_or_uri) { LoggerD("Entered"); return FilesystemProviderStorage::Create().GetRealPath(path_or_uri); } -std::string FilesystemProvider::GetVirtualPath( - const std::string& real_path) const { +std::string FilesystemProvider::GetVirtualPath(const std::string& real_path) const { LoggerD("Entered"); return FilesystemProviderStorage::Create().GetVirtualPath(real_path); } diff --git a/src/common/filesystem/filesystem_provider.h b/src/common/filesystem/filesystem_provider.h index 1b3dd92..49bbaa3 100644 --- a/src/common/filesystem/filesystem_provider.h +++ b/src/common/filesystem/filesystem_provider.h @@ -18,10 +18,10 @@ #define COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_H_ #include -#include #include -#include "common/filesystem/filesystem_storage.h" +#include #include "common/filesystem/filesystem_provider_types.h" +#include "common/filesystem/filesystem_storage.h" namespace common { @@ -54,6 +54,7 @@ class FilesystemProvider { std::string GetRealPath(const std::string& path_or_uri); std::string GetVirtualPath(const std::string& real_path) const; + private: FilesystemProvider(); FilesystemProvider(const FilesystemProvider&) = delete; diff --git a/src/common/filesystem/filesystem_provider_deviced.cc b/src/common/filesystem/filesystem_provider_deviced.cc index f3bb5a0..19e7a12 100644 --- a/src/common/filesystem/filesystem_provider_deviced.cc +++ b/src/common/filesystem/filesystem_provider_deviced.cc @@ -17,10 +17,10 @@ #include "common/filesystem/filesystem_provider_deviced.h" #include +#include #include #include #include -#include #include #include #include "common/filesystem/filesystem_storage.h" @@ -37,47 +37,49 @@ static const char* kGetDeviceListMethod = "GetDeviceList"; namespace common { struct DeviceListElem { - DeviceListElem() - : block_type(0), - devnode(nullptr), - syspath(nullptr), - fs_usage(nullptr), - fs_type(nullptr), - fs_version(nullptr), - fs_uuid_enc(nullptr), - readonly(0), - mount_point(nullptr), - state(0), - primary(false), - flags(0), - storage_id(0) {} - - int block_type; - char* devnode; - char* syspath; - char* fs_usage; - char* fs_type; - char* fs_version; - char* fs_uuid_enc; - int readonly; - char* mount_point; - int state; - bool primary; - int flags; - int storage_id; + DeviceListElem() + : block_type(0), + devnode(nullptr), + syspath(nullptr), + fs_usage(nullptr), + fs_type(nullptr), + fs_version(nullptr), + fs_uuid_enc(nullptr), + readonly(0), + mount_point(nullptr), + state(0), + primary(false), + flags(0), + storage_id(0) { + } + + int block_type; + char* devnode; + char* syspath; + char* fs_usage; + char* fs_type; + char* fs_version; + char* fs_uuid_enc; + int readonly; + char* mount_point; + int state; + bool primary; + int flags; + int storage_id; }; struct UsbListElem { UsbListElem() - : usb_devpath(nullptr), - usb_class(0), - usb_subclass(0), - usb_protocol(0), - usb_vendor_id(0), - usb_product_id(0), - usb_manufacturer(nullptr), - usb_product_name(nullptr), - usb_serial(nullptr) {} + : usb_devpath(nullptr), + usb_class(0), + usb_subclass(0), + usb_protocol(0), + usb_vendor_id(0), + usb_product_id(0), + usb_manufacturer(nullptr), + usb_product_name(nullptr), + usb_serial(nullptr) { + } char* usb_devpath; int usb_class; @@ -95,13 +97,13 @@ FilesystemProviderDeviced::~FilesystemProviderDeviced() { UnregisterDeviceChangeState(); } -FilesystemProviderDeviced::FilesystemProviderDeviced() : - dbus_(nullptr), - proxy_(nullptr), - device_changed_callback_(nullptr), - block_signal_subscribe_id_(0), - virtual_roots_provider_(FilesystemProviderStorage::Create()), - is_initialized_(false) { +FilesystemProviderDeviced::FilesystemProviderDeviced() + : dbus_(nullptr), + proxy_(nullptr), + device_changed_callback_(nullptr), + block_signal_subscribe_id_(0), + virtual_roots_provider_(FilesystemProviderStorage::Create()), + is_initialized_(false) { LoggerD("Entered"); GError* error = nullptr; @@ -127,19 +129,18 @@ FilesystemProviderDeviced& FilesystemProviderDeviced::Create() { return instance; } -void FilesystemProviderDeviced::BlockSignalProxy( - GDBusConnection* connection, const gchar* sender_name, - const gchar* object_path, const gchar* interface_name, - const gchar* signal_name, GVariant* parameters, gpointer user_data) { +void FilesystemProviderDeviced::BlockSignalProxy(GDBusConnection* connection, + const gchar* sender_name, const gchar* object_path, + const gchar* interface_name, + const gchar* signal_name, GVariant* parameters, + gpointer user_data) { LoggerD("Entered"); - FilesystemProviderDeviced* instance = - static_cast(user_data); + FilesystemProviderDeviced* instance = static_cast(user_data); DeviceListElem elem; - g_variant_get(parameters, "(issssssisibii)", &elem.block_type, &elem.devnode, - &elem.syspath, &elem.fs_usage, &elem.fs_type, &elem.fs_version, - &elem.fs_uuid_enc, &elem.readonly, &elem.mount_point, - &elem.state, &elem.primary, &elem.flags, &elem.storage_id); + g_variant_get(parameters, "(issssssisibii)", &elem.block_type, &elem.devnode, &elem.syspath, + &elem.fs_usage, &elem.fs_type, &elem.fs_version, &elem.fs_uuid_enc, &elem.readonly, + &elem.mount_point, &elem.state, &elem.primary, &elem.flags, &elem.storage_id); instance->BlockSignalCallback(elem); } @@ -159,11 +160,10 @@ void FilesystemProviderDeviced::BlockSignalCallback(DeviceListElem elem) { } } -void FilesystemProviderDeviced::RegisterDeviceChangeState( - DeviceChangeStateFun _callback) { +void FilesystemProviderDeviced::RegisterDeviceChangeState(DeviceChangeStateFun _callback) { LoggerD("Entered"); - if(!is_initialized_) { + if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return; } @@ -171,9 +171,8 @@ void FilesystemProviderDeviced::RegisterDeviceChangeState( if (device_changed_callback_ == nullptr) { LoggerD("Registering dbus signal subscription"); block_signal_subscribe_id_ = g_dbus_connection_signal_subscribe( - dbus_, nullptr, kBlockManagerIface, kDeviceChangedMethod, - nullptr, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, BlockSignalProxy, this, - nullptr); + dbus_, nullptr, kBlockManagerIface, kDeviceChangedMethod, nullptr, nullptr, + G_DBUS_SIGNAL_FLAGS_NONE, BlockSignalProxy, this, nullptr); } device_changed_callback_ = _callback; } @@ -181,14 +180,14 @@ void FilesystemProviderDeviced::RegisterDeviceChangeState( void FilesystemProviderDeviced::UnregisterDeviceChangeState() { LoggerD("Entered"); - if(!is_initialized_) { + if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return; } if (0 != block_signal_subscribe_id_) { LoggerD("Dbus signal handling unsubscription"); - g_dbus_connection_signal_unsubscribe (dbus_, block_signal_subscribe_id_); + g_dbus_connection_signal_unsubscribe(dbus_, block_signal_subscribe_id_); } device_changed_callback_ = nullptr; } @@ -196,14 +195,12 @@ void FilesystemProviderDeviced::UnregisterDeviceChangeState() { std::shared_ptr FilesystemProviderDeviced::GetStorage(const DeviceListElem& elem) { LoggerD("Entered"); return std::make_shared(GetIdFromUUID(elem.fs_uuid_enc), - (elem.block_type ? StorageType::kMmc : StorageType::kUsbDevice), - (elem.state ? StorageState::kMounted : StorageState::kUnmounted), - elem.mount_point, - GetNameFromPath(elem.devnode)); + (elem.block_type ? StorageType::kMmc : StorageType::kUsbDevice), + (elem.state ? StorageState::kMounted : StorageState::kUnmounted), + elem.mount_point, GetNameFromPath(elem.devnode)); } -std::string FilesystemProviderDeviced::GetNameFromPath( - const char* const char_path) { +std::string FilesystemProviderDeviced::GetNameFromPath(const char* const char_path) { LoggerD("Entered"); std::string path = char_path; std::string name = "removable_"; @@ -219,12 +216,12 @@ std::string FilesystemProviderDeviced::GetNameFromPath( int FilesystemProviderDeviced::GetIdFromUUID(const char* const char_uuid) { LoggerD("Entered"); - return (int)std::hash()( std::string(char_uuid) ); + return (int)std::hash()(std::string(char_uuid)); } Storages FilesystemProviderDeviced::GetStorages() { LoggerD("Entered"); - if(!is_initialized_) { + if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return Storages(); } @@ -235,17 +232,9 @@ Storages FilesystemProviderDeviced::GetStorages() { // external storages are gathered using deviced implementation Storages result; GError* error = nullptr; - GVariant* variant = g_dbus_connection_call_sync(dbus_, - kBus, - kPath, - kBlockManagerIface, - kGetDeviceListMethod, - g_variant_new("(s)", "all"), - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); + GVariant* variant = g_dbus_connection_call_sync(dbus_, kBus, kPath, kBlockManagerIface, + kGetDeviceListMethod, g_variant_new("(s)", "all"), + NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (!variant || error) { std::string message = error ? error->message : ""; LoggerE("Failed to call GetDeviceList method - %s", message.c_str()); @@ -262,16 +251,14 @@ Storages FilesystemProviderDeviced::GetStorages() { Storages FilesystemProviderDeviced::GetStoragesFromGVariant(GVariant* variant) { LoggerD("Entered"); Storages storages; - GVariantIter *iter; + GVariantIter* iter; g_variant_get(variant, "(a(issssssisibii))", &iter); DeviceListElem elem; - while (g_variant_iter_loop(iter, "(issssssisibii)", - &elem.block_type, &elem.devnode, &elem.syspath, - &elem.fs_usage, &elem.fs_type, - &elem.fs_version, &elem.fs_uuid_enc, - &elem.readonly, &elem.mount_point, - &elem.state, &elem.primary, &elem.flags, &elem.storage_id)) { + while (g_variant_iter_loop(iter, "(issssssisibii)", &elem.block_type, &elem.devnode, + &elem.syspath, &elem.fs_usage, &elem.fs_type, &elem.fs_version, + &elem.fs_uuid_enc, &elem.readonly, &elem.mount_point, &elem.state, + &elem.primary, &elem.flags, &elem.storage_id)) { SLoggerD("##### DEVICE INFO #####"); SLoggerD("# block_type : (%d)", elem.block_type); SLoggerD("# devnode : (%s)", elem.devnode); @@ -296,7 +283,7 @@ Storages FilesystemProviderDeviced::GetStoragesFromGVariant(GVariant* variant) { VirtualRoots FilesystemProviderDeviced::GetVirtualPaths() { LoggerD("Entered"); - if(!is_initialized_) { + if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return VirtualRoots(); } @@ -307,7 +294,7 @@ VirtualRoots FilesystemProviderDeviced::GetVirtualPaths() { VirtualStorages FilesystemProviderDeviced::GetAllStorages() { LoggerD("Entered"); - if(!is_initialized_) { + if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return VirtualStorages(); } diff --git a/src/common/filesystem/filesystem_provider_deviced.h b/src/common/filesystem/filesystem_provider_deviced.h index 388e6c5..2c47aa6 100644 --- a/src/common/filesystem/filesystem_provider_deviced.h +++ b/src/common/filesystem/filesystem_provider_deviced.h @@ -21,14 +21,14 @@ #include #include -#include #include #include #include +#include -#include "common/filesystem/filesystem_storage.h" #include "common/filesystem/filesystem_provider.h" #include "common/filesystem/filesystem_provider_storage.h" +#include "common/filesystem/filesystem_storage.h" namespace common { @@ -37,7 +37,6 @@ struct UsbListElem; class FilesystemProviderDeviced : public IFilesystemProvider { public: - virtual ~FilesystemProviderDeviced(); virtual void RegisterDeviceChangeState(DeviceChangeStateFun _callback); virtual void UnregisterDeviceChangeState(); @@ -49,11 +48,9 @@ class FilesystemProviderDeviced : public IFilesystemProvider { private: FilesystemProviderDeviced(); - static void BlockSignalProxy(GDBusConnection* connection, - const gchar* sender_name, const gchar* object_path, - const gchar* interface_name, - const gchar* signal_name, GVariant* parameters, - gpointer user_data); + static void BlockSignalProxy(GDBusConnection* connection, const gchar* sender_name, + const gchar* object_path, const gchar* interface_name, + const gchar* signal_name, GVariant* parameters, gpointer user_data); void BlockSignalCallback(DeviceListElem elem); static std::string GetNameFromPath(const char* const char_path); diff --git a/src/common/filesystem/filesystem_provider_storage.cc b/src/common/filesystem/filesystem_provider_storage.cc index a26cc3f..a744dc9 100644 --- a/src/common/filesystem/filesystem_provider_storage.cc +++ b/src/common/filesystem/filesystem_provider_storage.cc @@ -15,11 +15,11 @@ */ #include "common/filesystem/filesystem_provider_storage.h" +#include #include #include -#include -#include "common/logger.h" #include "common/current_application.h" +#include "common/logger.h" namespace { @@ -36,13 +36,13 @@ const std::string kVirtualRootWgtPrivateTmp = "wgt-private-tmp"; const std::string kVirtualRootMedia = "internal0"; const std::map kStorageDirectories = { - { STORAGE_DIRECTORY_CAMERA, &kVirtualRootCamera }, - { STORAGE_DIRECTORY_DOCUMENTS, &kVirtualRootDocuments }, - { STORAGE_DIRECTORY_DOWNLOADS, &kVirtualRootDownloads }, - { STORAGE_DIRECTORY_IMAGES, &kVirtualRootImages }, - { STORAGE_DIRECTORY_MUSIC, &kVirtualRootMusic }, - { STORAGE_DIRECTORY_SYSTEM_RINGTONES, &kVirtualRootRingtones }, - { STORAGE_DIRECTORY_VIDEOS, &kVirtualRootVideos } }; + {STORAGE_DIRECTORY_CAMERA, &kVirtualRootCamera}, + {STORAGE_DIRECTORY_DOCUMENTS, &kVirtualRootDocuments}, + {STORAGE_DIRECTORY_DOWNLOADS, &kVirtualRootDownloads}, + {STORAGE_DIRECTORY_IMAGES, &kVirtualRootImages}, + {STORAGE_DIRECTORY_MUSIC, &kVirtualRootMusic}, + {STORAGE_DIRECTORY_SYSTEM_RINGTONES, &kVirtualRootRingtones}, + {STORAGE_DIRECTORY_VIDEOS, &kVirtualRootVideos}}; const std::string kFileUriPrefix = "file://"; @@ -50,14 +50,13 @@ const std::string kFileUriPrefix = "file://"; namespace common { -StorageState TranslateCoreStorageState( - storage_state_e coreStorageState) { +StorageState TranslateCoreStorageState(storage_state_e coreStorageState) { LoggerD("Entered"); StorageState state = StorageState::kUnknown; if (coreStorageState == STORAGE_STATE_REMOVED) { state = StorageState::kUnmounted; - } else if (coreStorageState == STORAGE_STATE_MOUNTED - || coreStorageState == STORAGE_STATE_MOUNTED_READ_ONLY) { + } else if (coreStorageState == STORAGE_STATE_MOUNTED || + coreStorageState == STORAGE_STATE_MOUNTED_READ_ONLY) { state = StorageState::kMounted; } else { state = StorageState::kUnmountable; @@ -69,9 +68,8 @@ StorageState TranslateCoreStorageState( void OnStorageChange(int storage_id, storage_state_e state, void* user_data) { LoggerD("Entered, id: %d", storage_id); - FilesystemProviderStorage* provider = - static_cast(user_data); - for (auto &storage : provider->GetStorages()) { + FilesystemProviderStorage* provider = static_cast(user_data); + for (auto& storage : provider->GetStorages()) { if (storage->id_ == storage_id) { StorageState previous_state = storage->state_; storage->state_ = TranslateCoreStorageState(state); @@ -83,17 +81,15 @@ void OnStorageChange(int storage_id, storage_state_e state, void* user_data) { } } -bool OnForeachStorage(int storage_id, storage_type_e type, - storage_state_e state, const char* path, +bool OnForeachStorage(int storage_id, storage_type_e type, storage_state_e state, const char* path, void* user_data) { LoggerD("Entered, id: %d", storage_id); - FilesystemProviderStorage* provider = - static_cast(user_data); + FilesystemProviderStorage* provider = static_cast(user_data); // handling only internal storages (external are handled with deviced api) if (STORAGE_TYPE_INTERNAL == type) { - provider->AddStorage( - std::make_shared(storage_id, StorageType::kInternal, TranslateCoreStorageState(state), path)); + provider->AddStorage(std::make_shared(storage_id, StorageType::kInternal, + TranslateCoreStorageState(state), path)); provider->FillVirtualPaths(storage_id); } return true; @@ -140,17 +136,13 @@ void FilesystemProviderStorage::FillVirtualPaths(int storage_id) { // fill also virtual paths based on current application install dir std::string root = common::CurrentApplication::GetInstance().GetRoot(); if (!root.empty()) { - virtual_paths_.push_back( - VirtualRoot(kVirtualRootWgtPackage, root + "/res/wgt")); - virtual_paths_.push_back( - VirtualRoot(kVirtualRootWgtPrivate, root + "/data")); - virtual_paths_.push_back( - VirtualRoot(kVirtualRootWgtPrivateTmp, root + "/tmp")); + virtual_paths_.push_back(VirtualRoot(kVirtualRootWgtPackage, root + "/res/wgt")); + virtual_paths_.push_back(VirtualRoot(kVirtualRootWgtPrivate, root + "/data")); + virtual_paths_.push_back(VirtualRoot(kVirtualRootWgtPrivateTmp, root + "/tmp")); } } -void FilesystemProviderStorage::RegisterDeviceChangeState( - DeviceChangeStateFun callback) { +void FilesystemProviderStorage::RegisterDeviceChangeState(DeviceChangeStateFun callback) { LoggerD("Entered"); listener_ = callback; } @@ -170,8 +162,7 @@ VirtualRoots FilesystemProviderStorage::GetVirtualPaths() { return virtual_paths_; } -std::string FilesystemProviderStorage::GetRealPath( - const std::string& path_or_uri) { +std::string FilesystemProviderStorage::GetRealPath(const std::string& path_or_uri) { LoggerD("Enter"); std::string realpath; std::size_t pos = path_or_uri.find(kFileUriPrefix); @@ -183,10 +174,9 @@ std::string FilesystemProviderStorage::GetRealPath( pos = realpath.find('/'); if (pos != 0) { const std::string prefix = realpath.substr(0, pos); - const auto it = std::find_if(virtual_paths_.begin(), virtual_paths_.end(), - [prefix](const common::VirtualRoot & vr) { - return vr.name_ == prefix; - }); + const auto it = + std::find_if(virtual_paths_.begin(), virtual_paths_.end(), + [prefix](const common::VirtualRoot& vr) { return vr.name_ == prefix; }); if (it != virtual_paths_.end()) { realpath.replace(0, prefix.size(), it->path_); } else { @@ -196,8 +186,7 @@ std::string FilesystemProviderStorage::GetRealPath( return realpath; } -std::string FilesystemProviderStorage::GetVirtualPath( - const std::string& real_path) const { +std::string FilesystemProviderStorage::GetVirtualPath(const std::string& real_path) const { LoggerD("Enter"); for (const auto& kv : virtual_paths_) { if (0 == real_path.compare(0, kv.path_.size(), kv.path_)) { @@ -215,7 +204,7 @@ VirtualStorages FilesystemProviderStorage::GetAllStorages() { } for (auto virtualRoot : virtual_paths_) { - vs.push_back(std::make_shared < VirtualRoot > (virtualRoot)); + vs.push_back(std::make_shared(virtualRoot)); } return vs; diff --git a/src/common/filesystem/filesystem_provider_storage.h b/src/common/filesystem/filesystem_provider_storage.h index 2198200..49095af 100644 --- a/src/common/filesystem/filesystem_provider_storage.h +++ b/src/common/filesystem/filesystem_provider_storage.h @@ -17,10 +17,10 @@ #ifndef COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_STORAGE_H_ #define COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_STORAGE_H_ -#include #include -#include "common/filesystem/filesystem_provider_types.h" +#include #include "common/filesystem/filesystem_provider.h" +#include "common/filesystem/filesystem_provider_types.h" namespace common { diff --git a/src/common/filesystem/filesystem_provider_types.h b/src/common/filesystem/filesystem_provider_types.h index ca3c5c6..10580b7 100644 --- a/src/common/filesystem/filesystem_provider_types.h +++ b/src/common/filesystem/filesystem_provider_types.h @@ -2,18 +2,17 @@ #define COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_TYPES_H_ #include -#include #include +#include #include "common/filesystem/filesystem_storage.h" namespace common { -typedef std::function< - void(common::Storage, common::StorageState, - common::StorageState)> DeviceChangeStateFun; -typedef std::vector > Storages; +typedef std::function + DeviceChangeStateFun; +typedef std::vector> Storages; typedef std::vector VirtualRoots; -typedef std::vector > VirtualStorages; +typedef std::vector> VirtualStorages; } // namespace common #endif // COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_TYPES_H_ diff --git a/src/common/filesystem/filesystem_storage.cc b/src/common/filesystem/filesystem_storage.cc index 1ea9563..a776e69 100644 --- a/src/common/filesystem/filesystem_storage.cc +++ b/src/common/filesystem/filesystem_storage.cc @@ -20,19 +20,15 @@ namespace common { -VirtualRoot::VirtualRoot(std::string const& name, std::string const& path, - StorageType type, StorageState state) - : name_(name), - path_(path), - type_(type), - state_(state) { +VirtualRoot::VirtualRoot(std::string const& name, std::string const& path, StorageType type, + StorageState state) + : name_(name), path_(path), type_(type), state_(state) { LoggerD("Entered"); } -Storage::Storage(int id, StorageType type, StorageState state, - std::string const& path, std::string const& name) - : VirtualRoot(name, path, type, state), - id_(id) { +Storage::Storage(int id, StorageType type, StorageState state, std::string const& path, + std::string const& name) + : VirtualRoot(name, path, type, state), id_(id) { LoggerD("Enter"); if (name_ == "") { switch (type) { @@ -55,7 +51,7 @@ Storage::Storage(int id, StorageType type, StorageState state, picojson::value VirtualRoot::ToJson() const { LoggerD("Entered"); - picojson::value v { picojson::object { } }; + picojson::value v{picojson::object{}}; picojson::object& obj = v.get(); obj["type"] = picojson::value(ToString(type_)); @@ -74,8 +70,7 @@ picojson::value Storage::ToJson() const { return value; } -Storage::Storage(Storage const& other) - : VirtualRoot(other) { +Storage::Storage(Storage const& other) : VirtualRoot(other) { LoggerD("Entered"); this->id_ = other.id_; } diff --git a/src/common/filesystem/filesystem_storage.h b/src/common/filesystem/filesystem_storage.h index 806d0b2..9628977 100644 --- a/src/common/filesystem/filesystem_storage.h +++ b/src/common/filesystem/filesystem_storage.h @@ -22,20 +22,9 @@ namespace common { -enum class StorageState { - kMounted, - kUnmounted, - kUnmountable, - kUnknown -}; +enum class StorageState { kMounted, kUnmounted, kUnmountable, kUnknown }; -enum class StorageType { - kUnknown, - kInternal, - kUsbDevice, - kUsbHost, - kMmc -}; +enum class StorageType { kUnknown, kInternal, kUsbDevice, kUsbHost, kMmc }; class VirtualStorage { public: @@ -51,8 +40,9 @@ class VirtualStorage { class VirtualRoot : public VirtualStorage { public: - VirtualRoot(std::string const& name, std::string const & path, - StorageType type = StorageType::kInternal, StorageState state = StorageState::kMounted); + VirtualRoot(std::string const& name, std::string const& path, + StorageType type = StorageType::kInternal, + StorageState state = StorageState::kMounted); VirtualRoot(VirtualRoot const& other); std::string name_; @@ -60,16 +50,16 @@ class VirtualRoot : public VirtualStorage { StorageType type_; StorageState state_; virtual picojson::value ToJson() const; - virtual std::string path() const{ + virtual std::string path() const { return path_; } virtual std::string name() const { return name_; } - virtual StorageType type() const{ + virtual StorageType type() const { return type_; } - virtual StorageState state() const{ + virtual StorageState state() const { return state_; } @@ -82,8 +72,8 @@ class Storage : public VirtualRoot { virtual ~Storage() { } - Storage(int id, StorageType type, StorageState state, - std::string const& path = "", std::string const& name = ""); + Storage(int id, StorageType type, StorageState state, std::string const& path = "", + std::string const& name = ""); Storage(Storage const& other); int id_; diff --git a/src/common/filter-utils.cc b/src/common/filter-utils.cc old mode 100755 new mode 100644 index 9859d90..9bc7441 --- a/src/common/filter-utils.cc +++ b/src/common/filter-utils.cc @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "common/filter-utils.h" -#include "common/logger.h" #include "common/converter.h" +#include "common/logger.h" namespace common { -PlatformResult AttributeMatchFlagFromString( - const std::string &str, AttributeMatchFlag *filter_match_flag) { +PlatformResult AttributeMatchFlagFromString(const std::string &str, + AttributeMatchFlag *filter_match_flag) { LoggerD("Enter"); if (str == "EXACTLY") { *filter_match_flag = AttributeMatchFlag::kExactly; @@ -38,15 +38,14 @@ PlatformResult AttributeMatchFlagFromString( *filter_match_flag = AttributeMatchFlag::kExists; } else { LoggerE("Invalid attribute match string: %i", str.c_str()); - return PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid attribute match string!"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid attribute match string!"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CompositeFilterTypeFromString( - const std::string &str, CompositeFilterType *comp_filter_type) { +PlatformResult CompositeFilterTypeFromString(const std::string &str, + CompositeFilterType *comp_filter_type) { LoggerD("Enter"); if (str == "UNION") { *comp_filter_type = CompositeFilterType::kUnion; @@ -55,8 +54,7 @@ PlatformResult CompositeFilterTypeFromString( } else { LoggerE("Invalid composite type string: %i", str.c_str()); - return PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid composite type string!"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid composite type string!"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -96,22 +94,19 @@ PlatformResult FilterVisitor::Visit(const picojson::object &filter) { if (status.IsError()) return status; } else { LoggerE("Invalid filter type!"); - return PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid filter type!"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid filter type!"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult FilterVisitor::VisitAttributeFilter( - const picojson::object &filter) { +PlatformResult FilterVisitor::VisitAttributeFilter(const picojson::object &filter) { LoggerD("Enter"); - const std::string &attribute_name = - FromJson(filter, "attributeName"); + const std::string &attribute_name = FromJson(filter, "attributeName"); AttributeMatchFlag match_flag; - PlatformResult status = AttributeMatchFlagFromString( - FromJson(filter, "matchFlag"), &match_flag); + PlatformResult status = + AttributeMatchFlagFromString(FromJson(filter, "matchFlag"), &match_flag); if (status.IsError()) return status; const picojson::value &match_value = FindValue(filter, "matchValue"); @@ -124,29 +119,25 @@ PlatformResult FilterVisitor::VisitAttributeFilter( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult FilterVisitor::VisitAttributeRangeFilter( - const picojson::object &filter) { +PlatformResult FilterVisitor::VisitAttributeRangeFilter(const picojson::object &filter) { LoggerD("Enter"); - const std::string &attributeName = - FromJson(filter, "attributeName"); + const std::string &attributeName = FromJson(filter, "attributeName"); const picojson::value &initialValue = FindValue(filter, "initialValue"); const picojson::value &endValue = FindValue(filter, "endValue"); if (m_attributeRangeFilterOnVisit) { - PlatformResult status = - m_attributeRangeFilterOnVisit(attributeName, initialValue, endValue); + PlatformResult status = m_attributeRangeFilterOnVisit(attributeName, initialValue, endValue); if (status.IsError()) return status; } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult FilterVisitor::VisitCompositeFilter( - const picojson::object &filter) { +PlatformResult FilterVisitor::VisitCompositeFilter(const picojson::object &filter) { LoggerD("Enter"); CompositeFilterType filter_type; - PlatformResult status = CompositeFilterTypeFromString( - FromJson(filter, "type"), &filter_type); + PlatformResult status = + CompositeFilterTypeFromString(FromJson(filter, "type"), &filter_type); if (status.IsError()) return status; const picojson::array &filters = FromJson(filter, "filters"); @@ -168,5 +159,4 @@ PlatformResult FilterVisitor::VisitCompositeFilter( return PlatformResult(ErrorCode::NO_ERROR); } - } diff --git a/src/common/filter-utils.h b/src/common/filter-utils.h old mode 100755 new mode 100644 index daa7cc4..756622c --- a/src/common/filter-utils.h +++ b/src/common/filter-utils.h @@ -26,31 +26,21 @@ namespace common { enum PrimitiveType { - kPrimitiveTypeBoolean, - kPrimitiveTypeString, - kPrimitiveTypeLong, - kPrimitiveTypeId + kPrimitiveTypeBoolean, + kPrimitiveTypeString, + kPrimitiveTypeLong, + kPrimitiveTypeId }; -enum class AttributeMatchFlag { - kExactly, - kFullString, - kContains, - kStartsWith, - kEndsWith, - kExists -}; +enum class AttributeMatchFlag { kExactly, kFullString, kContains, kStartsWith, kEndsWith, kExists }; -PlatformResult AttributeMatchFlagFromString( - const std::string& str, AttributeMatchFlag* filter_match_flag); +PlatformResult AttributeMatchFlagFromString(const std::string& str, + AttributeMatchFlag* filter_match_flag); -enum class CompositeFilterType { - kUnion, - kIntersection -}; +enum class CompositeFilterType { kUnion, kIntersection }; -PlatformResult CompositeFilterTypeFromString( - const std::string& str, CompositeFilterType* comp_filter_type); +PlatformResult CompositeFilterTypeFromString(const std::string& str, + CompositeFilterType* comp_filter_type); typedef std::function @@ -60,8 +50,7 @@ typedef std::function AttributeRangeFilterOnVisit; -typedef std::function - CompositeFilterOnBegin; +typedef std::function CompositeFilterOnBegin; typedef std::function CompositeFilterOnEnd; @@ -71,57 +60,57 @@ typedef std::function CompositeFilterOnEnd; * User should set callbacks to react on each of Tizen filters detected. */ class FilterVisitor { - public: - /** - * @brief Sets callback to be invoked on AttributeFilter. - * - * @param[in] func - callback with arguments: - * - std::string AttributeName - * - AttributeMatchFlag flag - * - picojson::value matchValue - */ - void SetOnAttributeFilter(const AttributeFilterOnVisit& func); - - /** - * @brief Sets callback to be invoked on AttributeRangeFilter. - * - * @param[in] func - callback with arguments: - * - std::string AttributeName - * - picojson::value initialValue - * - picojson::value endValue - */ - void SetOnAttributeRangeFilter(const AttributeRangeFilterOnVisit& func); - - /** - * @brief Sets callback to be invoked on begin of CompositeFilter. - * - * @param[in] func - callback with arguments: - * - CompositeFilterType type - */ - void SetOnCompositeFilterBegin(const CompositeFilterOnBegin& func); - - /** - * @brief Sets callback to be invoked on end of CompositeFilter. - * - * @param[in] func - callback with no arguments - */ - void SetOnCompositeFilterEnd(const CompositeFilterOnEnd& func); - - /** - * @brief Parses a json object as Tizen filter. - * @param filter Object to be visited - */ - PlatformResult Visit(const picojson::object& filter); - -private: - PlatformResult VisitAttributeFilter(const picojson::object& filter); - PlatformResult VisitAttributeRangeFilter(const picojson::object& filter); - PlatformResult VisitCompositeFilter(const picojson::object& filter); - - AttributeFilterOnVisit m_attributeFilterOnVisit; - AttributeRangeFilterOnVisit m_attributeRangeFilterOnVisit; - CompositeFilterOnBegin m_compositeFilterOnBegin; - CompositeFilterOnEnd m_compositeFilterOnEnd; + public: + /** + * @brief Sets callback to be invoked on AttributeFilter. + * + * @param[in] func - callback with arguments: + * - std::string AttributeName + * - AttributeMatchFlag flag + * - picojson::value matchValue + */ + void SetOnAttributeFilter(const AttributeFilterOnVisit& func); + + /** + * @brief Sets callback to be invoked on AttributeRangeFilter. + * + * @param[in] func - callback with arguments: + * - std::string AttributeName + * - picojson::value initialValue + * - picojson::value endValue + */ + void SetOnAttributeRangeFilter(const AttributeRangeFilterOnVisit& func); + + /** + * @brief Sets callback to be invoked on begin of CompositeFilter. + * + * @param[in] func - callback with arguments: + * - CompositeFilterType type + */ + void SetOnCompositeFilterBegin(const CompositeFilterOnBegin& func); + + /** + * @brief Sets callback to be invoked on end of CompositeFilter. + * + * @param[in] func - callback with no arguments + */ + void SetOnCompositeFilterEnd(const CompositeFilterOnEnd& func); + + /** + * @brief Parses a json object as Tizen filter. + * @param filter Object to be visited + */ + PlatformResult Visit(const picojson::object& filter); + + private: + PlatformResult VisitAttributeFilter(const picojson::object& filter); + PlatformResult VisitAttributeRangeFilter(const picojson::object& filter); + PlatformResult VisitCompositeFilter(const picojson::object& filter); + + AttributeFilterOnVisit m_attributeFilterOnVisit; + AttributeRangeFilterOnVisit m_attributeRangeFilterOnVisit; + CompositeFilterOnBegin m_compositeFilterOnBegin; + CompositeFilterOnEnd m_compositeFilterOnEnd; }; } // namespace common diff --git a/src/common/logger.cc b/src/common/logger.cc index bd3db74..48d44f9 100644 --- a/src/common/logger.cc +++ b/src/common/logger.cc @@ -4,14 +4,11 @@ #include "common/logger.h" -LogMessage::LogMessage(const char* file, const char* function, int line, - log_priority priority) - : file_(file), - function_(function), - line_(line), - priority_(priority) {} +LogMessage::LogMessage(const char* file, const char* function, int line, log_priority priority) + : file_(file), function_(function), line_(line), priority_(priority) { +} LogMessage::~LogMessage() { - __dlog_print(LOG_ID_MAIN, priority_, LOGGER_TAG, "%s: %s(%d) > %s", - file_, function_, line_, stream_.str().c_str()); + __dlog_print(LOG_ID_MAIN, priority_, LOGGER_TAG, "%s: %s(%d) > %s", file_, function_, line_, + stream_.str().c_str()); } diff --git a/src/common/logger.h b/src/common/logger.h index 8be5a41..1054c4d 100644 --- a/src/common/logger.h +++ b/src/common/logger.h @@ -14,43 +14,48 @@ // by default in dlog.h file. #undef LOG_ #ifdef TIZEN_DEBUG_ENABLE -#define LOG_(id, prio, tag, fmt, arg...) \ - ({ do { \ - __dlog_print(id, prio, tag, "%s: %s(%d) > " fmt, __MODULE__, __func__, __LINE__, ##arg); \ - } while (0); }) -#else // TIZEN_DEBUG_ENABLE -#define LOG_(id, prio, tag, fmt, arg...) \ - ({ do { \ - if ((int)prio != DLOG_DEBUG) { \ +#define LOG_(id, prio, tag, fmt, arg...) \ + ({ \ + do { \ __dlog_print(id, prio, tag, "%s: %s(%d) > " fmt, __MODULE__, __func__, __LINE__, ##arg); \ - } \ - } while (0); }) + } while (0); \ + }) +#else // TIZEN_DEBUG_ENABLE +#define LOG_(id, prio, tag, fmt, arg...) \ + ({ \ + do { \ + if ((int)prio != DLOG_DEBUG) { \ + __dlog_print(id, prio, tag, "%s: %s(%d) > " fmt, __MODULE__, __func__, __LINE__, ##arg); \ + } \ + } while (0); \ + }) #endif // TIZEN_DEBUG_ENABLE #undef SECURE_LOG_ #ifdef TIZEN_DEBUG_ENABLE -#define SECURE_LOG_(id, prio, tag, fmt, arg...) \ - ({ do { \ - __dlog_print(id, prio, tag, "%s: %s(%d) > [SECURE_LOG] " fmt, __MODULE__, __func__, __LINE__, ##arg); \ - } while (0); }) +#define SECURE_LOG_(id, prio, tag, fmt, arg...) \ + ({ \ + do { \ + __dlog_print(id, prio, tag, "%s: %s(%d) > [SECURE_LOG] " fmt, __MODULE__, __func__, \ + __LINE__, ##arg); \ + } while (0); \ + }) #else // TIZEN_DEBUG_ENABLE #define SECURE_LOG_(id, prio, tag, fmt, arg...) NOP(fmt, ##arg) #endif // TIZEN_DEBUG_ENABLE -#include #include #include +#include #include "common/utils.h" #undef LOGGER_TAG #define LOGGER_TAG "WEBAPI_PLUGINS" -#define _LOGGER_LOG(prio, fmt, args...) \ - LOG_(LOG_ID_MAIN, prio, LOGGER_TAG, fmt, ##args) +#define _LOGGER_LOG(prio, fmt, args...) LOG_(LOG_ID_MAIN, prio, LOGGER_TAG, fmt, ##args) -#define _LOGGER_SLOG(prio, fmt, args...) \ - SECURE_LOG_(LOG_ID_MAIN, prio, LOGGER_TAG, fmt, ##args) +#define _LOGGER_SLOG(prio, fmt, args...) SECURE_LOG_(LOG_ID_MAIN, prio, LOGGER_TAG, fmt, ##args) #define LoggerD(fmt, args...) _LOGGER_LOG(DLOG_DEBUG, fmt, ##args) #define LoggerI(fmt, args...) _LOGGER_LOG(DLOG_INFO, fmt, ##args) @@ -66,23 +71,18 @@ // by LOGGER() and LOGGER_IF, etc. Since these are used all over our code, it's // better to have compact code for these operations. #ifdef TIZEN_DEBUG_ENABLE -#define COMPACT_LOG_DEBUG \ - LogMessage(__MODULE__, __func__, __LINE__, DLOG_DEBUG).stream() +#define COMPACT_LOG_DEBUG LogMessage(__MODULE__, __func__, __LINE__, DLOG_DEBUG).stream() #else -#define COMPACT_LOG_DEBUG \ - true ? (void) 0 : LogMessageVoidify() & (std::ostringstream()) +#define COMPACT_LOG_DEBUG true ? (void)0 : LogMessageVoidify() & (std::ostringstream()) #endif -#define COMPACT_LOG_INFO \ - LogMessage(__MODULE__, __func__, __LINE__, DLOG_INFO).stream() -#define COMPACT_LOG_WARN \ - LogMessage(__MODULE__, __func__, __LINE__, DLOG_WARN).stream() -#define COMPACT_LOG_ERROR \ - LogMessage(__MODULE__, __func__, __LINE__, DLOG_ERROR).stream() +#define COMPACT_LOG_INFO LogMessage(__MODULE__, __func__, __LINE__, DLOG_INFO).stream() +#define COMPACT_LOG_WARN LogMessage(__MODULE__, __func__, __LINE__, DLOG_WARN).stream() +#define COMPACT_LOG_ERROR LogMessage(__MODULE__, __func__, __LINE__, DLOG_ERROR).stream() -#define LOGGER(priority) COMPACT_LOG_ ## priority +#define LOGGER(priority) COMPACT_LOG_##priority #define LOGGER_IF(priority, condition) \ - !(condition) ? (void) 0 : LogMessageVoidify() & (LOGGER(priority)) + !(condition) ? (void)0 : LogMessageVoidify() & (LOGGER(priority)) // This class more or less represents a particular log message. // You create an instance of LogMessage and then stream stuff to it. @@ -93,11 +93,12 @@ // though. You should use the LOGGER() macro (and variants thereof) above. class LogMessage { public: - LogMessage(const char* file, const char* function, int line, - log_priority priority); + LogMessage(const char* file, const char* function, int line, log_priority priority); ~LogMessage(); - std::ostream& stream() { return stream_; } + std::ostream& stream() { + return stream_; + } private: const char* file_; @@ -114,59 +115,51 @@ class LogMessage { // logging macros. This avoids compiler warnings like "value computed // is not used" and "statement has no effect". class LogMessageVoidify { -public: - LogMessageVoidify() {} + public: + LogMessageVoidify() { + } // This has to be an operator with a precedence lower than << but // higher than ?: - void operator&(std::ostream &) {} + void operator&(std::ostream&) { + } }; // internal macros #define LogAndReportError_2(error, object) \ - do { \ - LoggerE("Reporting error."); \ - ReportError(error, object); \ - } while(false) + do { \ + LoggerE("Reporting error."); \ + ReportError(error, object); \ + } while (false) #define LogAndReportError_3(error, object, log) \ - do { \ - LoggerE log; \ - ReportError(error, object); \ - } while(false) + do { \ + LoggerE log; \ + ReportError(error, object); \ + } while (false) #define LogAndReportError_X(_0, _1, _2, _3, FUNC, ...) FUNC // usage: -// LogAndCreateResult(const common::PlatformResult& result, picojson::object* obj, [(const char* log, ...)]) +// LogAndCreateResult(const common::PlatformResult& result, picojson::object* obj, [(const char* +// log, ...)]) // LogAndReportError(result, &out); // LogAndReportError(result, &out, ("Failed to open archive.")); // LogAndReportError(result, &out, ("Failed to open archive: %d.", 11)); -#define LogAndReportError(...) \ - LogAndReportError_X(, ##__VA_ARGS__, \ - LogAndReportError_3(__VA_ARGS__), \ - LogAndReportError_2(__VA_ARGS__) \ - ) +#define LogAndReportError(...) \ + LogAndReportError_X(, ##__VA_ARGS__, LogAndReportError_3(__VA_ARGS__), \ + LogAndReportError_2(__VA_ARGS__)) // internal macros #define LogAndCreateResult_1(error_code) \ - ( \ - LoggerE("Creating PlatformResult with error"), \ - common::PlatformResult(error_code) \ - ) + (LoggerE("Creating PlatformResult with error"), common::PlatformResult(error_code)) #define LogAndCreateResult_2(error_code, msg) \ - ( \ - LoggerE("Creating PlatformResult with error"), \ - common::PlatformResult(error_code, msg) \ - ) + (LoggerE("Creating PlatformResult with error"), common::PlatformResult(error_code, msg)) #define LogAndCreateResult_3(error_code, msg, log) \ - ( \ - LoggerE log, \ - common::PlatformResult(error_code, msg) \ - ) + (LoggerE log, common::PlatformResult(error_code, msg)) #define LogAndCreateResult_X(_0, _1, _2, _3, FUNC, ...) FUNC @@ -180,69 +173,57 @@ public: // PlatformResult pr4 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory."); // return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory."); // -// auto pr5 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error")); -// PlatformResult pr6 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error")); -// return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error")); +// auto pr5 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: +// reporting IO error")); +// PlatformResult pr6 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a +// directory: reporting IO error")); +// return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO +// error")); // -// auto pr7 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error: %d", 33)); -// PlatformResult pr8 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error: %d", 33)); -// return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO error: %d", 33)); +// auto pr7 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: +// reporting IO error: %d", 33)); +// PlatformResult pr8 = LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a +// directory: reporting IO error: %d", 33)); +// return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory.", ("Not a directory: reporting IO +// error: %d", 33)); -#define LogAndCreateResult(...) \ - LogAndCreateResult_X(, ##__VA_ARGS__, \ - LogAndCreateResult_3(__VA_ARGS__), \ - LogAndCreateResult_2(__VA_ARGS__), \ - LogAndCreateResult_1(__VA_ARGS__) \ - ) +#define LogAndCreateResult(...) \ + LogAndCreateResult_X(, ##__VA_ARGS__, LogAndCreateResult_3(__VA_ARGS__), \ + LogAndCreateResult_2(__VA_ARGS__), LogAndCreateResult_1(__VA_ARGS__)) // internal macros -#define LogAndCreateTizenError_1(error_name) \ - ( \ - LoggerE("Creating TizenError"), \ - common::error_name() \ - ) +#define LogAndCreateTizenError_1(error_name) (LoggerE("Creating TizenError"), common::error_name()) #define LogAndCreateTizenError_2(error_name, msg) \ - ( \ - LoggerE("Creating TizenError"), \ - common::error_name(msg) \ - ) + (LoggerE("Creating TizenError"), common::error_name(msg)) -#define LogAndCreateTizenError_3(error_name, msg, log) \ - ( \ - LoggerE log, \ - common::error_name(msg) \ - ) +#define LogAndCreateTizenError_3(error_name, msg, log) (LoggerE log, common::error_name(msg)) #define LogAndCreateTizenError_X(_0, _1, _2, _3, FUNC, ...) FUNC -#define LogAndCreateTizenError(...) \ - LogAndCreateTizenError_X(, ##__VA_ARGS__, \ - LogAndCreateTizenError_3(__VA_ARGS__), \ - LogAndCreateTizenError_2(__VA_ARGS__), \ - LogAndCreateTizenError_1(__VA_ARGS__) \ - ) +#define LogAndCreateTizenError(...) \ + LogAndCreateTizenError_X(, ##__VA_ARGS__, LogAndCreateTizenError_3(__VA_ARGS__), \ + LogAndCreateTizenError_2(__VA_ARGS__), \ + LogAndCreateTizenError_1(__VA_ARGS__)) // internal macros #define LogAndReturnTizenError_1(error) \ - do { \ - LoggerE("Reporting error."); \ - return error; \ - } while(false) + do { \ + LoggerE("Reporting error."); \ + return error; \ + } while (false) #define LogAndReturnTizenError_2(error, log) \ - do { \ - LoggerE log; \ - return error; \ - } while(false) + do { \ + LoggerE log; \ + return error; \ + } while (false) #define LogAndReturnTizenError_X(_0, _1, _2, FUNC, ...) FUNC -#define LogAndReturnTizenError(...) \ - LogAndReturnTizenError_X(, ##__VA_ARGS__, \ - LogAndReturnTizenError_2(__VA_ARGS__), \ - LogAndReturnTizenError_1(__VA_ARGS__) \ - ) +#define LogAndReturnTizenError(...) \ + LogAndReturnTizenError_X(, ##__VA_ARGS__, LogAndReturnTizenError_2(__VA_ARGS__), \ + LogAndReturnTizenError_1(__VA_ARGS__)) namespace common { @@ -267,6 +248,9 @@ class ScopeLogger { } // common -#define ScopeLogger(EX) const common::ScopeLogger __sl__{__MODULE__, __func__, __LINE__, EX} +#define ScopeLogger(EX) \ + const common::ScopeLogger __sl__ { \ + __MODULE__, __func__, __LINE__, EX \ + } -#endif // COMMON_LOGGER_H_ +#endif // COMMON_LOGGER_H_ diff --git a/src/common/optional.h b/src/common/optional.h old mode 100755 new mode 100644 index 232a745..b6b2800 --- a/src/common/optional.h +++ b/src/common/optional.h @@ -18,52 +18,82 @@ #define COMMON_OPTIONAL_H_ #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 - #define ALIGNAS_TYPE(x) alignas(x) - #define ALIGNAS(x) alignas(x) +#define ALIGNAS_TYPE(x) alignas(x) +#define ALIGNAS(x) alignas(x) #else - #define ALIGNAS_TYPE(x) __attribute__((__aligned__(__alignof(x)))) - #define ALIGNAS(x) __attribute__((aligned(x))) +#define ALIGNAS_TYPE(x) __attribute__((__aligned__(__alignof(x)))) +#define ALIGNAS(x) __attribute__((aligned(x))) #endif - #include -#include #include +#include #include "common/assert.h" namespace common { -template +template class optional { static_assert(!std::is_reference::value, "reference is not supported"); public: - optional() : exist_(false) {} - optional(std::nullptr_t) : exist_(false) {} - optional(const optional& rhs): exist_(rhs.exist_) { create(rhs); } - optional(optional&& rhs): exist_(rhs.exist_) { create(std::move(rhs)); } - optional(const T& v): exist_(true) { create(v); } - ~optional() { if (exist_) destroy(); } - - bool operator !() const { return !exist_; } - explicit operator bool() const { return exist_; } - - optional& operator = (const optional& rhs) { return assign(rhs); } - optional& operator = (optional&& rhs) { return assign(std::move(rhs)); } - optional& operator = (std::nullptr_t) {if (exist_) cleanup(); return *this; } - optional& operator = (const T& v) { return assign(v); } - - const T& operator * () const { return *get(); } - T& operator * () { return *get(); } - const T* operator -> () const { return get(); } - T* operator -> () { return get(); } + optional() : exist_(false) { + } + optional(std::nullptr_t) : exist_(false) { + } + optional(const optional& rhs) : exist_(rhs.exist_) { + create(rhs); + } + optional(optional&& rhs) : exist_(rhs.exist_) { + create(std::move(rhs)); + } + optional(const T& v) : exist_(true) { + create(v); + } + ~optional() { + if (exist_) destroy(); + } + + bool operator!() const { + return !exist_; + } + explicit operator bool() const { + return exist_; + } + + optional& operator=(const optional& rhs) { + return assign(rhs); + } + optional& operator=(optional&& rhs) { + return assign(std::move(rhs)); + } + optional& operator=(std::nullptr_t) { + if (exist_) cleanup(); + return *this; + } + optional& operator=(const T& v) { + return assign(v); + } + + const T& operator*() const { + return *get(); + } + T& operator*() { + return *get(); + } + const T* operator->() const { + return get(); + } + T* operator->() { + return get(); + } private: void create(const T& v) { - new(value_) T(v); + new (value_) T(v); } void create(T&& v) { - new(value_) T(std::move(v)); + new (value_) T(std::move(v)); } void create(const optional& rhs) { if (exist_) create(*rhs.get()); diff --git a/src/common/picojson.h b/src/common/picojson.h index 2f9fb6d..728b63a 100644 --- a/src/common/picojson.h +++ b/src/common/picojson.h @@ -1,16 +1,16 @@ /* * Copyright 2009-2010 Cybozu Labs, Inc. * Copyright 2011 Kazuho Oku - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY CYBOZU LABS, INC. ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -21,7 +21,7 @@ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Cybozu Labs, Inc. @@ -35,195 +35,209 @@ #include #include #include -#include -#include #include +#include #include #include +#include #include #include #include "common/assert.h" #ifdef _MSC_VER - #define SNPRINTF _snprintf_s - #pragma warning(push) - #pragma warning(disable : 4244) // conversion from int to char +#define SNPRINTF _snprintf_s +#pragma warning(push) +#pragma warning(disable : 4244) // conversion from int to char #else - #define SNPRINTF snprintf +#define SNPRINTF snprintf #endif namespace picojson { - - enum { - null_type, - boolean_type, - number_type, - string_type, - array_type, - object_type - }; - - struct null {}; - - class value { - public: - typedef std::vector array; - typedef std::map object; - union _storage { - bool boolean_; - double number_; - std::string* string_; - array* array_; - object* object_; - }; - protected: - int type_; - _storage u_; - public: - value(); - value(int type, bool); - explicit value(bool b); - explicit value(double n); - explicit value(const std::string& s); - explicit value(const array& a); - explicit value(const object& o); - explicit value(const char* s); - value(const char* s, size_t len); - ~value(); - value(const value& x); - value& operator=(const value& x); - void swap(value& x); - template bool is() const; - template const T& get() const; - template T& get(); - bool evaluate_as_boolean() const; - const value& get(size_t idx) const; - const value& get(const std::string& key) const; - bool contains(size_t idx) const; - bool contains(const std::string& key) const; - std::string to_str() const; - template void serialize(Iter os) const; - std::string serialize() const; - private: - template value(const T*); // intentionally defined to block implicit conversion of pointer to bool + +enum { null_type, boolean_type, number_type, string_type, array_type, object_type }; + +struct null {}; + +class value { + public: + typedef std::vector array; + typedef std::map object; + union _storage { + bool boolean_; + double number_; + std::string* string_; + array* array_; + object* object_; }; - - typedef value::array array; - typedef value::object object; - - inline value::value() : type_(null_type) {} - - inline value::value(int type, bool) : type_(type) { - switch (type) { -#define INIT(p, v) case p##type: u_.p = v; break - INIT(boolean_, false); - INIT(number_, 0.0); - INIT(string_, new std::string()); - INIT(array_, new array()); - INIT(object_, new object()); + + protected: + int type_; + _storage u_; + + public: + value(); + value(int type, bool); + explicit value(bool b); + explicit value(double n); + explicit value(const std::string& s); + explicit value(const array& a); + explicit value(const object& o); + explicit value(const char* s); + value(const char* s, size_t len); + ~value(); + value(const value& x); + value& operator=(const value& x); + void swap(value& x); + template + bool is() const; + template + const T& get() const; + template + T& get(); + bool evaluate_as_boolean() const; + const value& get(size_t idx) const; + const value& get(const std::string& key) const; + bool contains(size_t idx) const; + bool contains(const std::string& key) const; + std::string to_str() const; + template + void serialize(Iter os) const; + std::string serialize() const; + + private: + template + value(const T*); // intentionally defined to block implicit conversion of pointer to bool +}; + +typedef value::array array; +typedef value::object object; + +inline value::value() : type_(null_type) { +} + +inline value::value(int type, bool) : type_(type) { + switch (type) { +#define INIT(p, v) \ + case p##type: \ + u_.p = v; \ + break + INIT(boolean_, false); + INIT(number_, 0.0); + INIT(string_, new std::string()); + INIT(array_, new array()); + INIT(object_, new object()); #undef INIT - default: break; - } + default: + break; } - - inline value::value(bool b) : type_(boolean_type) { - u_.boolean_ = b; - } - - inline value::value(double n) : type_(number_type) { - u_.number_ = n; - } - - inline value::value(const std::string& s) : type_(string_type) { - u_.string_ = new std::string(s); - } - - inline value::value(const array& a) : type_(array_type) { - u_.array_ = new array(a); - } - - inline value::value(const object& o) : type_(object_type) { - u_.object_ = new object(o); - } - - inline value::value(const char* s) : type_(string_type) { - u_.string_ = new std::string(s); - } - - inline value::value(const char* s, size_t len) : type_(string_type) { - u_.string_ = new std::string(s, len); - } - - inline value::~value() { - switch (type_) { -#define DEINIT(p) case p##type: delete u_.p; break - DEINIT(string_); - DEINIT(array_); - DEINIT(object_); +} + +inline value::value(bool b) : type_(boolean_type) { + u_.boolean_ = b; +} + +inline value::value(double n) : type_(number_type) { + u_.number_ = n; +} + +inline value::value(const std::string& s) : type_(string_type) { + u_.string_ = new std::string(s); +} + +inline value::value(const array& a) : type_(array_type) { + u_.array_ = new array(a); +} + +inline value::value(const object& o) : type_(object_type) { + u_.object_ = new object(o); +} + +inline value::value(const char* s) : type_(string_type) { + u_.string_ = new std::string(s); +} + +inline value::value(const char* s, size_t len) : type_(string_type) { + u_.string_ = new std::string(s, len); +} + +inline value::~value() { + switch (type_) { +#define DEINIT(p) \ + case p##type: \ + delete u_.p; \ + break + DEINIT(string_); + DEINIT(array_); + DEINIT(object_); #undef DEINIT - default: break; - } + default: + break; } - - inline value::value(const value& x) : type_(x.type_) { - switch (type_) { -#define INIT(p, v) case p##type: u_.p = v; break - INIT(string_, new std::string(*x.u_.string_)); - INIT(array_, new array(*x.u_.array_)); - INIT(object_, new object(*x.u_.object_)); +} + +inline value::value(const value& x) : type_(x.type_) { + switch (type_) { +#define INIT(p, v) \ + case p##type: \ + u_.p = v; \ + break + INIT(string_, new std::string(*x.u_.string_)); + INIT(array_, new array(*x.u_.array_)); + INIT(object_, new object(*x.u_.object_)); #undef INIT default: u_ = x.u_; break; - } } - - inline value& value::operator=(const value& x) { - if (this != &x) { - this->~value(); - new (this) value(x); - } - return *this; - } - - inline void value::swap(value& x) { - std::swap(type_, x.type_); - std::swap(u_, x.u_); - } - -#define IS(ctype, jtype) \ - template <> inline bool value::is() const { \ - return type_ == jtype##_type; \ - } - IS(null, null) - IS(bool, boolean) - IS(int, number) - IS(double, number) - IS(std::string, string) - IS(array, array) - IS(object, object) +} + +inline value& value::operator=(const value& x) { + if (this != &x) { + this->~value(); + new (this) value(x); + } + return *this; +} + +inline void value::swap(value& x) { + std::swap(type_, x.type_); + std::swap(u_, x.u_); +} + +#define IS(ctype, jtype) \ + template <> \ + inline bool value::is() const { \ + return type_ == jtype##_type; \ + } +IS(null, null) +IS(bool, boolean) +IS(int, number) +IS(double, number) +IS(std::string, string) +IS(array, array) +IS(object, object) #undef IS - -#define GET(ctype, var) \ - template <> inline const ctype& value::get() const { \ - Assert("type mismatch! call vis() before get()" \ - && is()); \ - return var; \ - } \ - template <> inline ctype& value::get() { \ - Assert("type mismatch! call is() before get()" \ - && is()); \ - return var; \ - } - GET(bool, u_.boolean_) - GET(double, u_.number_) - GET(std::string, *u_.string_) - GET(array, *u_.array_) - GET(object, *u_.object_) + +#define GET(ctype, var) \ + template <> \ + inline const ctype& value::get() const { \ + Assert("type mismatch! call vis() before get()" && is()); \ + return var; \ + } \ + template <> \ + inline ctype& value::get() { \ + Assert("type mismatch! call is() before get()" && is()); \ + return var; \ + } +GET(bool, u_.boolean_) +GET(double, u_.number_) +GET(std::string, *u_.string_) +GET(array, *u_.array_) +GET(object, *u_.object_) #undef GET - - inline bool value::evaluate_as_boolean() const { - switch (type_) { + +inline bool value::evaluate_as_boolean() const { + switch (type_) { case null_type: return false; case boolean_type: @@ -231,118 +245,126 @@ namespace picojson { case number_type: return u_.number_ != 0; case string_type: - return ! u_.string_->empty(); + return !u_.string_->empty(); default: return true; - } - } - - inline const value& value::get(size_t idx) const { - static value s_null; - Assert(is()); - return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; } +} - inline const value& value::get(const std::string& key) const { - static value s_null; - Assert(is()); - object::const_iterator i = u_.object_->find(key); - return i != u_.object_->end() ? i->second : s_null; - } +inline const value& value::get(size_t idx) const { + static value s_null; + Assert(is()); + return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; +} - inline bool value::contains(size_t idx) const { - Assert(is()); - return idx < u_.array_->size(); - } +inline const value& value::get(const std::string& key) const { + static value s_null; + Assert(is()); + object::const_iterator i = u_.object_->find(key); + return i != u_.object_->end() ? i->second : s_null; +} - inline bool value::contains(const std::string& key) const { - Assert(is()); - object::const_iterator i = u_.object_->find(key); - return i != u_.object_->end(); - } - - inline std::string value::to_str() const { - switch (type_) { - case null_type: return "null"; - case boolean_type: return u_.boolean_ ? "true" : "false"; - case number_type: { +inline bool value::contains(size_t idx) const { + Assert(is()); + return idx < u_.array_->size(); +} + +inline bool value::contains(const std::string& key) const { + Assert(is()); + object::const_iterator i = u_.object_->find(key); + return i != u_.object_->end(); +} + +inline std::string value::to_str() const { + switch (type_) { + case null_type: + return "null"; + case boolean_type: + return u_.boolean_ ? "true" : "false"; + case number_type: { std::stringstream num_str; - num_str.imbue( std::locale::classic() ); + num_str.imbue(std::locale::classic()); num_str << std::setprecision(16) << u_.number_; return num_str.str(); } - case string_type: return *u_.string_; - case array_type: return "array"; - case object_type: return "object"; - default: Assert(0); + case string_type: + return *u_.string_; + case array_type: + return "array"; + case object_type: + return "object"; + default: + Assert(0); #ifdef _MSC_VER __assume(0); #endif - } - return std::string(); - } - - template void copy(const std::string& s, Iter oi) { - std::copy(s.begin(), s.end(), oi); - } - - template void serialize_str(const std::string& s, Iter oi) { - *oi++ = '"'; - for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) { - switch (*i) { -#define MAP(val, sym) case val: copy(sym, oi); break - MAP('"', "\\\""); - MAP('\\', "\\\\"); - MAP('/', "\\/"); - MAP('\b', "\\b"); - MAP('\f', "\\f"); - MAP('\n', "\\n"); - MAP('\r', "\\r"); - MAP('\t', "\\t"); + } + return std::string(); +} + +template +void copy(const std::string& s, Iter oi) { + std::copy(s.begin(), s.end(), oi); +} + +template +void serialize_str(const std::string& s, Iter oi) { + *oi++ = '"'; + for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) { + switch (*i) { +#define MAP(val, sym) \ + case val: \ + copy(sym, oi); \ + break + MAP('"', "\\\""); + MAP('\\', "\\\\"); + MAP('/', "\\/"); + MAP('\b', "\\b"); + MAP('\f', "\\f"); + MAP('\n', "\\n"); + MAP('\r', "\\r"); + MAP('\t', "\\t"); #undef MAP default: - if ((unsigned char)*i < 0x20 || *i == 0x7f) { - char buf[7]; - SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff); - copy(buf, buf + 6, oi); - } else { - *oi++ = *i; - } - break; - } + if ((unsigned char)*i < 0x20 || *i == 0x7f) { + char buf[7]; + SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff); + copy(buf, buf + 6, oi); + } else { + *oi++ = *i; + } + break; } - *oi++ = '"'; } - - template void value::serialize(Iter oi) const { - switch (type_) { + *oi++ = '"'; +} + +template +void value::serialize(Iter oi) const { + switch (type_) { case string_type: serialize_str(*u_.string_, oi); break; case array_type: { *oi++ = '['; - for (array::const_iterator i = u_.array_->begin(); - i != u_.array_->end(); - ++i) { - if (i != u_.array_->begin()) { - *oi++ = ','; - } - i->serialize(oi); + for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) { + if (i != u_.array_->begin()) { + *oi++ = ','; + } + i->serialize(oi); } *oi++ = ']'; break; } case object_type: { *oi++ = '{'; - for (object::const_iterator i = u_.object_->begin(); - i != u_.object_->end(); - ++i) { - if (i != u_.object_->begin()) { - *oi++ = ','; - } - serialize_str(i->first, oi); - *oi++ = ':'; - i->second.serialize(oi); + for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) { + if (i != u_.object_->begin()) { + *oi++ = ','; + } + serialize_str(i->first, oi); + *oi++ = ':'; + i->second.serialize(oi); } *oi++ = '}'; break; @@ -350,247 +372,261 @@ namespace picojson { default: copy(to_str(), oi); break; - } } - - inline std::string value::serialize() const { - std::string s; - serialize(std::back_inserter(s)); - return s; - } - - template class input { - protected: - Iter cur_, end_; - int last_ch_; - bool ungot_; - int line_; - public: - input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {} - int getc() { - if (ungot_) { - ungot_ = false; - return last_ch_; - } - if (cur_ == end_) { - last_ch_ = -1; - return -1; - } - if (last_ch_ == '\n') { - line_++; - } - last_ch_ = *cur_++ & 0xff; +} + +inline std::string value::serialize() const { + std::string s; + serialize(std::back_inserter(s)); + return s; +} + +template +class input { + protected: + Iter cur_, end_; + int last_ch_; + bool ungot_; + int line_; + + public: + input(const Iter& first, const Iter& last) + : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) { + } + int getc() { + if (ungot_) { + ungot_ = false; return last_ch_; } - void ungetc() { - if (last_ch_ != -1) { - Assert(! ungot_); - ungot_ = true; - } + if (cur_ == end_) { + last_ch_ = -1; + return -1; } - Iter cur() const { return cur_; } - int line() const { return line_; } - void skip_ws() { - while (1) { - int ch = getc(); - if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { - ungetc(); - break; - } - } + if (last_ch_ == '\n') { + line_++; } - bool expect(int expect) { - skip_ws(); - if (getc() != expect) { - ungetc(); - return false; - } - return true; + last_ch_ = *cur_++ & 0xff; + return last_ch_; + } + void ungetc() { + if (last_ch_ != -1) { + Assert(!ungot_); + ungot_ = true; } - bool match(const std::string& pattern) { - for (std::string::const_iterator pi(pattern.begin()); - pi != pattern.end(); - ++pi) { - if (getc() != *pi) { - ungetc(); - return false; - } + } + Iter cur() const { + return cur_; + } + int line() const { + return line_; + } + void skip_ws() { + while (1) { + int ch = getc(); + if (!(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { + ungetc(); + break; } - return true; } - }; - - template inline int _parse_quadhex(input &in) { - int uni_ch = 0, hex; - for (int i = 0; i < 4; i++) { - if ((hex = in.getc()) == -1) { - return -1; - } - if ('0' <= hex && hex <= '9') { - hex -= '0'; - } else if ('A' <= hex && hex <= 'F') { - hex -= 'A' - 0xa; - } else if ('a' <= hex && hex <= 'f') { - hex -= 'a' - 0xa; - } else { - in.ungetc(); - return -1; + } + bool expect(int expect) { + skip_ws(); + if (getc() != expect) { + ungetc(); + return false; + } + return true; + } + bool match(const std::string& pattern) { + for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) { + if (getc() != *pi) { + ungetc(); + return false; } - uni_ch = uni_ch * 16 + hex; } - return uni_ch; + return true; + } +}; + +template +inline int _parse_quadhex(input& in) { + int uni_ch = 0, hex; + for (int i = 0; i < 4; i++) { + if ((hex = in.getc()) == -1) { + return -1; + } + if ('0' <= hex && hex <= '9') { + hex -= '0'; + } else if ('A' <= hex && hex <= 'F') { + hex -= 'A' - 0xa; + } else if ('a' <= hex && hex <= 'f') { + hex -= 'a' - 0xa; + } else { + in.ungetc(); + return -1; + } + uni_ch = uni_ch * 16 + hex; + } + return uni_ch; +} + +template +inline bool _parse_codepoint(String& out, input& in) { + int uni_ch; + if ((uni_ch = _parse_quadhex(in)) == -1) { + return false; } - - template inline bool _parse_codepoint(String& out, input& in) { - int uni_ch; - if ((uni_ch = _parse_quadhex(in)) == -1) { + if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { + if (0xdc00 <= uni_ch) { + // a second 16-bit of a surrogate pair appeared return false; } - if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { - if (0xdc00 <= uni_ch) { - // a second 16-bit of a surrogate pair appeared - return false; - } - // first 16-bit of surrogate pair, get the next one - if (in.getc() != '\\' || in.getc() != 'u') { - in.ungetc(); - return false; - } - int second = _parse_quadhex(in); - if (! (0xdc00 <= second && second <= 0xdfff)) { - return false; - } - uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); - uni_ch += 0x10000; + // first 16-bit of surrogate pair, get the next one + if (in.getc() != '\\' || in.getc() != 'u') { + in.ungetc(); + return false; + } + int second = _parse_quadhex(in); + if (!(0xdc00 <= second && second <= 0xdfff)) { + return false; } - if (uni_ch < 0x80) { - out.push_back(uni_ch); + uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); + uni_ch += 0x10000; + } + if (uni_ch < 0x80) { + out.push_back(uni_ch); + } else { + if (uni_ch < 0x800) { + out.push_back(0xc0 | (uni_ch >> 6)); } else { - if (uni_ch < 0x800) { - out.push_back(0xc0 | (uni_ch >> 6)); + if (uni_ch < 0x10000) { + out.push_back(0xe0 | (uni_ch >> 12)); } else { - if (uni_ch < 0x10000) { - out.push_back(0xe0 | (uni_ch >> 12)); - } else { - out.push_back(0xf0 | (uni_ch >> 18)); - out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); - } - out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); + out.push_back(0xf0 | (uni_ch >> 18)); + out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); } - out.push_back(0x80 | (uni_ch & 0x3f)); + out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); } - return true; + out.push_back(0x80 | (uni_ch & 0x3f)); } - - template inline bool _parse_string(String& out, input& in) { - while (1) { - int ch = in.getc(); - if (ch < ' ') { - in.ungetc(); - return false; - } else if (ch == '"') { - return true; - } else if (ch == '\\') { - if ((ch = in.getc()) == -1) { - return false; - } - switch (ch) { -#define MAP(sym, val) case sym: out.push_back(val); break - MAP('"', '\"'); - MAP('\\', '\\'); - MAP('/', '/'); - MAP('b', '\b'); - MAP('f', '\f'); - MAP('n', '\n'); - MAP('r', '\r'); - MAP('t', '\t'); + return true; +} + +template +inline bool _parse_string(String& out, input& in) { + while (1) { + int ch = in.getc(); + if (ch < ' ') { + in.ungetc(); + return false; + } else if (ch == '"') { + return true; + } else if (ch == '\\') { + if ((ch = in.getc()) == -1) { + return false; + } + switch (ch) { +#define MAP(sym, val) \ + case sym: \ + out.push_back(val); \ + break + MAP('"', '\"'); + MAP('\\', '\\'); + MAP('/', '/'); + MAP('b', '\b'); + MAP('f', '\f'); + MAP('n', '\n'); + MAP('r', '\r'); + MAP('t', '\t'); #undef MAP - case 'u': - if (! _parse_codepoint(out, in)) { - return false; - } - break; - default: - return false; - } - } else { - out.push_back(ch); + case 'u': + if (!_parse_codepoint(out, in)) { + return false; + } + break; + default: + return false; } + } else { + out.push_back(ch); } + } + return false; +} + +template +inline bool _parse_array(Context& ctx, input& in) { + if (!ctx.parse_array_start()) { return false; } - - template inline bool _parse_array(Context& ctx, input& in) { - if (! ctx.parse_array_start()) { + if (in.expect(']')) { + return true; + } + size_t idx = 0; + do { + if (!ctx.parse_array_item(in, idx)) { return false; } - if (in.expect(']')) { - return true; - } - size_t idx = 0; - do { - if (! ctx.parse_array_item(in, idx)) { - return false; - } - idx++; - } while (in.expect(',')); - return in.expect(']'); + idx++; + } while (in.expect(',')); + return in.expect(']'); +} + +template +inline bool _parse_object(Context& ctx, input& in) { + if (!ctx.parse_object_start()) { + return false; + } + if (in.expect('}')) { + return true; } - - template inline bool _parse_object(Context& ctx, input& in) { - if (! ctx.parse_object_start()) { + do { + std::string key; + if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) { return false; } - if (in.expect('}')) { - return true; + if (!ctx.parse_object_item(in, key)) { + return false; } - do { - std::string key; - if (! in.expect('"') - || ! _parse_string(key, in) - || ! in.expect(':')) { - return false; - } - if (! ctx.parse_object_item(in, key)) { - return false; - } - } while (in.expect(',')); - return in.expect('}'); - } - - template inline bool _parse_number(double& out, input& in) { - std::stringstream num_str; - num_str.imbue( std::locale::classic() ); + } while (in.expect(',')); + return in.expect('}'); +} - while (true) { - int ch = in.getc(); - if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == '.' - || ch == 'e' || ch == 'E') { - num_str.put(ch); - } else { - in.ungetc(); - break; - } +template +inline bool _parse_number(double& out, input& in) { + std::stringstream num_str; + num_str.imbue(std::locale::classic()); + + while (true) { + int ch = in.getc(); + if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == '.' || ch == 'e' || ch == 'E') { + num_str.put(ch); + } else { + in.ungetc(); + break; } + } - num_str >> out; + num_str >> out; - return num_str && num_str.eof(); - } - - template inline bool _parse(Context& ctx, input& in) { - in.skip_ws(); - int ch = in.getc(); - switch (ch) { -#define IS(ch, text, op) case ch: \ - if (in.match(text) && op) { \ - return true; \ - } else { \ - return false; \ - } - IS('n', "ull", ctx.set_null()); - IS('f', "alse", ctx.set_bool(false)); - IS('t', "rue", ctx.set_bool(true)); + return num_str && num_str.eof(); +} + +template +inline bool _parse(Context& ctx, input& in) { + in.skip_ws(); + int ch = in.getc(); + switch (ch) { +#define IS(ch, text, op) \ + case ch: \ + if (in.match(text) && op) { \ + return true; \ + } else { \ + return false; \ + } + IS('n', "ull", ctx.set_null()); + IS('f', "alse", ctx.set_bool(false)); + IS('t', "rue", ctx.set_bool(true)); #undef IS case '"': return ctx.parse_string(in); @@ -600,235 +636,270 @@ namespace picojson { return _parse_object(ctx, in); default: if (('0' <= ch && ch <= '9') || ch == '-') { - in.ungetc(); - double f; - if (_parse_number(f, in)) { - ctx.set_number(f); - return true; - } else { - return false; - } + in.ungetc(); + double f; + if (_parse_number(f, in)) { + ctx.set_number(f); + return true; + } else { + return false; + } } break; - } - in.ungetc(); + } + in.ungetc(); + return false; +} + +class deny_parse_context { + public: + bool set_null() { return false; } - - class deny_parse_context { - public: - bool set_null() { return false; } - bool set_bool(bool) { return false; } - bool set_number(double) { return false; } - template bool parse_string(input&) { return false; } - bool parse_array_start() { return false; } - template bool parse_array_item(input&, size_t) { - return false; - } - bool parse_object_start() { return false; } - template bool parse_object_item(input&, const std::string&) { - return false; - } - }; - - class default_parse_context { - protected: - value* out_; - public: - default_parse_context(value* out) : out_(out) {} - bool set_null() { - *out_ = value(); - return true; - } - bool set_bool(bool b) { - *out_ = value(b); - return true; - } - bool set_number(double f) { - *out_ = value(f); - return true; - } - template bool parse_string(input& in) { - *out_ = value(string_type, false); - return _parse_string(out_->get(), in); - } - bool parse_array_start() { - *out_ = value(array_type, false); - return true; - } - template bool parse_array_item(input& in, size_t) { - array& a = out_->get(); - a.push_back(value()); - default_parse_context ctx(&a.back()); - return _parse(ctx, in); - } - bool parse_object_start() { - *out_ = value(object_type, false); - return true; - } - template bool parse_object_item(input& in, const std::string& key) { - object& o = out_->get(); - default_parse_context ctx(&o[key]); - return _parse(ctx, in); - } - private: - default_parse_context(const default_parse_context&); - default_parse_context& operator=(const default_parse_context&); - }; + bool set_bool(bool) { + return false; + } + bool set_number(double) { + return false; + } + template + bool parse_string(input&) { + return false; + } + bool parse_array_start() { + return false; + } + template + bool parse_array_item(input&, size_t) { + return false; + } + bool parse_object_start() { + return false; + } + template + bool parse_object_item(input&, const std::string&) { + return false; + } +}; - class null_parse_context { - public: - struct dummy_str { - void push_back(int) {} - }; - public: - null_parse_context() {} - bool set_null() { return true; } - bool set_bool(bool) { return true; } - bool set_number(double) { return true; } - template bool parse_string(input& in) { - dummy_str s; - return _parse_string(s, in); - } - bool parse_array_start() { return true; } - template bool parse_array_item(input& in, size_t) { - return _parse(*this, in); - } - bool parse_object_start() { return true; } - template bool parse_object_item(input& in, const std::string&) { - return _parse(*this, in); +class default_parse_context { + protected: + value* out_; + + public: + default_parse_context(value* out) : out_(out) { + } + bool set_null() { + *out_ = value(); + return true; + } + bool set_bool(bool b) { + *out_ = value(b); + return true; + } + bool set_number(double f) { + *out_ = value(f); + return true; + } + template + bool parse_string(input& in) { + *out_ = value(string_type, false); + return _parse_string(out_->get(), in); + } + bool parse_array_start() { + *out_ = value(array_type, false); + return true; + } + template + bool parse_array_item(input& in, size_t) { + array& a = out_->get(); + a.push_back(value()); + default_parse_context ctx(&a.back()); + return _parse(ctx, in); + } + bool parse_object_start() { + *out_ = value(object_type, false); + return true; + } + template + bool parse_object_item(input& in, const std::string& key) { + object& o = out_->get(); + default_parse_context ctx(&o[key]); + return _parse(ctx, in); + } + + private: + default_parse_context(const default_parse_context&); + default_parse_context& operator=(const default_parse_context&); +}; + +class null_parse_context { + public: + struct dummy_str { + void push_back(int) { } - private: - null_parse_context(const null_parse_context&); - null_parse_context& operator=(const null_parse_context&); }; - - // obsolete, use the version below - template inline std::string parse(value& out, Iter& pos, const Iter& last) { - std::string err; - pos = parse(out, pos, last, &err); - return err; - } - - template inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { - input in(first, last); - if (! _parse(ctx, in) && err != NULL) { - char buf[64]; - SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); - *err = buf; - while (1) { - int ch = in.getc(); - if (ch == -1 || ch == '\n') { - break; - } else if (ch >= ' ') { - err->push_back(ch); - } + + public: + null_parse_context() { + } + bool set_null() { + return true; + } + bool set_bool(bool) { + return true; + } + bool set_number(double) { + return true; + } + template + bool parse_string(input& in) { + dummy_str s; + return _parse_string(s, in); + } + bool parse_array_start() { + return true; + } + template + bool parse_array_item(input& in, size_t) { + return _parse(*this, in); + } + bool parse_object_start() { + return true; + } + template + bool parse_object_item(input& in, const std::string&) { + return _parse(*this, in); + } + + private: + null_parse_context(const null_parse_context&); + null_parse_context& operator=(const null_parse_context&); +}; + +// obsolete, use the version below +template +inline std::string parse(value& out, Iter& pos, const Iter& last) { + std::string err; + pos = parse(out, pos, last, &err); + return err; +} + +template +inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { + input in(first, last); + if (!_parse(ctx, in) && err != NULL) { + char buf[64]; + SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); + *err = buf; + while (1) { + int ch = in.getc(); + if (ch == -1 || ch == '\n') { + break; + } else if (ch >= ' ') { + err->push_back(ch); } } - return in.cur(); - } - - template inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) { - default_parse_context ctx(&out); - return _parse(ctx, first, last, err); - } - - inline std::string parse(value& out, std::istream& is) { - std::string err; - parse(out, std::istreambuf_iterator(is.rdbuf()), - std::istreambuf_iterator(), &err); - return err; - } - - template struct last_error_t { - static std::string s; - }; - template std::string last_error_t::s; - - inline void set_last_error(const std::string& s) { - last_error_t::s = s; - } - - inline const std::string& get_last_error() { - return last_error_t::s; - } - - inline bool operator==(const value& x, const value& y) { - if (x.is()) - return y.is(); -#define PICOJSON_CMP(type) \ - if (x.is()) \ - return y.is() && x.get() == y.get() - PICOJSON_CMP(bool); - PICOJSON_CMP(double); - PICOJSON_CMP(std::string); - PICOJSON_CMP(array); - PICOJSON_CMP(object); + } + return in.cur(); +} + +template +inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) { + default_parse_context ctx(&out); + return _parse(ctx, first, last, err); +} + +inline std::string parse(value& out, std::istream& is) { + std::string err; + parse(out, std::istreambuf_iterator(is.rdbuf()), std::istreambuf_iterator(), &err); + return err; +} + +template +struct last_error_t { + static std::string s; +}; +template +std::string last_error_t::s; + +inline void set_last_error(const std::string& s) { + last_error_t::s = s; +} + +inline const std::string& get_last_error() { + return last_error_t::s; +} + +inline bool operator==(const value& x, const value& y) { + if (x.is()) return y.is(); +#define PICOJSON_CMP(type) \ + if (x.is()) return y.is() && x.get() == y.get() + PICOJSON_CMP(bool); + PICOJSON_CMP(double); + PICOJSON_CMP(std::string); + PICOJSON_CMP(array); + PICOJSON_CMP(object); #undef PICOJSON_CMP - Assert(0); + Assert(0); #ifdef _MSC_VER - __assume(0); + __assume(0); #endif - return false; - } - - inline bool operator!=(const value& x, const value& y) { - return ! (x == y); - } + return false; +} + +inline bool operator!=(const value& x, const value& y) { + return !(x == y); +} } namespace std { - template<> inline void swap(picojson::value& x, picojson::value& y) - { - x.swap(y); - } +template <> +inline void swap(picojson::value& x, picojson::value& y) { + x.swap(y); +} } -inline std::istream& operator>>(std::istream& is, picojson::value& x) -{ +inline std::istream& operator>>(std::istream& is, picojson::value& x) { picojson::set_last_error(std::string()); std::string err = picojson::parse(x, is); - if (! err.empty()) { + if (!err.empty()) { picojson::set_last_error(err); is.setstate(std::ios::failbit); } return is; } -inline std::ostream& operator<<(std::ostream& os, const picojson::value& x) -{ +inline std::ostream& operator<<(std::ostream& os, const picojson::value& x) { x.serialize(std::ostream_iterator(os)); return os; } #ifdef _MSC_VER - #pragma warning(pop) +#pragma warning(pop) #endif #endif #ifdef TEST_PICOJSON #ifdef _MSC_VER - #pragma warning(disable : 4127) // conditional expression is constant +#pragma warning(disable : 4127) // conditional expression is constant #endif using namespace std; - -static void plan(int num) -{ + +static void plan(int num) { printf("1..%d\n", num); } static bool success = true; -static void ok(bool b, const char* name = "") -{ +static void ok(bool b, const char* name = "") { static int n = 1; - if (! b) - success = false; + if (!b) success = false; printf("%s %d - %s\n", b ? "ok" : "ng", n++, name); } -template void is(const T& x, const T& y, const char* name = "") -{ +template +void is(const T& x, const T& y, const char* name = "") { if (x == y) { ok(true, name); } else { @@ -836,25 +907,24 @@ template void is(const T& x, const T& y, const char* name = "") } } -#include -#include #include #include +#include +#include -int main(void) -{ +int main(void) { plan(85); - // constructors +// constructors #define TEST(expr, expected) \ - is(picojson::value expr .serialize(), string(expected), "picojson::value" #expr) - - TEST( (true), "true"); - TEST( (false), "false"); - TEST( (42.0), "42"); - TEST( (string("hello")), "\"hello\""); - TEST( ("hello"), "\"hello\""); - TEST( ("hello", 4), "\"hell\""); + is(picojson::value expr.serialize(), string(expected), "picojson::value" #expr) + + TEST((true), "true"); + TEST((false), "false"); + TEST((42.0), "42"); + TEST((string("hello")), "\"hello\""); + TEST(("hello"), "\"hello\""); + TEST(("hello", 4), "\"hell\""); { double a = 1; @@ -871,48 +941,49 @@ int main(void) a *= 2; } } - + #undef TEST - -#define TEST(in, type, cmp, serialize_test) { \ - picojson::value v; \ - const char* s = in; \ - string err = picojson::parse(v, s, s + strlen(s)); \ - ok(err.empty(), in " no error"); \ - ok(v.is(), in " check type"); \ - is(v.get(), cmp, in " correct output"); \ - is(*s, '\0', in " read to eof"); \ - if (serialize_test) { \ - is(v.serialize(), string(in), in " serialize"); \ - } \ + +#define TEST(in, type, cmp, serialize_test) \ + { \ + picojson::value v; \ + const char* s = in; \ + string err = picojson::parse(v, s, s + strlen(s)); \ + ok(err.empty(), in " no error"); \ + ok(v.is(), in " check type"); \ + is(v.get(), cmp, in " correct output"); \ + is(*s, '\0', in " read to eof"); \ + if (serialize_test) { \ + is(v.serialize(), string(in), in " serialize"); \ + } \ } TEST("false", bool, false, true); TEST("true", bool, true, true); TEST("90.5", double, 90.5, false); TEST("1.7976931348623157e+308", double, DBL_MAX, false); TEST("\"hello\"", string, string("hello"), true); - TEST("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"", string, string("\"\\/\b\f\n\r\t"), - true); - TEST("\"\\u0061\\u30af\\u30ea\\u30b9\"", string, - string("a\xe3\x82\xaf\xe3\x83\xaa\xe3\x82\xb9"), false); + TEST("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"", string, string("\"\\/\b\f\n\r\t"), true); + TEST("\"\\u0061\\u30af\\u30ea\\u30b9\"", string, string("a\xe3\x82\xaf\xe3\x83\xaa\xe3\x82\xb9"), + false); TEST("\"\\ud840\\udc0b\"", string, string("\xf0\xa0\x80\x8b"), false); #undef TEST -#define TEST(type, expr) { \ - picojson::value v; \ - const char *s = expr; \ - string err = picojson::parse(v, s, s + strlen(s)); \ - ok(err.empty(), "empty " #type " no error"); \ - ok(v.is(), "empty " #type " check type"); \ +#define TEST(type, expr) \ + { \ + picojson::value v; \ + const char* s = expr; \ + string err = picojson::parse(v, s, s + strlen(s)); \ + ok(err.empty(), "empty " #type " no error"); \ + ok(v.is(), "empty " #type " check type"); \ ok(v.get().empty(), "check " #type " array size"); \ } TEST(array, "[]"); TEST(object, "{}"); #undef TEST - + { picojson::value v; - const char *s = "[1,true,\"hello\"]"; + const char* s = "[1,true,\"hello\"]"; string err = picojson::parse(v, s, s + strlen(s)); ok(err.empty(), "array no error"); ok(v.is(), "array check type"); @@ -928,10 +999,10 @@ int main(void) is(v.get(2).get(), string("hello"), "check array[2] value"); ok(!v.contains(3), "check not contains array[3]"); } - + { picojson::value v; - const char *s = "{ \"a\": true }"; + const char* s = "{ \"a\": true }"; string err = picojson::parse(v, s, s + strlen(s)); ok(err.empty(), "object no error"); ok(v.is(), "object check type"); @@ -943,21 +1014,22 @@ int main(void) ok(!v.contains("z"), "check not contains property"); } -#define TEST(json, msg) do { \ - picojson::value v; \ - const char *s = json; \ - string err = picojson::parse(v, s, s + strlen(s)); \ - is(err, string("syntax error at line " msg), msg); \ +#define TEST(json, msg) \ + do { \ + picojson::value v; \ + const char* s = json; \ + string err = picojson::parse(v, s, s + strlen(s)); \ + is(err, string("syntax error at line " msg), msg); \ } while (0) TEST("falsoa", "1 near: oa"); TEST("{]", "1 near: ]"); TEST("\n\bbell", "2 near: bell"); TEST("\"abc\nd\"", "1 near: "); #undef TEST - + { picojson::value v1, v2; - const char *s; + const char* s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); @@ -968,7 +1040,7 @@ int main(void) { picojson::value v1, v2; - const char *s; + const char* s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); @@ -979,7 +1051,7 @@ int main(void) { picojson::value v1, v2; - const char *s; + const char* s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); @@ -990,7 +1062,7 @@ int main(void) { picojson::value v1, v2; - const char *s; + const char* s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); @@ -1005,9 +1077,8 @@ int main(void) ok((v1 == v2), "check erase()"); } - ok(picojson::value(3.0).serialize() == "3", - "integral number should be serialized as a integer"); - + ok(picojson::value(3.0).serialize() == "3", "integral number should be serialized as a integer"); + { const char* s = "{ \"a\": [1,2], \"d\": 2 }"; picojson::null_parse_context ctx; @@ -1015,7 +1086,7 @@ int main(void) picojson::_parse(ctx, s, s + strlen(s), &err); ok(err.empty(), "null_parse_context"); } - + { picojson::value v1, v2; v1 = picojson::value(true); @@ -1035,7 +1106,7 @@ int main(void) ok(v1.is(), "swap (array)"); ok(v2.is(), "swap (object)"); } - + return success ? 0 : 1; } diff --git a/src/common/platform_exception.cc b/src/common/platform_exception.cc old mode 100755 new mode 100644 index 20d6892..db7a3d1 --- a/src/common/platform_exception.cc +++ b/src/common/platform_exception.cc @@ -13,16 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "common/platform_exception.h" namespace common { -PlatformException::PlatformException( - const std::string& name, - const std::string& message) - : name_(name), - message_(message) { +PlatformException::PlatformException(const std::string& name, const std::string& message) + : name_(name), message_(message) { } PlatformException::~PlatformException() { @@ -44,4 +41,4 @@ picojson::value PlatformException::ToJSON() const { return ret; } -} // namespace common +} // namespace common diff --git a/src/common/platform_exception.h b/src/common/platform_exception.h old mode 100755 new mode 100644 index 3054187..a742e68 --- a/src/common/platform_exception.h +++ b/src/common/platform_exception.h @@ -37,13 +37,12 @@ class PlatformException { std::string message_; }; -#define DEFINE_EXCEPTION(NAME) \ -class NAME##Exception: public PlatformException { \ - public: \ - NAME##Exception(const std::string& msg) \ - : PlatformException(#NAME "Error", msg) { \ - } \ -}; +#define DEFINE_EXCEPTION(NAME) \ + class NAME##Exception : public PlatformException { \ + public: \ + NAME##Exception(const std::string& msg) : PlatformException(#NAME "Error", msg) { \ + } \ + }; DEFINE_EXCEPTION(Unknown) DEFINE_EXCEPTION(TypeMismatch) DEFINE_EXCEPTION(InvalidValues) @@ -60,6 +59,6 @@ DEFINE_EXCEPTION(InvalidState) DEFINE_EXCEPTION(InvalidModification) #undef DEFINE_EXCEPTION -} // namespace common +} // namespace common -#endif // COMMON_PLATFORM_EXCEPTION_H_ +#endif // COMMON_PLATFORM_EXCEPTION_H_ diff --git a/src/common/platform_result.cc b/src/common/platform_result.cc old mode 100755 new mode 100644 index cc85f30..ec3a50d --- a/src/common/platform_result.cc +++ b/src/common/platform_result.cc @@ -19,10 +19,8 @@ namespace common { -PlatformResult::PlatformResult(const ErrorCode& error_code, const std::string& message) : - error_code_(error_code), - message_(message) -{ +PlatformResult::PlatformResult(const ErrorCode& error_code, const std::string& message) + : error_code_(error_code), message_(message) { LoggerD("Enter"); if (ErrorCode::NO_ERROR != error_code) { @@ -34,12 +32,9 @@ picojson::value PlatformResult::ToJSON() const { LoggerD("Enter"); picojson::value::object obj; obj["code"] = picojson::value(static_cast(error_code_)); - if (!message_.empty()) - obj["message"] = picojson::value(message_); + if (!message_.empty()) obj["message"] = picojson::value(message_); picojson::value ret(obj); return ret; } } // namespace common - - diff --git a/src/common/platform_result.h b/src/common/platform_result.h old mode 100755 new mode 100644 index f250556..4b69f1e --- a/src/common/platform_result.h +++ b/src/common/platform_result.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef SRC_COMMON_PLATFORM_RESULT_H_ #define SRC_COMMON_PLATFORM_RESULT_H_ @@ -74,15 +74,24 @@ enum class ErrorCode : int { class PlatformResult { public: - explicit PlatformResult(const ErrorCode& error_code, - const std::string& message = ""); + explicit PlatformResult(const ErrorCode& error_code, const std::string& message = ""); - ErrorCode error_code() const { return error_code_; } - std::string message() const { return message_; } + ErrorCode error_code() const { + return error_code_; + } + std::string message() const { + return message_; + } - bool IsSuccess() const { return error_code() == ErrorCode::NO_ERROR; } - bool IsError() const { return !IsSuccess(); } - explicit operator bool() const { return IsSuccess(); } + bool IsSuccess() const { + return error_code() == ErrorCode::NO_ERROR; + } + bool IsError() const { + return !IsSuccess(); + } + explicit operator bool() const { + return IsSuccess(); + } picojson::value ToJSON() const; diff --git a/src/common/scope_exit.h b/src/common/scope_exit.h index fda1b45..a2a7627 100644 --- a/src/common/scope_exit.h +++ b/src/common/scope_exit.h @@ -2,13 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - - // Header file coppied from crosswalk extensions repository. Difference is to miss final keyword // in class ScopeExit - - #ifndef COMMON_SCOPE_EXIT_H_ #define COMMON_SCOPE_EXIT_H_ @@ -45,13 +41,13 @@ namespace common { * // do 3rd operation with unit and possibly quit function * } */ -template +template class ScopeExit { public: - ScopeExit(Func func) : func_(func), released_(false) { } // NOLINT + ScopeExit(Func func) : func_(func), released_(false) { + } // NOLINT ~ScopeExit() noexcept(false) { - if (!released_) - func_(); + if (!released_) func_(); } ScopeExit(const ScopeExit&) = delete; @@ -74,14 +70,11 @@ ScopeExit MakeScopeExit(F f) { // Internal use for macro SCOPE_EXIT -struct __dummy{}; +struct __dummy {}; template -ScopeExit::type> -operator+(__dummy, F&& f) -{ - return ScopeExit::type> - {std::forward(f)}; +ScopeExit::type> operator+(__dummy, F&& f) { + return ScopeExit::type>{std::forward(f)}; } /* @@ -106,10 +99,9 @@ operator+(__dummy, F&& f) * // do 3rd operation with unit and possibly quit function * } */ -#define _SYNTAX_CONCAT(A, B) A ## B +#define _SYNTAX_CONCAT(A, B) A##B #define SYNTAX_CONCAT(A, B) _SYNTAX_CONCAT(A, B) -#define SCOPE_EXIT \ - auto SYNTAX_CONCAT(SCOPE_EXIT_, __LINE__) = ::common::__dummy{} + [&]() +#define SCOPE_EXIT auto SYNTAX_CONCAT(SCOPE_EXIT_, __LINE__) = ::common::__dummy{} + [&]() } // namespace common diff --git a/src/common/task-queue.cpp b/src/common/task-queue.cpp old mode 100755 new mode 100644 index 2fc305c..9bafdae --- a/src/common/task-queue.cpp +++ b/src/common/task-queue.cpp @@ -19,49 +19,49 @@ namespace common { TaskQueue& TaskQueue::GetInstance() { - static TaskQueue task_queue; - return task_queue; + static TaskQueue task_queue; + return task_queue; } template <> gboolean TaskQueue::AfterWorkCallback(gpointer data) { - QueueData* d = static_cast*>(data); - if (nullptr != d) { - d->after_work_callback_(); - delete d; - } - return FALSE; + QueueData* d = static_cast*>(data); + if (nullptr != d) { + d->after_work_callback_(); + delete d; + } + return FALSE; } template <> void* TaskQueue::WorkCallback(void* data) { - QueueData* d = static_cast*>(data); - if (nullptr != d) { - d->work_callback_(); - if (d->after_work_callback_) { - g_idle_add(AfterWorkCallback, d); - } + QueueData* d = static_cast*>(data); + if (nullptr != d) { + d->work_callback_(); + if (d->after_work_callback_) { + g_idle_add(AfterWorkCallback, d); } - return nullptr; + } + return nullptr; } void TaskQueue::Queue(const std::function& work, const std::function& after_work) { - QueueData* d = new QueueData(); - d->work_callback_ = work; - d->after_work_callback_ = after_work; + QueueData* d = new QueueData(); + d->work_callback_ = work; + d->after_work_callback_ = after_work; - if (pthread_create(&d->thread_, nullptr, WorkCallback, d) != 0) { - LoggerE("Failed to create a background thread."); - delete d; - } else { - pthread_detach(d->thread_); - } + if (pthread_create(&d->thread_, nullptr, WorkCallback, d) != 0) { + LoggerE("Failed to create a background thread."); + delete d; + } else { + pthread_detach(d->thread_); + } } void TaskQueue::Async(const std::function& work) { - QueueData* d = new QueueData(); - d->after_work_callback_ = work; - g_idle_add(AfterWorkCallback, d); + QueueData* d = new QueueData(); + d->after_work_callback_ = work; + g_idle_add(AfterWorkCallback, d); } -} // namespace common +} // namespace common diff --git a/src/common/task-queue.h b/src/common/task-queue.h old mode 100755 new mode 100644 index 94df211..fb3300a --- a/src/common/task-queue.h +++ b/src/common/task-queue.h @@ -13,137 +13,138 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef WEBAPI_PLUGINS_COMMON_THREAD_SCHEDULER_H_ #define WEBAPI_PLUGINS_COMMON_THREAD_SCHEDULER_H_ #include +#include #include #include -#include #include "logger.h" namespace common { class TaskQueue { -public: - TaskQueue(const TaskQueue&) = delete; - TaskQueue& operator=(const TaskQueue&) = delete; - - static TaskQueue& GetInstance(); - - /** - * @brief Schedules work to be executed in a separate thread, after_work is going - * to be called in main glib loop. - * - * @param[in] work - callback is going to be called in a separate thread - * @param[in] after_work - callback is going to be called in main glib loop - * @param[in] data - data passed to both callbacks - */ - template - void Queue(const std::function&)>& work, - const std::function&)>& after_work, - const std::shared_ptr& data); - - /** - * @brief Schedules work to be executed in a separate thread, after_work is going - * to be called in main glib loop. - * - * @param[in] work - callback is going to be called in a separate thread - * @param[in] after_work - callback is going to be called in main glib loop - */ - void Queue(const std::function& work, - const std::function& after_work = std::function()); - - /** - * @brief Schedules work to be executed in main glib loop. - * - * @param[in] work - callback is going to be called in main glib loop - * @param[in] data - data passed to callback - */ - template - void Async(const std::function&)>& work, - const std::shared_ptr& data); - - /** - * @brief Schedules work to be executed in main glib loop. - * - * @param[in] work - callback is going to be called in main glib loop - */ - void Async(const std::function& work); - -private: - TaskQueue() {} - - template - struct QueueData { - pthread_t thread_; - std::function&)> work_callback_; - std::function&)> after_work_callback_; - std::shared_ptr data_; - }; - - template - static void* WorkCallback(void* data); - - template - static gboolean AfterWorkCallback(gpointer data); + public: + TaskQueue(const TaskQueue&) = delete; + TaskQueue& operator=(const TaskQueue&) = delete; + + static TaskQueue& GetInstance(); + + /** + * @brief Schedules work to be executed in a separate thread, after_work is going + * to be called in main glib loop. + * + * @param[in] work - callback is going to be called in a separate thread + * @param[in] after_work - callback is going to be called in main glib loop + * @param[in] data - data passed to both callbacks + */ + template + void Queue(const std::function&)>& work, + const std::function&)>& after_work, + const std::shared_ptr& data); + + /** + * @brief Schedules work to be executed in a separate thread, after_work is going + * to be called in main glib loop. + * + * @param[in] work - callback is going to be called in a separate thread + * @param[in] after_work - callback is going to be called in main glib loop + */ + void Queue(const std::function& work, + const std::function& after_work = std::function()); + + /** + * @brief Schedules work to be executed in main glib loop. + * + * @param[in] work - callback is going to be called in main glib loop + * @param[in] data - data passed to callback + */ + template + void Async(const std::function&)>& work, + const std::shared_ptr& data); + + /** + * @brief Schedules work to be executed in main glib loop. + * + * @param[in] work - callback is going to be called in main glib loop + */ + void Async(const std::function& work); + + private: + TaskQueue() { + } + + template + struct QueueData { + pthread_t thread_; + std::function&)> work_callback_; + std::function&)> after_work_callback_; + std::shared_ptr data_; + }; + + template + static void* WorkCallback(void* data); + + template + static gboolean AfterWorkCallback(gpointer data); }; template <> struct TaskQueue::QueueData { - pthread_t thread_; - std::function work_callback_; - std::function after_work_callback_; + pthread_t thread_; + std::function work_callback_; + std::function after_work_callback_; }; template gboolean TaskQueue::AfterWorkCallback(gpointer data) { - QueueData* d = static_cast*>(data); - if (nullptr != d) { - d->after_work_callback_(d->data_); - delete d; - } - return FALSE; + QueueData* d = static_cast*>(data); + if (nullptr != d) { + d->after_work_callback_(d->data_); + delete d; + } + return FALSE; } template void* TaskQueue::WorkCallback(void* data) { - QueueData* d = static_cast*>(data); - if (nullptr != d) { - d->work_callback_(d->data_); - g_idle_add(AfterWorkCallback, d); - } - return nullptr; + QueueData* d = static_cast*>(data); + if (nullptr != d) { + d->work_callback_(d->data_); + g_idle_add(AfterWorkCallback, d); + } + return nullptr; } template void TaskQueue::Queue(const std::function&)>& work, const std::function&)>& after_work, const std::shared_ptr& data) { - QueueData* d = new QueueData(); - d->work_callback_ = work; - d->after_work_callback_ = after_work; - d->data_ = data; - - if (pthread_create(&d->thread_, nullptr, WorkCallback, d) != 0) { - LoggerE("Failed to create a background thread."); - delete d; - } else { - pthread_detach(d->thread_); - } + QueueData* d = new QueueData(); + d->work_callback_ = work; + d->after_work_callback_ = after_work; + d->data_ = data; + + if (pthread_create(&d->thread_, nullptr, WorkCallback, d) != 0) { + LoggerE("Failed to create a background thread."); + delete d; + } else { + pthread_detach(d->thread_); + } } template void TaskQueue::Async(const std::function&)>& work, const std::shared_ptr& data) { - QueueData* d = new QueueData(); - d->after_work_callback_ = work; - d->data_ = data; - g_idle_add(AfterWorkCallback, d); + QueueData* d = new QueueData(); + d->after_work_callback_ = work; + d->data_ = data; + g_idle_add(AfterWorkCallback, d); } -} // namespace common +} // namespace common -#endif // WEBAPI_PLUGINS_COMMON_THREAD_SCHEDULER_H_ +#endif // WEBAPI_PLUGINS_COMMON_THREAD_SCHEDULER_H_ diff --git a/src/common/tizen_instance.cc b/src/common/tizen_instance.cc index 8c8d526..504ee11 100644 --- a/src/common/tizen_instance.cc +++ b/src/common/tizen_instance.cc @@ -45,20 +45,22 @@ void TizenInstance::RegisterHandler(const std::string& name, const AsyncHandler& ScopeLogger(); // TODO: change to RegisterHandler() when applicable - ParsedInstance::RegisterSyncHandler(name, [func](const picojson::value& args, picojson::object& out) -> void { - const auto& a = args.get(); - auto result = func(a, AsyncToken(a)); - result.ToJson(&out); - }); + ParsedInstance::RegisterSyncHandler( + name, [func](const picojson::value& args, picojson::object& out) -> void { + const auto& a = args.get(); + auto result = func(a, AsyncToken(a)); + result.ToJson(&out); + }); } void TizenInstance::RegisterSyncHandler(const std::string& name, const SyncHandler& func) { ScopeLogger(); - ParsedInstance::RegisterSyncHandler(name, [func](const picojson::value& args, picojson::object& out) -> void { - auto result = func(args.get()); - result.ToJson(&out); - }); + ParsedInstance::RegisterSyncHandler( + name, [func](const picojson::value& args, picojson::object& out) -> void { + auto result = func(args.get()); + result.ToJson(&out); + }); } void TizenInstance::Post(const AsyncToken& token, const TizenResult& result) { @@ -70,9 +72,8 @@ void TizenInstance::Post(const AsyncToken& token, const TizenResult& result) { token.ToJson(&obj); result.ToJson(&obj); - TaskQueue::GetInstance().Async([this, msg]() { - ParsedInstance::PostMessage(this, msg.serialize().c_str()); - }); + TaskQueue::GetInstance().Async( + [this, msg]() { ParsedInstance::PostMessage(this, msg.serialize().c_str()); }); } PostCallback TizenInstance::SimplePost(const AsyncToken& token) { diff --git a/src/common/tizen_instance.h b/src/common/tizen_instance.h index b8537ff..bb859e2 100644 --- a/src/common/tizen_instance.h +++ b/src/common/tizen_instance.h @@ -29,12 +29,14 @@ namespace common { class AsyncToken { public: explicit AsyncToken(const picojson::object& msg); - virtual ~AsyncToken() {} + virtual ~AsyncToken() { + } virtual void ToJson(picojson::object* msg) const; protected: - AsyncToken() : value_(-1.0) {} + AsyncToken() : value_(-1.0) { + } private: double value_; @@ -42,7 +44,8 @@ class AsyncToken { class ListenerToken : public AsyncToken { public: - explicit ListenerToken(const std::string& lid) : lid_(lid) {} + explicit ListenerToken(const std::string& lid) : lid_(lid) { + } virtual void ToJson(picojson::object* msg) const override; diff --git a/src/common/tizen_result.cc b/src/common/tizen_result.cc index ed8a4c8..8508ae6 100644 --- a/src/common/tizen_result.cc +++ b/src/common/tizen_result.cc @@ -26,13 +26,11 @@ void TizenResult::ToJson(picojson::object* msg) const { } } -TizenSuccess::TizenSuccess() - : TizenResult(ErrorCode::NO_ERROR) { +TizenSuccess::TizenSuccess() : TizenResult(ErrorCode::NO_ERROR) { tools::ReportSuccess(data_); } -TizenSuccess::TizenSuccess(const picojson::value& r) - : TizenResult(ErrorCode::NO_ERROR) { +TizenSuccess::TizenSuccess(const picojson::value& r) : TizenResult(ErrorCode::NO_ERROR) { tools::ReportSuccess(r, data_); } @@ -46,10 +44,12 @@ TizenError::TizenError(const ErrorCode& error_code, int platform_error) tools::ReportError(*this, &data_); } -#define DefineErrorClass(name) \ -const ErrorCode name::code_; \ -name::name(const std::string& msg) : TizenError(code_, msg) {} \ -name::name(int error_code) : TizenError(code_, error_code) {} +#define DefineErrorClass(name) \ + const ErrorCode name::code_; \ + name::name(const std::string& msg) : TizenError(code_, msg) { \ + } \ + name::name(int error_code) : TizenError(code_, error_code) { \ + } DefineErrorClass(IndexSizeError); DefineErrorClass(DomStringSizeError); diff --git a/src/common/tizen_result.h b/src/common/tizen_result.h index d1e18a4..aa45ca7 100644 --- a/src/common/tizen_result.h +++ b/src/common/tizen_result.h @@ -44,14 +44,15 @@ class TizenError : public TizenResult { TizenError(const ErrorCode& error_code, int platform_error); }; -#define DeclareErrorClass(name, code) \ -class name : public TizenError { \ - public: \ - explicit name(const std::string& msg = ""); \ - explicit name(int error_code); \ - private: \ - static const ErrorCode code_ = code; \ -} +#define DeclareErrorClass(name, code) \ + class name : public TizenError { \ + public: \ + explicit name(const std::string& msg = ""); \ + explicit name(int error_code); \ + \ + private: \ + static const ErrorCode code_ = code; \ + } DeclareErrorClass(IndexSizeError, ErrorCode::INDEX_SIZE_ERR); DeclareErrorClass(DomStringSizeError, ErrorCode::DOMSTRING_SIZE_ERR); diff --git a/src/common/tools.cc b/src/common/tools.cc index cd8beea..588663f 100644 --- a/src/common/tools.cc +++ b/src/common/tools.cc @@ -16,9 +16,9 @@ #include "common/tools.h" -#include #include #include +#include #include #ifdef PRIVILEGE_USE_DB @@ -73,8 +73,7 @@ namespace { class AccessControlImpl { public: - AccessControlImpl() - : initialized_(false) { + AccessControlImpl() : initialized_(false) { LoggerD("Privilege access checked using DB."); const char* kWrtDBPath = "/opt/dbspace/.wrt.db"; @@ -86,9 +85,10 @@ class AccessControlImpl { return; } - const char* kQuery = "select name from WidgetFeature where app_id = " - "(select app_id from WidgetInfo where tizen_appid = ?)" - " and rejected = 0"; + const char* kQuery = + "select name from WidgetFeature where app_id = " + "(select app_id from WidgetInfo where tizen_appid = ?)" + " and rejected = 0"; const std::string app_id = common::CurrentApplication::GetInstance().GetApplicationId(); sqlite3_stmt* stmt = nullptr; @@ -114,7 +114,8 @@ class AccessControlImpl { initialized_ = true; } - ~AccessControlImpl() {} + ~AccessControlImpl() { + } bool CheckAccess(const std::vector& privileges) { LoggerD("Enter"); @@ -123,7 +124,8 @@ class AccessControlImpl { } for (const auto& privilege : privileges) { - if (std::find(granted_privileges_.begin(), granted_privileges_.end(), privilege) == granted_privileges_.end()) { + if (std::find(granted_privileges_.begin(), granted_privileges_.end(), privilege) == + granted_privileges_.end()) { return false; } } @@ -162,7 +164,7 @@ class AccessControlImpl { LoggerD("Privilege access checked using Cynara."); char* smack_label = nullptr; - int len= smack_new_label_from_self(&smack_label); + int len = smack_new_label_from_self(&smack_label); if (0 < len && nullptr != smack_label) { auto uid = getuid(); @@ -197,15 +199,14 @@ class AccessControlImpl { } bool CheckAccess(const std::vector& privileges) { - if (cynara_) { for (const auto& privilege : privileges) { - if (CYNARA_API_ACCESS_ALLOWED != cynara_check(cynara_, // p_cynara + if (CYNARA_API_ACCESS_ALLOWED != cynara_check(cynara_, // p_cynara smack_label_.c_str(), // client - "", // client_session - uid_.c_str(), // user - privilege.c_str() // privilege - )) { + "", // client_session + uid_.c_str(), // user + privilege.c_str()) // privilege + ) { return false; } } @@ -252,13 +253,14 @@ class AccessControl { } private: - AccessControl() {} - ~AccessControl() {} + AccessControl() { + } + ~AccessControl() { + } AccessControlImpl impl_; }; -} // namespace - +} // namespace PlatformResult CheckAccess(const std::string& privilege) { return CheckAccess(std::vector{privilege}); @@ -283,8 +285,8 @@ PlatformResult CheckAccess(const std::vector& privileges) { for (auto input_priv : privileges) { LoggerD("Input privilege: %s", input_priv.c_str()); - GList *input_glist = nullptr; - GList *mapped_glist = nullptr; + GList* input_glist = nullptr; + GList* mapped_glist = nullptr; SCOPE_EXIT { g_list_free(input_glist); @@ -299,10 +301,8 @@ PlatformResult CheckAccess(const std::vector& privileges) { LoggerD("Mapped privileges - need to be fetched from database"); // Not in cache - retrieve from underlying databases. input_glist = g_list_append(input_glist, (void*)input_priv.c_str()); - int ret = privilege_manager_get_mapped_privilege_list(api_version.c_str(), - PRVMGR_PACKAGE_TYPE_WRT, - input_glist, - &mapped_glist); + int ret = privilege_manager_get_mapped_privilege_list( + api_version.c_str(), PRVMGR_PACKAGE_TYPE_WRT, input_glist, &mapped_glist); if (PRVMGR_ERR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to get mapped privilege list"); } @@ -320,15 +320,15 @@ PlatformResult CheckAccess(const std::vector& privileges) { } }; // fill the vector with data - g_list_foreach (mapped_glist, push_elem, &mapped_privilege_cache[input_priv]); + g_list_foreach(mapped_glist, push_elem, &mapped_privilege_cache[input_priv]); mapped_vector_ptr = &mapped_privilege_cache[input_priv]; } else { // Retrieve from local cache LoggerD("Mapped privileges already in cache"); - mapped_vector_ptr = (std::vector*) &(it->second); + mapped_vector_ptr = (std::vector*)&(it->second); } - if (!AccessControl::GetInstance().CheckAccess(*mapped_vector_ptr)){ + if (!AccessControl::GetInstance().CheckAccess(*mapped_vector_ptr)) { for (const auto& mapped_priv : *mapped_vector_ptr) { LoggerD("Access to privilege: %s has been denied.", mapped_priv.c_str()); } @@ -409,15 +409,13 @@ PlatformResult GetPkgApiVersion(std::string* api_version) { std::vector SplitString(const std::string& str, const std::string& delim) { std::vector tokens; size_t prev = 0, pos = 0; - do - { + do { pos = str.find(delim, prev); if (pos == std::string::npos) pos = str.length(); - std::string token = str.substr(prev, pos-prev); + std::string token = str.substr(prev, pos - prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); - } - while (pos < str.length() && prev < str.length()); + } while (pos < str.length() && prev < str.length()); return tokens; } @@ -426,7 +424,8 @@ bool IsAppVersionEarlierThan(const std::string& ver) { std::string app_ver; auto res = GetPkgApiVersion(&app_ver); if (!res) { - LoggerE("Failed to get application version, " + LoggerE( + "Failed to get application version, " "assuming that application version is same as platform"); return false; } @@ -453,7 +452,6 @@ std::string GetErrorString(int error_code) { return msg; } - int HexToInt(char c) { if (c >= '0' && c <= '9') { return c - '0'; @@ -473,7 +471,7 @@ unsigned char* HexToBin(const char* hex, int size, unsigned char* bin, int bin_s } char* BinToHex(const unsigned char* bin, int size, char* hex, int hex_size) { - static const char * const digits = "0123456789ABCDEF"; + static const char* const digits = "0123456789ABCDEF"; for (int i = 0; i < size && i < hex_size / 2; i++) { hex[i * 2] = digits[bin[i] >> 4]; hex[i * 2 + 1] = digits[bin[i] & 0xF]; @@ -487,12 +485,9 @@ bool IsPathValid(const std::string& path) { /* * Directory dot-referencing is not allowed */ - return std::string::npos == path.find("/../") && - std::string::npos == path.find("/./") && - 0 != path.find("./") && - 0 != path.find("../") && - path.length() - 2 != path.rfind("/.") && - path.length() - 3 != path.rfind("/.."); + return std::string::npos == path.find("/../") && std::string::npos == path.find("/./") && + 0 != path.find("./") && 0 != path.find("../") && path.length() - 2 != path.rfind("/.") && + path.length() - 3 != path.rfind("/.."); } PlatformResult CheckFileStatus(const std::string& path) { @@ -514,8 +509,8 @@ PlatformResult CheckFileStatus(const std::string& path) { } if (!S_ISREG(buf.st_mode)) { - return PlatformResult(ErrorCode::NOT_FOUND_ERR, "Path does not point to a regular file: " - + path); + return PlatformResult(ErrorCode::NOT_FOUND_ERR, + "Path does not point to a regular file: " + path); } if (!(S_IRUSR & buf.st_mode)) { diff --git a/src/common/tools.h b/src/common/tools.h index fc905ec..d72a09b 100644 --- a/src/common/tools.h +++ b/src/common/tools.h @@ -39,38 +39,38 @@ common::PlatformResult GetPkgApiVersion(std::string* api_version); bool IsAppVersionEarlierThan(const std::string& ver); -//it is used for modules which return TizenResult objects to JS layer -#define CHECK_PRIVILEGE(privilege) \ -do { \ - auto r = common::tools::CheckAccess(privilege); \ - if (!r) { \ - return common::SecurityError("Application does not have privilege to call this method"); \ - } \ -} while (0) - -#define CHECK_PRIVILEGE_ACCESS(privilege, out) \ -do { \ - auto r = common::tools::CheckAccess(privilege); \ - if (!r) { \ - common::tools::ReportError(r, out); \ - return; \ - } \ -} while (0) +// it is used for modules which return TizenResult objects to JS layer +#define CHECK_PRIVILEGE(privilege) \ + do { \ + auto r = common::tools::CheckAccess(privilege); \ + if (!r) { \ + return common::SecurityError("Application does not have privilege to call this method"); \ + } \ + } while (0) + +#define CHECK_PRIVILEGE_ACCESS(privilege, out) \ + do { \ + auto r = common::tools::CheckAccess(privilege); \ + if (!r) { \ + common::tools::ReportError(r, out); \ + return; \ + } \ + } while (0) #define CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(current_priv, prev_priv, out) \ -do { \ - auto ret = common::tools::CheckAccess(current_priv); \ - auto ret2 = common::tools::CheckAccess(prev_priv); \ -\ - if (!ret && ret2) { \ - ret = ret2; \ - } \ -\ - if (!ret) { \ - common::tools::ReportError(ret, out); \ - return; \ - } \ -} while (0) + do { \ + auto ret = common::tools::CheckAccess(current_priv); \ + auto ret2 = common::tools::CheckAccess(prev_priv); \ + \ + if (!ret && ret2) { \ + ret = ret2; \ + } \ + \ + if (!ret) { \ + common::tools::ReportError(ret, out); \ + return; \ + } \ + } while (0) /** * @brief Safe wrapper of strerror() function. diff --git a/src/common/typeutil.h b/src/common/typeutil.h old mode 100755 new mode 100644 index c20c398..58065f1 --- a/src/common/typeutil.h +++ b/src/common/typeutil.h @@ -50,10 +50,11 @@ using picojson::array; template bool IsType(const value& arg, const char* name); -#define IS_TYPE_NORANGE(wtype, ctype) \ - template <> bool IsType(const value& arg, const char* name) { \ - return arg.get(name).is(); \ - } +#define IS_TYPE_NORANGE(wtype, ctype) \ + template <> \ + bool IsType(const value& arg, const char* name) { \ + return arg.get(name).is(); \ + } IS_TYPE_NORANGE(StringType, std::string) IS_TYPE_NORANGE(ArrayType, array) IS_TYPE_NORANGE(ObjectType, object) @@ -62,14 +63,15 @@ IS_TYPE_NORANGE(DoubleType, double) IS_TYPE_NORANGE(FloatType, double) #undef IS_TYPE_NORANGE -#define IS_TYPE_RANGE(wtype, min, max) \ - template <> bool IsType(const value& arg, const char* name) { \ - const value& v = arg.get(name); \ - if (!v.is()) return false; \ - double n = v.get(); \ - if (n < min || n > max) return false; \ - return true; \ - } +#define IS_TYPE_RANGE(wtype, min, max) \ + template <> \ + bool IsType(const value& arg, const char* name) { \ + const value& v = arg.get(name); \ + if (!v.is()) return false; \ + double n = v.get(); \ + if (n < min || n > max) return false; \ + return true; \ + } IS_TYPE_RANGE(ByteType, -128, 127) IS_TYPE_RANGE(OctetType, 0, 255) IS_TYPE_RANGE(ShortType, -32768, 32767) @@ -80,71 +82,63 @@ IS_TYPE_RANGE(LongLongType, -9223372036854775807LL, 9223372036854775807LL) IS_TYPE_RANGE(UnsignedLongLongType, 0, 18446744073709551615ULL) #undef IS_TYPE_RANGE -bool IsEnum(const value& arg, const std::string& name, - const std::set& values) { +bool IsEnum(const value& arg, const std::string& name, const std::set& values) { const value& v = arg.get(name); - return v.is() && - values.find(v.get()) != values.end(); + return v.is() && values.find(v.get()) != values.end(); } } // namespace WIDLTypeValidator namespace CTypeConveter { -enum CType { - StringType, - ArrayType -}; +enum CType { StringType, ArrayType }; } // namespace CTypeConveter } // namespace common #ifdef TEST_TYPEUTIL -#include #include -//using namespace common::WIDLTypeValidator; +#include +// using namespace common::WIDLTypeValidator; int main(void) { - const char *tc = + const char* tc = "{" - "\"string\": \"string value\"," - "\"object\": {\"first\":1, \"second\":2}," - "\"array\": [1,2,3,4]," - "\"array2\": [1,\"two\",3,{\"obj\":\"obj!!\"}]," - "\"boolean\": true," - "\"double\": 12345678.9999," - "\"float\": 12345.678," - "\"byte1\": -128," - "\"byte2\": 127," - "\"octet\": 255," - "\"short1\": -32768," - "\"short2\": 32767," - "\"ushort\": 65535," - "\"long1\": -2147483648," - "\"long2\": 2147483647," - "\"ulong\": 4294967295," - "\"longlong1\": -9223372036854775808," - "\"longlong2\": 9223372036854775807," - "\"ulonglong\": 18446744073709551615," - "\"zero\": 0," - "\"enum\": \"enum\"" + "\"string\": \"string value\"," + "\"object\": {\"first\":1, \"second\":2}," + "\"array\": [1,2,3,4]," + "\"array2\": [1,\"two\",3,{\"obj\":\"obj!!\"}]," + "\"boolean\": true," + "\"double\": 12345678.9999," + "\"float\": 12345.678," + "\"byte1\": -128," + "\"byte2\": 127," + "\"octet\": 255," + "\"short1\": -32768," + "\"short2\": 32767," + "\"ushort\": 65535," + "\"long1\": -2147483648," + "\"long2\": 2147483647," + "\"ulong\": 4294967295," + "\"longlong1\": -9223372036854775808," + "\"longlong2\": 9223372036854775807," + "\"ulonglong\": 18446744073709551615," + "\"zero\": 0," + "\"enum\": \"enum\"" "}"; picojson::value v; std::string err = picojson::parse(v, tc, tc + strlen(tc)); printf("parse err : %s\n", err.c_str()); - using common::WIDLTypeValidator::WIDLType; using common::WIDLTypeValidator::IsType; using common::WIDLTypeValidator::IsEnum; -#define TC_POSITIVE(name, wtype) \ - printf("%s positive %s : %s\n", #wtype, \ - IsType(v, name) ? "pass" : "fail", \ +#define TC_POSITIVE(name, wtype) \ + printf("%s positive %s : %s\n", #wtype, IsType(v, name) ? "pass" : "fail", \ v.get(name).to_str().c_str()); -#define TC_NEGATIVE(name, wtype) \ - printf("%s negative %s : %s\n", #wtype, \ - !IsType(v, name) ? "pass" : "fail", \ +#define TC_NEGATIVE(name, wtype) \ + printf("%s negative %s : %s\n", #wtype, !IsType(v, name) ? "pass" : "fail", \ v.get(name).to_str().c_str()); TC_POSITIVE("string", WIDLType::StringType); @@ -264,13 +258,10 @@ int main(void) { TC_NEGATIVE("array2", WIDLType::UnsignedLongLongType); TC_NEGATIVE("boolean", WIDLType::UnsignedLongLongType); - std::string values[] = { - "enum", "foo", "bar" - }; - std::set enums(values, values+3); + std::string values[] = {"enum", "foo", "bar"}; + std::set enums(values, values + 3); bool enum_p = IsEnum(v, "enum", enums); - printf("%s positive %s : %s\n", "enum", enum_p ? "pass" : "fail", - v.get("enum").to_str().c_str()); + printf("%s positive %s : %s\n", "enum", enum_p ? "pass" : "fail", v.get("enum").to_str().c_str()); bool enum_n = IsEnum(v, "xxx", enums); printf("%s negative %s : %s\n", "enum", !enum_n ? "pass" : "fail", v.get("enum").to_str().c_str()); diff --git a/src/common/utils.h b/src/common/utils.h old mode 100755 new mode 100644 index c118025..f04b1fd --- a/src/common/utils.h +++ b/src/common/utils.h @@ -7,12 +7,10 @@ #define COMMON_UTILS_H_ // Put this in the private: declarations for a class to be uncopyable. -#define DISALLOW_COPY(TypeName) \ - TypeName(const TypeName&) +#define DISALLOW_COPY(TypeName) TypeName(const TypeName&) // Put this in the private: declarations for a class to be unassignable. -#define DISALLOW_ASSIGN(TypeName) \ - void operator=(const TypeName&) +#define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName&) // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class diff --git a/src/contact/addressbook.cc b/src/contact/addressbook.cc old mode 100755 new mode 100644 index 8431eff..755a857 --- a/src/contact/addressbook.cc +++ b/src/contact/addressbook.cc @@ -46,7 +46,9 @@ inline bool IsUnified(const JsonObject& args) { return AddressBookId(args) == kUnifiedAddressBookId; } -inline bool IsUnified(long id) { return id == kUnifiedAddressBookId; } +inline bool IsUnified(long id) { + return id == kUnifiedAddressBookId; +} } // anonymous namespace @@ -58,19 +60,16 @@ PlatformResult AddressBookGet(const JsonObject& args, JsonObject& out) { int contact_id = common::stol(FromJson(args, "id")); contacts_record_h contacts_record = nullptr; - int err = contacts_db_get_record(_contacts_contact._uri, contact_id, - &contacts_record); + int err = contacts_db_get_record(_contacts_contact._uri, contact_id, &contacts_record); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Contacts record get error", - ("Contacts record get error, error code: %d", err)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Contacts record get error", + ("Contacts record get error, error code: %d", err)); } - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); out["id"] = picojson::value(std::to_string(contact_id)); - status = - ContactUtil::ImportContactFromContactsRecord(*contacts_record_ptr, &out); + status = ContactUtil::ImportContactFromContactsRecord(*contacts_record_ptr, &out); if (status.IsError()) return status; status = ContactUtil::UpdateAdditionalInformation(*contacts_record_ptr, &out); @@ -95,20 +94,18 @@ PlatformResult AddressBookAdd(const JsonObject& args, JsonObject& out) { int err = 0; err = contacts_record_create(_contacts_contact._uri, &contacts_record); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contacts record create error", - ("Contacts record create error, error code: %d", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record create error", + ("Contacts record create error, error code: %d", err)); } // contacts_record starts to be protected by unique_ptr - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); - status = - ContactUtil::ExportContactToContactsRecord(*contacts_record_ptr, contact); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); + status = ContactUtil::ExportContactToContactsRecord(*contacts_record_ptr, contact); if (status.IsError()) return status; - status = ContactUtil::SetIntInRecord( - contacts_record, _contacts_contact.address_book_id, addressBookId); + status = ContactUtil::SetIntInRecord(contacts_record, _contacts_contact.address_book_id, + addressBookId); if (status.IsError()) return status; int id = -1; @@ -152,28 +149,23 @@ PlatformResult AddressBookUpdate(const JsonObject& args, JsonObject& out) { contacts_record_h to_update = nullptr; int err = contacts_db_get_record(_contacts_contact._uri, contactId, &to_update); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Problem with getting contact", - ("Problem with getting contact. Error: %d", err)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Problem with getting contact", + ("Problem with getting contact. Error: %d", err)); } - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &to_update, ContactUtil::ContactsDeleter); - status = - ContactUtil::ExportContactToContactsRecord(*contacts_record_ptr, contact); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&to_update, ContactUtil::ContactsDeleter); + status = ContactUtil::ExportContactToContactsRecord(*contacts_record_ptr, contact); if (status.IsError()) return status; err = contacts_db_update_record(*contacts_record_ptr); if (CONTACTS_ERROR_NONE != err) { if (CONTACTS_ERROR_INVALID_PARAMETER == err) { return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, - "Error during executing contacts_db_update_record().", + ErrorCode::NOT_FOUND_ERR, "Error during executing contacts_db_update_record().", ("Error during executing contacts_db_update_record(). Error: %d", err)); } if (CONTACTS_ERROR_DB == err) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Error during executing contacts_db_update_record().", + ErrorCode::UNKNOWN_ERR, "Error during executing contacts_db_update_record().", ("Error during executing contacts_db_update_record(). Error: %d", err)); } } @@ -197,11 +189,9 @@ PlatformResult AddressBookRemove(const JsonObject& args, JsonObject&) { int err = contacts_db_delete_record(_contacts_contact._uri, contact_id); if (CONTACTS_ERROR_NO_DATA == err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Remove failed: contact not found"); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Remove failed: contact not found"); } else if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contacts record delete error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record delete error"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -214,8 +204,7 @@ PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { if (status.IsError()) return status; const JsonArray& batch_args = FromJson(args, "batchArgs"); - long addressBookId = - common::stol(FromJson(args, "addressBookId")); + long addressBookId = common::stol(FromJson(args, "addressBookId")); addressBookId = addressBookId == -1 ? 0 : addressBookId; int length = static_cast(batch_args.size()); @@ -223,35 +212,31 @@ PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { int error_code = contacts_list_create(&contacts_list); if (CONTACTS_ERROR_NONE != error_code) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "list creation failed", - ("list creation failed, code: %d", error_code)); + ("list creation failed, code: %d", error_code)); } - ContactUtil::ContactsListHPtr contacts_list_ptr( - &contacts_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr contacts_list_ptr(&contacts_list, ContactUtil::ContactsListDeleter); for (auto& item : batch_args) { contacts_record_h contacts_record = nullptr; int err = 0; err = contacts_record_create(_contacts_contact._uri, &contacts_record); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contacts record create error", - ("Contacts record create error, error code: %d", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record create error", + ("Contacts record create error, error code: %d", err)); } - ContactUtil::ContactsRecordHPtr x(&contacts_record, - ContactUtil::ContactsDeleter); - status = ContactUtil::ExportContactToContactsRecord( - contacts_record, JsonCast(item)); + ContactUtil::ContactsRecordHPtr x(&contacts_record, ContactUtil::ContactsDeleter); + status = + ContactUtil::ExportContactToContactsRecord(contacts_record, JsonCast(item)); if (status.IsError()) return status; - status = ContactUtil::SetIntInRecord( - contacts_record, _contacts_contact.address_book_id, addressBookId); + status = ContactUtil::SetIntInRecord(contacts_record, _contacts_contact.address_book_id, + addressBookId); if (status.IsError()) return status; error_code = contacts_list_add(*contacts_list_ptr, *(x.release())); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "error during add record to list", - ("error during add record to list, code: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "error during add record to list", + ("error during add record to list, code: %d", error_code)); } } @@ -264,9 +249,8 @@ PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { error_code = contacts_db_insert_records(*contacts_list_ptr, &ids, &count); if (CONTACTS_ERROR_NONE != error_code || nullptr == ids) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "inserting contacts to db fails", - ("inserting contacts to db fails, code: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "inserting contacts to db fails", + ("inserting contacts to db fails, code: %d", error_code)); } if (length != count) { @@ -276,15 +260,12 @@ PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { for (int i = 0; i < count; i++) { JsonObject out_object; contacts_record_h contact_record = nullptr; - error_code = - contacts_db_get_record(_contacts_contact._uri, ids[i], &contact_record); + error_code = contacts_db_get_record(_contacts_contact._uri, ids[i], &contact_record); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contacts record get error", - ("Contacts record get error, error code: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record get error", + ("Contacts record get error, error code: %d", error_code)); } - status = ContactUtil::ImportContactFromContactsRecord( - contact_record, &out_object); + status = ContactUtil::ImportContactFromContactsRecord(contact_record, &out_object); if (status.IsError()) return status; out.push_back(JsonValue{out_object}); @@ -305,10 +286,9 @@ PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out) { err = contacts_list_create(&contacts_list); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "list creation failed", - ("list creation failed, code: %d", err)); + ("list creation failed, code: %d", err)); } - ContactUtil::ContactsListHPtr contacts_list_ptr( - &contacts_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr contacts_list_ptr(&contacts_list, ContactUtil::ContactsListDeleter); for (auto& item : batch_args) { const JsonObject& contact = JsonCast(item); long contactId = common::stol(FromJson(contact, "id")); @@ -319,14 +299,11 @@ PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out) { contacts_record_h to_update = nullptr; err = contacts_db_get_record(_contacts_contact._uri, contactId, &to_update); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Problem with getting contact", - ("Problem with getting contact. Error: %d", err)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Problem with getting contact", + ("Problem with getting contact. Error: %d", err)); } - ContactUtil::ContactsRecordHPtr x(&to_update, - ContactUtil::ContactsDeleter); - status = ContactUtil::ExportContactToContactsRecord( - to_update, JsonCast(item)); + ContactUtil::ContactsRecordHPtr x(&to_update, ContactUtil::ContactsDeleter); + status = ContactUtil::ExportContactToContactsRecord(to_update, JsonCast(item)); if (status.IsError()) return status; JsonObject out_object; status = ContactUtil::UpdateAdditionalInformation(*x, &out_object); @@ -335,26 +312,21 @@ PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out) { err = contacts_list_add(*contacts_list_ptr, *(x.release())); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "error during add record to list", - ("error during add record to list, code: %d", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "error during add record to list", + ("error during add record to list, code: %d", err)); } } err = contacts_db_update_records(*contacts_list_ptr); if (CONTACTS_ERROR_NONE != err) { if (CONTACTS_ERROR_INVALID_PARAMETER == err) { return LogAndCreateResult( - ErrorCode::NOT_FOUND_ERR, - "Error during executing contacts_db_update_record().", - ("Error during executing contacts_db_update_record(). Error: %d", - err)); + ErrorCode::NOT_FOUND_ERR, "Error during executing contacts_db_update_record().", + ("Error during executing contacts_db_update_record(). Error: %d", err)); } if (CONTACTS_ERROR_DB == err) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Error during executing contacts_db_update_record().", - ("Error during executing contacts_db_update_record(). Error: %d", - err)); + ErrorCode::UNKNOWN_ERR, "Error during executing contacts_db_update_record().", + ("Error during executing contacts_db_update_record(). Error: %d", err)); } } return PlatformResult(ErrorCode::NO_ERROR); @@ -367,7 +339,7 @@ PlatformResult AddressBookRemoveBatch(const JsonObject& args) { if (status.IsError()) return status; const JsonArray& batch_args = FromJson(args, "batchArgs"); int length = static_cast(batch_args.size()); - int ids[length], i=0; + int ids[length], i = 0; for (auto& item : batch_args) { long contact_id = common::stol(item.get()); if (contact_id < 0) { @@ -378,11 +350,9 @@ PlatformResult AddressBookRemoveBatch(const JsonObject& args) { } int err = contacts_db_delete_records(_contacts_contact._uri, ids, length); if (CONTACTS_ERROR_NO_DATA == err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Remove failed: contact not found"); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Remove failed: contact not found"); } else if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contacts record delete error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record delete error"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -423,28 +393,23 @@ PlatformResult AddressBookAddGroup(const JsonObject& args, JsonObject& out) { const JsonObject& group = FromJson(args, "group"); if (!IsNull(group, "id") || !IsNull(group, "addressBookId")) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Group object is previously added"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Group object is previously added"); } contacts_record_h contacts_record = nullptr; int err = contacts_record_create(_contacts_group._uri, &contacts_record); - status = ContactUtil::ErrorChecker( - err, "Error during executing contacts_record_create()"); + status = ContactUtil::ErrorChecker(err, "Error during executing contacts_record_create()"); if (status.IsError()) return status; - ContactUtil::ContactsRecordHPtr record(&contacts_record, - ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr record(&contacts_record, ContactUtil::ContactsDeleter); - long addressbook_id = - common::stol(FromJson(args, "addressBookId")); + long addressbook_id = common::stol(FromJson(args, "addressBookId")); addressbook_id = (IsUnified(addressbook_id)) ? 0 : addressbook_id; - status = ContactUtil::SetIntInRecord( - contacts_record, _contacts_group.address_book_id, addressbook_id); + status = + ContactUtil::SetIntInRecord(contacts_record, _contacts_group.address_book_id, addressbook_id); if (status.IsError()) return status; - status = - ContactUtil::ExportContactGroupToContactsRecord(contacts_record, group); + status = ContactUtil::ExportContactGroupToContactsRecord(contacts_record, group); if (status.IsError()) return status; int groupId = 0; @@ -475,23 +440,20 @@ PlatformResult AddressBookGetGroup(const JsonObject& args, JsonObject& out) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Group not exist"); } - ContactUtil::ContactsRecordHPtr record(&contacts_record, - ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr record(&contacts_record, ContactUtil::ContactsDeleter); long addressbook_id = common::stol(FromJson(args, "addressBookId")); if (IsUnified(addressbook_id)) { int address_book_id = 0; - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_group.address_book_id, &address_book_id); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_group.address_book_id, + &address_book_id); if (status.IsError()) return status; if (address_book_id != addressbook_id) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "No group in this address book."); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "No group in this address book."); } } - status = - ContactUtil::ImportContactGroupFromContactsRecord(contacts_record, &out); + status = ContactUtil::ImportContactGroupFromContactsRecord(contacts_record, &out); if (status.IsError()) return status; return PlatformResult(ErrorCode::NO_ERROR); @@ -505,21 +467,17 @@ PlatformResult AddressBookUpdateGroup(const JsonObject& args, JsonObject&) { const JsonObject& group = FromJson(args, "group"); if (IsNull(group, "id") || IsNull(group, "addressBookId")) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Group object is not added"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Group object is not added"); } - long addressbook_id = - common::stol(FromJson(args, "addressBookId")); - long group_addressbook_id = - common::stol(FromJson(group, "addressBookId")); + long addressbook_id = common::stol(FromJson(args, "addressBookId")); + long group_addressbook_id = common::stol(FromJson(group, "addressBookId")); if (IsUnified(addressbook_id) && (addressbook_id != group_addressbook_id)) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Wrong address book"); } if (FromJson(group, "readOnly")) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Group is readonly - cancel update"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Group is readonly - cancel update"); } long group_id = common::stol(FromJson(group, "id")); @@ -528,26 +486,21 @@ PlatformResult AddressBookUpdateGroup(const JsonObject& args, JsonObject&) { } contacts_record_h contacts_record = nullptr; - int err = - contacts_db_get_record(_contacts_group._uri, group_id, &contacts_record); + int err = contacts_db_get_record(_contacts_group._uri, group_id, &contacts_record); if (CONTACTS_ERROR_NONE != err || nullptr == contacts_record) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Group not exist"); } - status = ContactUtil::ErrorChecker( - err, "Error during executing contacts_db_get_record()"); + status = ContactUtil::ErrorChecker(err, "Error during executing contacts_db_get_record()"); if (status.IsError()) return status; - ContactUtil::ContactsRecordHPtr record(&contacts_record, - ContactUtil::ContactsDeleter); - status = - ContactUtil::ExportContactGroupToContactsRecord(contacts_record, group); + ContactUtil::ContactsRecordHPtr record(&contacts_record, ContactUtil::ContactsDeleter); + status = ContactUtil::ExportContactGroupToContactsRecord(contacts_record, group); if (status.IsError()) return status; err = contacts_db_update_record(contacts_record); if (CONTACTS_ERROR_INVALID_PARAMETER == err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Problem during db_update_record"); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Problem during db_update_record"); } status = ContactUtil::ErrorChecker(err, "Problem during db_update_record"); if (status.IsError()) return status; @@ -575,21 +528,19 @@ PlatformResult AddressBookRemoveGroup(const JsonObject& args, JsonObject&) { } int group_addressbook_id = 0; - status = ContactUtil::GetIntFromRecord(contacts_record, - _contacts_group.address_book_id, + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_group.address_book_id, &group_addressbook_id); if (status.IsError()) return status; if (group_addressbook_id != addressbook_id) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Contact is not a member of this address book"); + "Contact is not a member of this address book"); } } err = contacts_db_delete_record(_contacts_group._uri, id); if (CONTACTS_ERROR_INVALID_PARAMETER == err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Problem during db_delete_record"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Problem during db_delete_record"); } status = ContactUtil::ErrorChecker(err, "Problem during db_delete_record"); if (status.IsError()) return status; @@ -615,43 +566,35 @@ PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out) { contacts_filter_h filter = nullptr; err = contacts_query_create(_contacts_group._uri, &query); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_query_create "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_query_create "); if (status.IsError()) return status; err = contacts_filter_create(_contacts_group._uri, &filter); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_create "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_create "); if (status.IsError()) return status; - err = contacts_filter_add_int(filter, _contacts_group.address_book_id, - CONTACTS_MATCH_EQUAL, addressbook_id); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_add_int "); + err = contacts_filter_add_int(filter, _contacts_group.address_book_id, CONTACTS_MATCH_EQUAL, + addressbook_id); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_add_int "); if (status.IsError()) return status; err = contacts_query_set_filter(query, filter); - status = ContactUtil::ErrorChecker( - err, "Fail to get contacts_query_set_filter "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_query_set_filter "); if (status.IsError()) return status; err = contacts_db_get_records_with_query(query, 0, 0, &groups_list); - status = ContactUtil::ErrorChecker( - err, "Fail to get contacts_db_get_records_with_query "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_db_get_records_with_query "); if (status.IsError()) return status; // deleter to release the memory in case of an error - ContactUtil::ContactsListHPtr group_list_ptr( - &groups_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr group_list_ptr(&groups_list, ContactUtil::ContactsListDeleter); err = contacts_filter_destroy(filter); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_destroy "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_filter_destroy "); if (status.IsError()) return status; err = contacts_query_destroy(query); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_query_destroy "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_query_destroy "); if (status.IsError()) return status; // release the ownership, pass it back to the outer scope @@ -659,13 +602,11 @@ PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out) { } // groups_list has been initialized, take the ownership - ContactUtil::ContactsListHPtr group_list_ptr( - &groups_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr group_list_ptr(&groups_list, ContactUtil::ContactsListDeleter); int record_count = 0; err = contacts_list_get_count(groups_list, &record_count); - status = - ContactUtil::ErrorChecker(err, "Fail to get contacts_list_get_count "); + status = ContactUtil::ErrorChecker(err, "Fail to get contacts_list_get_count "); if (status.IsError()) return status; contacts_list_first(groups_list); @@ -678,8 +619,8 @@ PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out) { } JsonValue group{JsonObject{}}; - status = ContactUtil::ImportContactGroupFromContactsRecord( - contacts_record, &group.get()); + status = ContactUtil::ImportContactGroupFromContactsRecord(contacts_record, + &group.get()); if (status.IsError()) return status; out.push_back(group); @@ -725,16 +666,16 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { for (int version = instance->current_state(); version < current_version; ++version) { int latest_version = 0; - error_code = contacts_db_get_changes_by_version( - _contacts_contact_updated_info._uri, kUnifiedAddressBookId, version, - &contacts_list, &latest_version); + error_code = contacts_db_get_changes_by_version(_contacts_contact_updated_info._uri, + kUnifiedAddressBookId, version, &contacts_list, + &latest_version); if (CONTACTS_ERROR_NONE != error_code) { LoggerE("cannot get changes by version, code: %d", error_code); continue; } - ContactUtil::ContactsListHPtr contacts_list_ptr( - &contacts_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr contacts_list_ptr(&contacts_list, + ContactUtil::ContactsListDeleter); int count = 0; error_code = contacts_list_get_count(contacts_list, &count); @@ -752,24 +693,22 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { JsonValue result{JsonObject{}}; JsonObject& result_obj = result.get(); - result_obj.insert( - std::make_pair(std::string("listenerId"), - picojson::value(std::string(kContactListenerId)))); + result_obj.insert(std::make_pair(std::string("listenerId"), + picojson::value(std::string(kContactListenerId)))); JsonArray& added = - result_obj.insert(std::make_pair(std::string("added"), - picojson::value(JsonArray{}))).first->second.get(); + result_obj.insert(std::make_pair(std::string("added"), picojson::value(JsonArray{}))) + .first->second.get(); JsonArray& updated = - result_obj.insert(std::make_pair(std::string("updated"), - picojson::value(JsonArray{}))).first->second.get(); + result_obj.insert(std::make_pair(std::string("updated"), picojson::value(JsonArray{}))) + .first->second.get(); JsonArray& removed = - result_obj.insert(std::make_pair(std::string("removed"), - picojson::value(JsonArray{}))).first->second.get(); + result_obj.insert(std::make_pair(std::string("removed"), picojson::value(JsonArray{}))) + .first->second.get(); for (int i = 0; i < count; i++) { contacts_record_h contact_updated_record = nullptr; - error_code = contacts_list_get_current_record_p(contacts_list, - &contact_updated_record); + error_code = contacts_list_get_current_record_p(contacts_list, &contact_updated_record); if (CONTACTS_ERROR_NONE != error_code) { LoggerW("fail to get contact from list, code: %d", error_code); break; @@ -780,50 +719,44 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { int changed_type = 0; PlatformResult status = ContactUtil::GetIntFromRecord( - contact_updated_record, _contacts_contact_updated_info.contact_id, - &changed_id); + contact_updated_record, _contacts_contact_updated_info.contact_id, &changed_id); if (status.IsError()) { LoggerE("Fail to get int from record: %s", status.message().c_str()); break; } status = ContactUtil::GetIntFromRecord( - contact_updated_record, - _contacts_contact_updated_info.address_book_id, &changed_ab_id); + contact_updated_record, _contacts_contact_updated_info.address_book_id, &changed_ab_id); if (status.IsError()) { LoggerE("Fail to get int from record: %s", status.message().c_str()); break; } - status = ContactUtil::GetIntFromRecord( - contact_updated_record, _contacts_contact_updated_info.type, - &changed_type); + status = ContactUtil::GetIntFromRecord(contact_updated_record, + _contacts_contact_updated_info.type, &changed_type); if (status.IsError()) { LoggerE("Fail to get int from record: %s", status.message().c_str()); break; } - if (CONTACTS_CHANGE_INSERTED == changed_type || - CONTACTS_CHANGE_UPDATED == changed_type) { + if (CONTACTS_CHANGE_INSERTED == changed_type || CONTACTS_CHANGE_UPDATED == changed_type) { contacts_record_h contacts_record = nullptr; - error_code = contacts_db_get_record(_contacts_contact._uri, changed_id, - &contacts_record); + error_code = contacts_db_get_record(_contacts_contact._uri, changed_id, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { LoggerW("fail to get contact from record"); break; } - ContactUtil::ContactsRecordHPtr contact_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr contact_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); JsonValue contact{JsonObject{}}; - status = ContactUtil::ImportContactFromContactsRecord( - contacts_record, &contact.get()); + status = ContactUtil::ImportContactFromContactsRecord(contacts_record, + &contact.get()); if (status.IsError()) { - LoggerE("Fail to get contact from record: %s", - status.message().c_str()); + LoggerE("Fail to get contact from record: %s", status.message().c_str()); break; } @@ -838,11 +771,9 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { JsonObject& removed_data_obj = removed_data.get(); removed_data_obj.insert( - std::make_pair(std::string("id"), - picojson::value(std::to_string(changed_id)))); - removed_data_obj.insert( - std::make_pair(std::string("addressBookId"), - picojson::value(std::to_string(changed_ab_id)))); + std::make_pair(std::string("id"), picojson::value(std::to_string(changed_id)))); + removed_data_obj.insert(std::make_pair(std::string("addressBookId"), + picojson::value(std::to_string(changed_ab_id)))); removed.push_back(std::move(removed_data)); } } @@ -854,7 +785,8 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { } } -PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonObject&, JsonObject& out) { +PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonObject&, + JsonObject& out) { LoggerD("Enter"); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -869,14 +801,13 @@ PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonOb instance.set_current_state(current_state); - error_code = contacts_db_add_changed_cb(_contacts_contact._uri, - AddressBookListenerCallback, &instance); + error_code = + contacts_db_add_changed_cb(_contacts_contact._uri, AddressBookListenerCallback, &instance); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error while registering listener to contacts db", - ("Error while registering listener to contacts db, code: %d", - error_code)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while registering listener to contacts db", + ("Error while registering listener to contacts db, code: %d", error_code)); } instance.set_is_listening(true); @@ -889,12 +820,11 @@ PlatformResult AddressBookStopListening(ContactInstance& instance) { PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; - int error_code = contacts_db_remove_changed_cb( - _contacts_contact._uri, AddressBookListenerCallback, &instance); + int error_code = + contacts_db_remove_changed_cb(_contacts_contact._uri, AddressBookListenerCallback, &instance); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error while removing listener"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while removing listener"); } instance.set_is_listening(false); diff --git a/src/contact/addressbook.h b/src/contact/addressbook.h index 5836357..1dd721a 100644 --- a/src/contact/addressbook.h +++ b/src/contact/addressbook.h @@ -18,9 +18,9 @@ #define CONTACT_ADDRESSBOOK_H_ #include "common/picojson.h" +#include "common/platform_result.h" #include "contact/contact_util.h" #include "functional" -#include "common/platform_result.h" namespace extension { namespace contact { @@ -29,36 +29,25 @@ class ContactInstance; namespace AddressBook { -typedef std::function - NativeFunction; +typedef std::function NativeFunction; common::PlatformResult AddressBookGet(const JsonObject& args, JsonObject& out); common::PlatformResult AddressBookAdd(const JsonObject& args, JsonObject& out); -common::PlatformResult AddressBookUpdate(const JsonObject& args, - JsonObject& out); +common::PlatformResult AddressBookUpdate(const JsonObject& args, JsonObject& out); common::PlatformResult AddressBookRemove(const JsonObject& args, JsonObject&); -common::PlatformResult AddressBookFind(const JsonObject& args, - JsonArray& array); -common::PlatformResult AddressBookFindByUsageCount(const JsonObject& args, - JsonArray& array); -common::PlatformResult AddressBookAddGroup(const JsonObject& args, - JsonObject& out); -common::PlatformResult AddressBookGetGroup(const JsonObject& args, - JsonObject& out); -common::PlatformResult AddressBookUpdateGroup(const JsonObject& args, - JsonObject&); -common::PlatformResult AddressBookRemoveGroup(const JsonObject& args, - JsonObject&); -common::PlatformResult AddressBookGetGroups(const JsonObject& args, - JsonArray& out); +common::PlatformResult AddressBookFind(const JsonObject& args, JsonArray& array); +common::PlatformResult AddressBookFindByUsageCount(const JsonObject& args, JsonArray& array); +common::PlatformResult AddressBookAddGroup(const JsonObject& args, JsonObject& out); +common::PlatformResult AddressBookGetGroup(const JsonObject& args, JsonObject& out); +common::PlatformResult AddressBookUpdateGroup(const JsonObject& args, JsonObject&); +common::PlatformResult AddressBookRemoveGroup(const JsonObject& args, JsonObject&); +common::PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out); common::PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonObject& args, JsonObject& out); common::PlatformResult AddressBookStopListening(ContactInstance& instance); -common::PlatformResult AddressBookAddBatch(const JsonObject& args, - JsonArray& out); -common::PlatformResult AddressBookUpdateBatch(const JsonObject& args, - JsonArray& out); +common::PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out); +common::PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out); common::PlatformResult AddressBookRemoveBatch(const JsonObject& args); } // AddressBook } // contact diff --git a/src/contact/contact_extension.cc b/src/contact/contact_extension.cc old mode 100755 new mode 100644 index b7bad1e..e2e660a --- a/src/contact/contact_extension.cc +++ b/src/contact/contact_extension.cc @@ -19,25 +19,34 @@ extern const char kSource_contact_api[]; -common::Extension* CreateExtension() { return new ContactExtension; } +common::Extension* CreateExtension() { + return new ContactExtension; +} ContactExtension::ContactExtension() { SetExtensionName("tizen.contact"); SetJavaScriptAPI(kSource_contact_api); - const char* entry_points[] = { - "tizen.ContactRef", "tizen.ContactName", - "tizen.ContactOrganization", "tizen.ContactWebSite", - "tizen.ContactAnniversary", "tizen.ContactAddress", - "tizen.ContactPhoneNumber", "tizen.ContactEmailAddress", - "tizen.ContactGroup", "tizen.ContactRelationship", - "tizen.ContactInstantMessenger", "tizen.Contact", - "tizen.AddressBook", "tizen.ContactExtension", - NULL}; + const char* entry_points[] = {"tizen.ContactRef", + "tizen.ContactName", + "tizen.ContactOrganization", + "tizen.ContactWebSite", + "tizen.ContactAnniversary", + "tizen.ContactAddress", + "tizen.ContactPhoneNumber", + "tizen.ContactEmailAddress", + "tizen.ContactGroup", + "tizen.ContactRelationship", + "tizen.ContactInstantMessenger", + "tizen.Contact", + "tizen.AddressBook", + "tizen.ContactExtension", + NULL}; SetExtraJSEntryPoints(entry_points); } -ContactExtension::~ContactExtension() {} +ContactExtension::~ContactExtension() { +} common::Instance* ContactExtension::CreateInstance() { return new extension::contact::ContactInstance(); diff --git a/src/contact/contact_instance.cc b/src/contact/contact_instance.cc old mode 100755 new mode 100644 index 51fec47..252bef0 --- a/src/contact/contact_instance.cc +++ b/src/contact/contact_instance.cc @@ -17,9 +17,9 @@ #include "contact/contact_instance.h" #include "common/converter.h" -#include "common/task-queue.h" #include "common/logger.h" #include "common/platform_exception.h" +#include "common/task-queue.h" #include "common/tools.h" #include "contact/addressbook.h" @@ -36,24 +36,18 @@ const std::string kPrivilegeContactWrite = "http://tizen.org/privilege/contact.w using namespace common; -ContactInstance::ContactInstance() - : current_state_(0), - is_listening_(false) { +ContactInstance::ContactInstance() : current_state_(0), is_listening_(false) { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&ContactInstance::x, this, _1, _2)); -#define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&ContactInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&ContactInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&ContactInstance::x, this, _1, _2)); // Contact Manager - REGISTER_ASYNC("ContactManager_getAddressBooks", - ContactManagerGetAddressBooks); + REGISTER_ASYNC("ContactManager_getAddressBooks", ContactManagerGetAddressBooks); REGISTER_SYNC("ContactManager_getAddressBook", ContactManagerGetAddressBook); REGISTER_SYNC("ContactManager_addAddressBook", ContactManagerAddAddressBook); - REGISTER_SYNC("ContactManager_removeAddressBook", - ContactManagerRemoveAddressBook); + REGISTER_SYNC("ContactManager_removeAddressBook", ContactManagerRemoveAddressBook); REGISTER_SYNC("ContactManager_get", ContactManagerGet); REGISTER_SYNC("ContactManager_update", ContactManagerUpdate); REGISTER_ASYNC("ContactManager_updateBatch", ContactManagerUpdateBatch); @@ -61,8 +55,7 @@ ContactInstance::ContactInstance() REGISTER_ASYNC("ContactManager_removeBatch", ContactManagerRemoveBatch); REGISTER_ASYNC("ContactManager_find", ContactManagerFind); REGISTER_ASYNC("ContactManager_findByUsageCount", ContactManagerFindByUsageCount); - REGISTER_SYNC("ContactManager_importFromVCard", - ContactManagerImportFromVCard); + REGISTER_SYNC("ContactManager_importFromVCard", ContactManagerImportFromVCard); REGISTER_SYNC("ContactManager_startListening", ContactManagerStartListening); REGISTER_SYNC("ContactManager_stopListening", ContactManagerStopListening); @@ -103,8 +96,8 @@ ContactInstance::~ContactInstance() { void ContactInstance::AddressBookGet(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookGet( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookGet(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else @@ -114,16 +107,15 @@ void ContactInstance::AddressBookGet(const JsonValue& args, JsonObject& out) { void ContactInstance::AddressBookAdd(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookAdd( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookAdd(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookAddBatch(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookAddBatch(const JsonValue& args, JsonObject& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); @@ -131,16 +123,15 @@ void ContactInstance::AddressBookAddBatch(const JsonValue& args, auto get = [=](const std::shared_ptr& response) -> void { JsonValue result = JsonValue(JsonArray()); - PlatformResult status = AddressBook::AddressBookAddBatch( - common::JsonCast(args), result.get()); + PlatformResult status = AddressBook::AddressBookAddBatch(common::JsonCast(args), + result.get()); if (status.IsSuccess()) ReportSuccess(result, response->get()); else LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -148,20 +139,17 @@ void ContactInstance::AddressBookAddBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, JsonObject& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - PlatformResult status = AddressBook::AddressBookRemoveBatch( - common::JsonCast(args)); + PlatformResult status = AddressBook::AddressBookRemoveBatch(common::JsonCast(args)); if (status.IsSuccess()) ReportSuccess(response->get()); @@ -169,8 +157,7 @@ void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -178,12 +165,10 @@ void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, JsonObject& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); @@ -191,16 +176,15 @@ void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, auto get = [=](const std::shared_ptr& response) -> void { JsonValue result = JsonValue(JsonArray()); - PlatformResult status = AddressBook::AddressBookUpdateBatch( - common::JsonCast(args), result.get()); + PlatformResult status = AddressBook::AddressBookUpdateBatch(common::JsonCast(args), + result.get()); if (status.IsSuccess()) ReportSuccess(result, response->get()); else LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -208,28 +192,25 @@ void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::AddressBookUpdate(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookUpdate(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookUpdate( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookUpdate(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookRemove(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookRemove(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookRemove( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookRemove(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(out); else @@ -243,16 +224,15 @@ void ContactInstance::AddressBookFind(const JsonValue& args, JsonObject& out) { auto get = [=](const std::shared_ptr& response) -> void { JsonValue result = JsonValue(JsonArray()); - PlatformResult status = AddressBook::AddressBookFind( - JsonCast(args), result.get()); + PlatformResult status = + AddressBook::AddressBookFind(JsonCast(args), result.get()); if (status.IsSuccess()) ReportSuccess(result, response->get()); else LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -260,72 +240,65 @@ void ContactInstance::AddressBookFind(const JsonValue& args, JsonObject& out) { auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::AddressBookAddGroup(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookAddGroup(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookAddGroup( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookAddGroup(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookGetGroup(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookGetGroup(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookGetGroup( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookGetGroup(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookUpdateGroup(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookUpdateGroup(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookUpdateGroup( - common::JsonCast(args), val.get()); + PlatformResult status = AddressBook::AddressBookUpdateGroup(common::JsonCast(args), + val.get()); if (status.IsSuccess()) ReportSuccess(out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookRemoveGroup(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookRemoveGroup(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = AddressBook::AddressBookRemoveGroup( - common::JsonCast(args), val.get()); + PlatformResult status = AddressBook::AddressBookRemoveGroup(common::JsonCast(args), + val.get()); if (status.IsSuccess()) ReportSuccess(out); else LogAndReportError(status, &out); } -void ContactInstance::AddressBookGetGroups(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookGetGroups(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonArray{}}; - PlatformResult status = AddressBook::AddressBookGetGroups( - common::JsonCast(args), val.get()); + PlatformResult status = + AddressBook::AddressBookGetGroups(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); @@ -341,8 +314,7 @@ void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -350,12 +322,10 @@ void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::ContactManagerGetAddressBook(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerGetAddressBook(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerGetAddressBook( @@ -366,8 +336,7 @@ void ContactInstance::ContactManagerGetAddressBook(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::ContactManagerAddAddressBook(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerAddAddressBook(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerAddAddressBook( @@ -378,8 +347,7 @@ void ContactInstance::ContactManagerAddAddressBook(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::ContactManagerRemoveAddressBook(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerRemoveAddressBook(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerRemoveAddressBook( @@ -390,8 +358,7 @@ void ContactInstance::ContactManagerRemoveAddressBook(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::AddressBookStartListening(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookStartListening(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookStartListening( @@ -402,8 +369,7 @@ void ContactInstance::AddressBookStartListening(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::AddressBookStopListening(const JsonValue& args, - JsonObject& out) { +void ContactInstance::AddressBookStopListening(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookStopListening(*this); @@ -413,40 +379,37 @@ void ContactInstance::AddressBookStopListening(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::ContactManagerGet(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerGet(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = ContactManager::ContactManagerGet( - common::JsonCast(args), val.get()); + PlatformResult status = + ContactManager::ContactManagerGet(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else LogAndReportError(status, &out); } -void ContactInstance::ContactManagerUpdate(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerUpdate(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = ContactManager::ContactManagerUpdate( - common::JsonCast(args), val.get()); + PlatformResult status = ContactManager::ContactManagerUpdate(common::JsonCast(args), + val.get()); if (status.IsSuccess()) ReportSuccess(out); else LogAndReportError(status, &out); } -void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, JsonObject& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - PlatformResult status = ContactManager::ContactManagerUpdateBatch( - common::JsonCast(args)); + PlatformResult status = + ContactManager::ContactManagerUpdateBatch(common::JsonCast(args)); if (status.IsSuccess()) ReportSuccess(response->get()); @@ -454,8 +417,7 @@ void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -463,32 +425,29 @@ void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::ContactManagerRemove(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerRemove(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = ContactManager::ContactManagerRemove( - common::JsonCast(args), val.get()); + PlatformResult status = ContactManager::ContactManagerRemove(common::JsonCast(args), + val.get()); if (status.IsSuccess()) ReportSuccess(out); else LogAndReportError(status, &out); } -void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, JsonObject& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - PlatformResult status = ContactManager::ContactManagerRemoveBatch( - common::JsonCast(args)); + PlatformResult status = + ContactManager::ContactManagerRemoveBatch(common::JsonCast(args)); if (status.IsSuccess()) ReportSuccess(response->get()); @@ -496,8 +455,7 @@ void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, LogAndReportError(status, &response->get()); }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -505,20 +463,18 @@ void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::ContactManagerFind(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerFind(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [this, args](const std::shared_ptr& response) -> void { JsonValue result = JsonValue(JsonArray()); - PlatformResult status = ContactManager::ContactManagerFind( - common::JsonCast(args), result.get()); + PlatformResult status = ContactManager::ContactManagerFind(common::JsonCast(args), + result.get()); if (status.IsSuccess()) { ReportSuccess(result, response->get()); } else { @@ -526,8 +482,7 @@ void ContactInstance::ContactManagerFind(const JsonValue& args, } }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -535,8 +490,7 @@ void ContactInstance::ContactManagerFind(const JsonValue& args, auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, JsonObject& out) { @@ -556,8 +510,7 @@ void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, Json } }; - auto get_response = - [this, callback_id](const std::shared_ptr& response) { + auto get_response = [this, callback_id](const std::shared_ptr& response) { JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -565,12 +518,10 @@ void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, Json auto data = std::shared_ptr(new JsonValue(JsonObject())); - TaskQueue::GetInstance().Queue( - get, get_response, data); + TaskQueue::GetInstance().Queue(get, get_response, data); } -void ContactInstance::ContactManagerImportFromVCard(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerImportFromVCard(const JsonValue& args, JsonObject& out) { JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerImportFromVCard( common::JsonCast(args), val.get()); @@ -580,8 +531,7 @@ void ContactInstance::ContactManagerImportFromVCard(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::ContactManagerStartListening(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerStartListening(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerStartListening( @@ -592,8 +542,7 @@ void ContactInstance::ContactManagerStartListening(const JsonValue& args, LogAndReportError(status, &out); } -void ContactInstance::ContactManagerStopListening(const JsonValue& args, - JsonObject& out) { +void ContactInstance::ContactManagerStopListening(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerStopListening( @@ -607,8 +556,8 @@ void ContactInstance::ContactManagerStopListening(const JsonValue& args, void ContactInstance::PersonLink(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = Person::PersonLink(common::JsonCast(args), - val.get()); + PlatformResult status = + Person::PersonLink(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(out); else @@ -618,8 +567,8 @@ void ContactInstance::PersonLink(const JsonValue& args, JsonObject& out) { void ContactInstance::PersonUnlink(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; - PlatformResult status = Person::PersonUnlink( - common::JsonCast(args), val.get()); + PlatformResult status = + Person::PersonUnlink(common::JsonCast(args), val.get()); if (status.IsSuccess()) ReportSuccess(val, out); else @@ -629,8 +578,8 @@ void ContactInstance::PersonUnlink(const JsonValue& args, JsonObject& out) { void ContactInstance::PersonGetUsageCount(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; - PlatformResult status = Person::GetUsageCount( - common::JsonCast(args), val.get()); + PlatformResult status = + Person::GetUsageCount(common::JsonCast(args), val.get()); if (status.IsSuccess()) { ReportSuccess(val, out); } else { @@ -640,8 +589,7 @@ void ContactInstance::PersonGetUsageCount(const JsonValue& args, JsonObject& out void ContactInstance::PersonResetUsageCount(const JsonValue& args, JsonObject& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); - PlatformResult status = Person::PersonResetUsageCount( - common::JsonCast(args)); + PlatformResult status = Person::PersonResetUsageCount(common::JsonCast(args)); if (status.IsSuccess()) { ReportSuccess(out); } else { diff --git a/src/contact/contact_instance.h b/src/contact/contact_instance.h old mode 100755 new mode 100644 index b9a0125..7c91fee --- a/src/contact/contact_instance.h +++ b/src/contact/contact_instance.h @@ -30,9 +30,15 @@ class ContactInstance : public common::ParsedInstance { ContactInstance(); virtual ~ContactInstance(); - int current_state() const { return current_state_; } - void set_current_state(int state) { current_state_ = state; } - void set_is_listening(bool listening) { is_listening_ = listening; } + int current_state() const { + return current_state_; + } + void set_current_state(int state) { + current_state_ = state; + } + void set_is_listening(bool listening) { + is_listening_ = listening; + } private: void AddressBookGet(const JsonValue& args, JsonObject& out); diff --git a/src/contact/contact_manager.cc b/src/contact/contact_manager.cc old mode 100755 new mode 100644 index aeab4f2..e6c519a --- a/src/contact/contact_manager.cc +++ b/src/contact/contact_manager.cc @@ -27,8 +27,8 @@ #include #include #include "contact/contact_instance.h" -#include "contact/person.h" #include "contact/contact_search_engine.h" +#include "contact/person.h" namespace extension { namespace contact { @@ -41,44 +41,39 @@ const char* kTokenDelimiter = " ,:"; using namespace common; -PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, - JsonArray& out) { +PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, JsonArray& out) { LoggerD("Enter"); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; contacts_list_h address_book_list = nullptr; - int error_code = contacts_db_get_all_records(_contacts_address_book._uri, 0, - 0, &address_book_list); + int error_code = + contacts_db_get_all_records(_contacts_address_book._uri, 0, 0, &address_book_list); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Fail to get address book list", - ("Fail to get address book list, error: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to get address book list", + ("Fail to get address book list, error: %d", error_code)); } - ContactUtil::ContactsListHPtr contacts_list_ptr( - &address_book_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr contacts_list_ptr(&address_book_list, + ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(*contacts_list_ptr, &record_count); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Fail to get address book list count", - ("Fail to get address book list count, error: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to get address book list count", + ("Fail to get address book list count, error: %d", error_code)); } error_code = contacts_list_first(*contacts_list_ptr); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Fail to get address book from list", - ("Fail to get address book from list, error: %d", error_code)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to get address book from list", + ("Fail to get address book from list, error: %d", error_code)); } for (int i = 0; i < record_count; i++) { contacts_record_h contacts_record = nullptr; - error_code = contacts_list_get_current_record_p(*contacts_list_ptr, - &contacts_record); + error_code = contacts_list_get_current_record_p(*contacts_list_ptr, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { LoggerW("Fail to get address book record"); @@ -89,20 +84,17 @@ PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, int account_id = 0; int mode = 0; char* name = nullptr; - status = ContactUtil::GetIntFromRecord(contacts_record, - _contacts_address_book.id, &id); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_address_book.id, &id); if (status.IsError()) return status; - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_address_book.account_id, &account_id); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_address_book.account_id, + &account_id); if (status.IsError()) return status; - status = ContactUtil::GetIntFromRecord(contacts_record, - _contacts_address_book.mode, &mode); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_address_book.mode, &mode); if (status.IsError()) return status; - status = ContactUtil::GetStrFromRecord(contacts_record, - _contacts_address_book.name, &name); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_address_book.name, &name); if (status.IsError()) return status; JsonValue single = JsonValue(JsonObject()); @@ -111,8 +103,7 @@ PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, single_obj["id"] = JsonValue(std::to_string(id)); single_obj["accountId"] = JsonValue(static_cast(account_id)); single_obj["name"] = JsonValue(name); - single_obj["readOnly"] = - JsonValue(CONTACTS_ADDRESS_BOOK_MODE_READONLY == mode); + single_obj["readOnly"] = JsonValue(CONTACTS_ADDRESS_BOOK_MODE_READONLY == mode); out.push_back(single); contacts_list_next(*contacts_list_ptr); @@ -121,47 +112,40 @@ PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ContactManagerGetAddressBook(const JsonObject& args, - JsonObject& out) { +PlatformResult ContactManagerGetAddressBook(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; - long address_book_id = - common::stol(FromJson(args, "addressBookId")); + long address_book_id = common::stol(FromJson(args, "addressBookId")); contacts_record_h contacts_record; int error_code = contacts_db_get_record(_contacts_address_book._uri, - static_cast(address_book_id), - &contacts_record); + static_cast(address_book_id), &contacts_record); if (CONTACTS_ERROR_NONE != error_code || nullptr == contacts_record) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Fail to get address book with given id", - ("Fail to get addressbook record, error code: %d", error_code)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Fail to get address book with given id", + ("Fail to get addressbook record, error code: %d", error_code)); } - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); int account_id; - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_address_book.account_id, &account_id); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_address_book.account_id, + &account_id); if (status.IsError()) return status; int mode; - status = ContactUtil::GetIntFromRecord(contacts_record, - _contacts_address_book.mode, &mode); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_address_book.mode, &mode); if (status.IsError()) return status; char* name; - status = ContactUtil::GetStrFromRecord(contacts_record, - _contacts_address_book.name, &name); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_address_book.name, &name); if (status.IsError()) return status; out["accountId"] = picojson::value(static_cast(account_id)); out["name"] = picojson::value(name); - out["readOnly"] = - picojson::value(CONTACTS_ADDRESS_BOOK_MODE_READONLY == mode); + out["readOnly"] = picojson::value(CONTACTS_ADDRESS_BOOK_MODE_READONLY == mode); return PlatformResult(ErrorCode::NO_ERROR); } @@ -171,15 +155,13 @@ PlatformResult ContactManagerGetInternal(int person_id, JsonObject* out) { LoggerD("Enter"); contacts_record_h contacts_record = nullptr; - int error_code = contacts_db_get_record(_contacts_person._uri, person_id, - &contacts_record); + int error_code = contacts_db_get_record(_contacts_person._uri, person_id, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Person not found", ("Person with id: %d, not found, error: %d", person_id, error_code)); } - PlatformResult status = - ContactUtil::ImportPersonFromContactsRecord(contacts_record, out); + PlatformResult status = ContactUtil::ImportPersonFromContactsRecord(contacts_record, out); if (status.IsError()) { if (CONTACTS_ERROR_NONE != contacts_record_destroy(contacts_record, true)) { @@ -196,8 +178,7 @@ PlatformResult ContactManagerGetInternal(int person_id, JsonObject* out) { } } -PlatformResult ContactManagerAddAddressBook(const JsonObject& args, - JsonObject& out) { +PlatformResult ContactManagerAddAddressBook(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -209,40 +190,35 @@ PlatformResult ContactManagerAddAddressBook(const JsonObject& args, } contacts_record_h contacts_record; - int ret = - contacts_record_create(_contacts_address_book._uri, &contacts_record); + int ret = contacts_record_create(_contacts_address_book._uri, &contacts_record); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create address book record", - ("Failed to create address book record, error code : %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create address book record", + ("Failed to create address book record, error code : %d", ret)); } - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); - status = ContactUtil::SetStrInRecord( - contacts_record, _contacts_address_book.name, - FromJson(addressBook, "name").c_str()); + status = ContactUtil::SetStrInRecord(contacts_record, _contacts_address_book.name, + FromJson(addressBook, "name").c_str()); if (status.IsError()) return status; contacts_address_book_mode_e mode = FromJson(addressBook, "readOnly") ? CONTACTS_ADDRESS_BOOK_MODE_READONLY : CONTACTS_ADDRESS_BOOK_MODE_NONE; - status = ContactUtil::SetIntInRecord( - contacts_record, _contacts_address_book.mode, static_cast(mode)); + status = ContactUtil::SetIntInRecord(contacts_record, _contacts_address_book.mode, + static_cast(mode)); if (status.IsError()) return status; double account_id = FromJson(addressBook, "accountId"); - status = ContactUtil::SetIntInRecord(contacts_record, - _contacts_address_book.account_id, + status = ContactUtil::SetIntInRecord(contacts_record, _contacts_address_book.account_id, static_cast(account_id)); if (status.IsError()) return status; int address_book_id; ret = contacts_db_insert_record(*contacts_record_ptr, &address_book_id); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to insert address book record", - ("Failed to insert address book record, error code: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to insert address book record", + ("Failed to insert address book record, error code: %d", ret)); } out["id"] = picojson::value(std::to_string(address_book_id)); @@ -250,31 +226,26 @@ PlatformResult ContactManagerAddAddressBook(const JsonObject& args, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, - JsonObject& out) { +PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; - long address_book_id = - common::stol(FromJson(args, "addressBookId")); + long address_book_id = common::stol(FromJson(args, "addressBookId")); contacts_record_h contacts_record; int error_code = contacts_db_get_record(_contacts_address_book._uri, - static_cast(address_book_id), - &contacts_record); + static_cast(address_book_id), &contacts_record); if (CONTACTS_ERROR_NONE != error_code || nullptr == contacts_record) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Fail to get address book with given id", - ("Fail to get addressbook record, error code: %d", error_code)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Fail to get address book with given id", + ("Fail to get addressbook record, error code: %d", error_code)); } - int ret = contacts_db_delete_record(_contacts_address_book._uri, - static_cast(address_book_id)); + int ret = + contacts_db_delete_record(_contacts_address_book._uri, static_cast(address_book_id)); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to delete address book record", - ("Failed to delete address book record, error code : %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to delete address book record", + ("Failed to delete address book record, error code : %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -298,8 +269,7 @@ PlatformResult ContactManagerUpdate(const JsonObject& args, JsonObject&) { const JsonObject& person = FromJson(args, "person"); long person_id = common::stol(FromJson(person, "id")); contacts_record_h contacts_record = nullptr; - int error_code = contacts_db_get_record(_contacts_person._uri, person_id, - &contacts_record); + int error_code = contacts_db_get_record(_contacts_person._uri, person_id, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Person not found"); @@ -308,14 +278,14 @@ PlatformResult ContactManagerUpdate(const JsonObject& args, JsonObject&) { status = ContactUtil::ExportPersonToContactsRecord(contacts_record, person); if (status.IsError()) return status; - ContactUtil::ContactsRecordHPtr contacts_record_ptr( - &contacts_record, ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr contacts_record_ptr(&contacts_record, + ContactUtil::ContactsDeleter); error_code = contacts_db_update_record(*contacts_record_ptr); if (CONTACTS_ERROR_NONE != error_code) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during executing contacts_db_update_record()", - ("error code: %d", error_code)); + "Error during executing contacts_db_update_record()", + ("error code: %d", error_code)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -336,8 +306,7 @@ PlatformResult ContactManagerUpdateBatch(const JsonObject& args) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "list creation failed", ("list creation failed, code: %d", err)); } - ContactUtil::ContactsListHPtr contacts_list_ptr( - &contacts_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr contacts_list_ptr(&contacts_list, ContactUtil::ContactsListDeleter); for (auto& item : batch_args) { const JsonObject& person = JsonCast(item); @@ -348,25 +317,23 @@ PlatformResult ContactManagerUpdateBatch(const JsonObject& args) { if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Person not found"); } - ContactUtil::ContactsRecordHPtr x(&to_update, - ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr x(&to_update, ContactUtil::ContactsDeleter); status = ContactUtil::ExportPersonToContactsRecord(to_update, person); if (status.IsError()) return status; err = contacts_list_add(*contacts_list_ptr, *(x.release())); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "error during add record to list", - ("error during add record to list, code: %d", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "error during add record to list", + ("error during add record to list, code: %d", err)); } } err = contacts_db_update_records(*contacts_list_ptr); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during executing contacts_db_update_record()", - ("error code: %d", err)); + "Error during executing contacts_db_update_record()", + ("error code: %d", err)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -385,9 +352,8 @@ PlatformResult ContactManagerRemove(const JsonObject& args, JsonObject&) { int error_code = contacts_db_delete_record(_contacts_person._uri, person_id); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Error during removing contact", - ("Error during removing contact, error: %d", error_code)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Error during removing contact", + ("Error during removing contact, error: %d", error_code)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -400,7 +366,7 @@ PlatformResult ContactManagerRemoveBatch(const JsonObject& args) { const JsonArray& batch_args = FromJson(args, "batchArgs"); int length = static_cast(batch_args.size()); - int ids[length], i=0; + int ids[length], i = 0; for (auto& item : batch_args) { long person_id = common::stol(item.get()); @@ -413,9 +379,8 @@ PlatformResult ContactManagerRemoveBatch(const JsonObject& args) { int err = contacts_db_delete_records(_contacts_person._uri, ids, length); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Error during removing contact", - ("Error during removing contact, error: %d", err)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Error during removing contact", + ("Error during removing contact, error: %d", err)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -449,8 +414,7 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { bool is_asc = sort_mode.get("order").to_str() == "ASC"; error_code = contacts_query_set_sort(contacts_query, property.propertyId, is_asc); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_sort"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_sort"); if (status.IsError()) return status; } else { error_code = contacts_query_create(_contacts_person._uri, &contacts_query); @@ -458,108 +422,97 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (status.IsError()) return status; } - ContactUtil::ContactsQueryHPtr contacts_query_ptr( - &contacts_query, ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr contacts_query_ptr(&contacts_query, + ContactUtil::ContactsQueryDeleter); // Add filter to query - std::vector> intermediate_filters( - 1); + std::vector> intermediate_filters(1); if (!IsNull(args, "filter")) { FilterVisitor visitor; - visitor.SetOnAttributeFilter([&](const std::string& name, - AttributeMatchFlag match_flag, - const JsonValue& match_value) { - Person::PersonProperty property; - status = Person::PersonPropertyFromString(name, &property); - if (status.IsError()) return status; + visitor.SetOnAttributeFilter( + [&](const std::string& name, AttributeMatchFlag match_flag, const JsonValue& match_value) { + Person::PersonProperty property; + status = Person::PersonPropertyFromString(name, &property); + if (status.IsError()) return status; - contacts_filter_h contacts_filter = nullptr; - int error_code = CONTACTS_ERROR_NONE; + contacts_filter_h contacts_filter = nullptr; + int error_code = CONTACTS_ERROR_NONE; - error_code = contacts_filter_create(_contacts_person._uri, &contacts_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); - if (status.IsError()) return status; + error_code = contacts_filter_create(_contacts_person._uri, &contacts_filter); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); + if (status.IsError()) return status; - ContactUtil::ContactsFilterPtr contacts_filter_ptr( - contacts_filter, ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr contacts_filter_ptr(contacts_filter, + ContactUtil::ContactsFilterDeleter); - if (property.type == kPrimitiveTypeBoolean) { - bool value = true; - if (AttributeMatchFlag::kExists != match_flag) { - value = JsonCast(match_value); - } - error_code = contacts_filter_add_bool(contacts_filter, - property.propertyId, value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); - if (status.IsError()) return status; - } else if (property.type == kPrimitiveTypeString) { - std::string value = JsonCast(match_value); - - contacts_match_str_flag_e flag = CONTACTS_MATCH_EXISTS; - if (AttributeMatchFlag::kExactly == match_flag) { - flag = CONTACTS_MATCH_EXACTLY; - } else if (AttributeMatchFlag::kFullString == match_flag) { - flag = CONTACTS_MATCH_FULLSTRING; - } else if (AttributeMatchFlag::kContains == match_flag) { - flag = CONTACTS_MATCH_CONTAINS; - } else if (AttributeMatchFlag::kStartsWith == match_flag) { - flag = CONTACTS_MATCH_STARTSWITH; - } else if (AttributeMatchFlag::kEndsWith == match_flag) { - flag = CONTACTS_MATCH_ENDSWITH; - } else if (AttributeMatchFlag::kExists == match_flag) { - flag = CONTACTS_MATCH_EXISTS; - value = ""; - } - error_code = contacts_filter_add_str( - contacts_filter, property.propertyId, flag, value.c_str()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); - if (status.IsError()) return status; - } else if (property.type == kPrimitiveTypeLong || - property.type == kPrimitiveTypeId) { - int value; - if (property.type == kPrimitiveTypeLong) { - value = static_cast(JsonCast(match_value)); - } else { - value = common::stol(JsonCast(match_value)); - } - if (value < 0) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Match value cannot be less than 0"); - } - contacts_match_int_flag_e flag; - if (AttributeMatchFlag::kExists == match_flag) { - flag = CONTACTS_MATCH_GREATER_THAN_OR_EQUAL; - value = 0; - } else if (AttributeMatchFlag::kStartsWith == match_flag || - AttributeMatchFlag::kContains == match_flag) { - flag = CONTACTS_MATCH_GREATER_THAN_OR_EQUAL; - } else if (AttributeMatchFlag::kEndsWith == match_flag) { - flag = CONTACTS_MATCH_LESS_THAN_OR_EQUAL; - } else { - flag = CONTACTS_MATCH_EQUAL; - } + if (property.type == kPrimitiveTypeBoolean) { + bool value = true; + if (AttributeMatchFlag::kExists != match_flag) { + value = JsonCast(match_value); + } + error_code = contacts_filter_add_bool(contacts_filter, property.propertyId, value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); + if (status.IsError()) return status; + } else if (property.type == kPrimitiveTypeString) { + std::string value = JsonCast(match_value); + + contacts_match_str_flag_e flag = CONTACTS_MATCH_EXISTS; + if (AttributeMatchFlag::kExactly == match_flag) { + flag = CONTACTS_MATCH_EXACTLY; + } else if (AttributeMatchFlag::kFullString == match_flag) { + flag = CONTACTS_MATCH_FULLSTRING; + } else if (AttributeMatchFlag::kContains == match_flag) { + flag = CONTACTS_MATCH_CONTAINS; + } else if (AttributeMatchFlag::kStartsWith == match_flag) { + flag = CONTACTS_MATCH_STARTSWITH; + } else if (AttributeMatchFlag::kEndsWith == match_flag) { + flag = CONTACTS_MATCH_ENDSWITH; + } else if (AttributeMatchFlag::kExists == match_flag) { + flag = CONTACTS_MATCH_EXISTS; + value = ""; + } + error_code = + contacts_filter_add_str(contacts_filter, property.propertyId, flag, value.c_str()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); + if (status.IsError()) return status; + } else if (property.type == kPrimitiveTypeLong || property.type == kPrimitiveTypeId) { + int value; + if (property.type == kPrimitiveTypeLong) { + value = static_cast(JsonCast(match_value)); + } else { + value = common::stol(JsonCast(match_value)); + } + if (value < 0) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Match value cannot be less than 0"); + } + contacts_match_int_flag_e flag; + if (AttributeMatchFlag::kExists == match_flag) { + flag = CONTACTS_MATCH_GREATER_THAN_OR_EQUAL; + value = 0; + } else if (AttributeMatchFlag::kStartsWith == match_flag || + AttributeMatchFlag::kContains == match_flag) { + flag = CONTACTS_MATCH_GREATER_THAN_OR_EQUAL; + } else if (AttributeMatchFlag::kEndsWith == match_flag) { + flag = CONTACTS_MATCH_LESS_THAN_OR_EQUAL; + } else { + flag = CONTACTS_MATCH_EQUAL; + } - error_code = contacts_filter_add_int(contacts_filter, - property.propertyId, flag, value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); - if (status.IsError()) return status; - } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Invalid primitive type!"); - } - intermediate_filters[intermediate_filters.size() - 1].push_back( - std::move(contacts_filter_ptr)); + error_code = contacts_filter_add_int(contacts_filter, property.propertyId, flag, value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); + if (status.IsError()) return status; + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Invalid primitive type!"); + } + intermediate_filters[intermediate_filters.size() - 1].push_back( + std::move(contacts_filter_ptr)); - return PlatformResult(ErrorCode::NO_ERROR); - }); + return PlatformResult(ErrorCode::NO_ERROR); + }); - visitor.SetOnAttributeRangeFilter([&](const std::string& name, - const JsonValue& initial_value, + visitor.SetOnAttributeRangeFilter([&](const std::string& name, const JsonValue& initial_value, const JsonValue& end_value) { Person::PersonProperty property; status = Person::PersonPropertyFromString(name, &property); @@ -569,12 +522,11 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { int error_code = CONTACTS_ERROR_NONE; error_code = contacts_filter_create(_contacts_person._uri, &contacts_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; - ContactUtil::ContactsFilterPtr contacts_filter_ptr( - contacts_filter, ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr contacts_filter_ptr(contacts_filter, + ContactUtil::ContactsFilterDeleter); bool initial_value_exists = (!IsNull(initial_value)); bool end_value_exists = (!IsNull(end_value)); @@ -592,26 +544,21 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { if (initial_value_exists && end_value_exists) { if (initial_value_bool == end_value_bool) { - error_code = contacts_filter_add_bool( - contacts_filter, property.propertyId, initial_value_bool); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_filter_add_bool"); + error_code = + contacts_filter_add_bool(contacts_filter, property.propertyId, initial_value_bool); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (status.IsError()) return status; } } else if (initial_value_exists) { if (initial_value_bool) { - error_code = contacts_filter_add_bool(contacts_filter, - property.propertyId, true); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_filter_add_bool"); + error_code = contacts_filter_add_bool(contacts_filter, property.propertyId, true); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (status.IsError()) return status; } } else if (end_value_exists) { if (!end_value_bool) { - error_code = contacts_filter_add_bool(contacts_filter, - property.propertyId, false); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_filter_add_bool"); + error_code = contacts_filter_add_bool(contacts_filter, property.propertyId, false); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (status.IsError()) return status; } } @@ -631,64 +578,51 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { contacts_filter_h sub_filter = NULL; error_code = contacts_filter_create(_contacts_person._uri, &sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; - ContactUtil::ContactsFilterPtr sub_filter_ptr( - sub_filter, ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, + ContactUtil::ContactsFilterDeleter); - error_code = contacts_filter_add_str(sub_filter, property.propertyId, - CONTACTS_MATCH_STARTSWITH, - initial_value_str.c_str()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = + contacts_filter_add_str(sub_filter, property.propertyId, CONTACTS_MATCH_STARTSWITH, + initial_value_str.c_str()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; - error_code = contacts_filter_add_operator( - sub_filter, CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; error_code = contacts_filter_add_str(sub_filter, property.propertyId, - CONTACTS_MATCH_ENDSWITH, - end_value_str.c_str()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + CONTACTS_MATCH_ENDSWITH, end_value_str.c_str()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; error_code = contacts_filter_add_filter(contacts_filter, sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; } else if (initial_value_exists) { - error_code = contacts_filter_add_str( - contacts_filter, property.propertyId, CONTACTS_MATCH_STARTSWITH, - initial_value_str.c_str()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = + contacts_filter_add_str(contacts_filter, property.propertyId, + CONTACTS_MATCH_STARTSWITH, initial_value_str.c_str()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; } else if (end_value_exists) { - error_code = contacts_filter_add_str( - contacts_filter, property.propertyId, CONTACTS_MATCH_ENDSWITH, - end_value_str.c_str()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = contacts_filter_add_str(contacts_filter, property.propertyId, + CONTACTS_MATCH_ENDSWITH, end_value_str.c_str()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (status.IsError()) return status; } - } else if (property.type == kPrimitiveTypeLong || - property.type == kPrimitiveTypeId) { + } else if (property.type == kPrimitiveTypeLong || property.type == kPrimitiveTypeId) { int initial_value_int = 0; int end_value_int = 0; if (initial_value_exists) { if (property.type == kPrimitiveTypeLong) { - initial_value_int = - static_cast(JsonCast(initial_value)); + initial_value_int = static_cast(JsonCast(initial_value)); } else { - initial_value_int = - common::stol(JsonCast(initial_value)); + initial_value_int = common::stol(JsonCast(initial_value)); } } @@ -704,55 +638,44 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { contacts_filter_h sub_filter = NULL; error_code = contacts_filter_create(_contacts_person._uri, &sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (status.IsError()) return status; - ContactUtil::ContactsFilterPtr sub_filter_ptr( - sub_filter, ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, + ContactUtil::ContactsFilterDeleter); - error_code = contacts_filter_add_int( - sub_filter, property.propertyId, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value_int); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(sub_filter, property.propertyId, + CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value_int); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (status.IsError()) return status; - error_code = contacts_filter_add_operator( - sub_filter, CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (status.IsError()) return status; - error_code = contacts_filter_add_int( - sub_filter, property.propertyId, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value_int); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = contacts_filter_add_int(sub_filter, property.propertyId, + CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value_int); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (status.IsError()) return status; error_code = contacts_filter_add_filter(contacts_filter, sub_filter); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_filter_add_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_filter"); if (status.IsError()) return status; } else if (initial_value_exists) { - error_code = contacts_filter_add_int( - contacts_filter, property.propertyId, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value_int); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(contacts_filter, property.propertyId, + CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value_int); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (status.IsError()) return status; } else if (end_value_exists) { - error_code = contacts_filter_add_int( - contacts_filter, property.propertyId, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value_int); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = contacts_filter_add_int(contacts_filter, property.propertyId, + CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value_int); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (status.IsError()) return status; } } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Invalid primitive type!"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Invalid primitive type!"); } intermediate_filters[intermediate_filters.size() - 1].push_back( std::move(contacts_filter_ptr)); @@ -761,50 +684,40 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { }); visitor.SetOnCompositeFilterBegin([&](CompositeFilterType type) { - intermediate_filters.push_back( - std::vector()); + intermediate_filters.push_back(std::vector()); return PlatformResult(ErrorCode::NO_ERROR); }); visitor.SetOnCompositeFilterEnd([&](CompositeFilterType type) { if (intermediate_filters.size() == 0) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Reached stack size equal to 0!"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Reached stack size equal to 0!"); } contacts_filter_h merged_filter = nullptr; - int error_code = - contacts_filter_create(_contacts_person._uri, &merged_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + int error_code = contacts_filter_create(_contacts_person._uri, &merged_filter); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; - ContactUtil::ContactsFilterPtr merged_filter_ptr( - merged_filter, ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr merged_filter_ptr(merged_filter, + ContactUtil::ContactsFilterDeleter); for (std::size_t i = 0; i < intermediate_filters.back().size(); ++i) { - error_code = contacts_filter_add_filter( - merged_filter, intermediate_filters.back().at(i).get()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + error_code = + contacts_filter_add_filter(merged_filter, intermediate_filters.back().at(i).get()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; if (CompositeFilterType::kIntersection == type) { - error_code = contacts_filter_add_operator( - merged_filter, CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_query_set_filter"); + error_code = contacts_filter_add_operator(merged_filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; } else if (CompositeFilterType::kUnion == type) { - error_code = contacts_filter_add_operator( - merged_filter, CONTACTS_FILTER_OPERATOR_OR); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_query_set_filter"); + error_code = contacts_filter_add_operator(merged_filter, CONTACTS_FILTER_OPERATOR_OR); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; } else { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid union type!"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid union type!"); } } @@ -818,33 +731,26 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { if (status.IsError()) return status; // Should compute only one filter always. - if ((intermediate_filters.size() != 1) || - (intermediate_filters[0].size() != 1)) { + if ((intermediate_filters.size() != 1) || (intermediate_filters[0].size() != 1)) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Bad filter evaluation!"); } // Filter is generated - error_code = contacts_query_set_filter(contacts_query, - intermediate_filters[0][0].get()); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + error_code = contacts_query_set_filter(contacts_query, intermediate_filters[0][0].get()); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (status.IsError()) return status; } contacts_list_h person_list = nullptr; - error_code = - contacts_db_get_records_with_query(contacts_query, 0, 0, &person_list); + error_code = contacts_db_get_records_with_query(contacts_query, 0, 0, &person_list); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (status.IsError()) return status; - ContactUtil::ContactsListHPtr person_list_ptr( - &person_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr person_list_ptr(&person_list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(person_list, &record_count); - status = - ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (status.IsError()) return status; contacts_list_first(person_list); @@ -885,7 +791,7 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& int error_code = CONTACTS_ERROR_NONE; // parse filter const auto filter_it = args.find("filter"); - if (args.end() == filter_it || !filter_it->second.is()){ + if (args.end() == filter_it || !filter_it->second.is()) { LoggerD("Filter is invalid."); return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Filter is invalid"); } @@ -903,8 +809,7 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& is_asc = ("ASC" == sort_mode); } - error_code = contacts_query_set_sort(contacts_query, - _contacts_person_usage.times_used, is_asc); + error_code = contacts_query_set_sort(contacts_query, _contacts_person_usage.times_used, is_asc); status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_sort"); if (status.IsError()) return status; @@ -923,16 +828,14 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& // Attribute filter handling, only EQUAL is supported for ints (other are ignored) int match_value = 0; const auto& match = filter.get("matchValue"); - if (match.is()){ + if (match.is()) { match_value = static_cast(match.get()); if (match_value < 0) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Match value cannot be less than 0"); + "Match value cannot be less than 0"); } - ret = contacts_filter_add_int(filter_handle, - _contacts_person_usage.times_used, - CONTACTS_MATCH_EQUAL, - match_value); + ret = contacts_filter_add_int(filter_handle, _contacts_person_usage.times_used, + CONTACTS_MATCH_EQUAL, match_value); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { return status; @@ -946,13 +849,11 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& // inital value handling const auto& initial = filter.get("initialValue"); - if (initial.is()){ + if (initial.is()) { initial_value = static_cast(initial.get()); - ret = contacts_filter_add_int(filter_handle, - _contacts_person_usage.times_used, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, - initial_value); + ret = contacts_filter_add_int(filter_handle, _contacts_person_usage.times_used, + CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { return status; @@ -961,20 +862,18 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& } // end value handling const auto& end = filter.get("endValue"); - if (end.is()){ + if (end.is()) { end_value = static_cast(end.get()); - if (is_added){ + if (is_added) { ret = contacts_filter_add_operator(filter_handle, CONTACTS_FILTER_OPERATOR_AND); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_operator"); if (!status) { return status; } } - ret = contacts_filter_add_int(filter_handle, - _contacts_person_usage.times_used, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, - end_value); + ret = contacts_filter_add_int(filter_handle, _contacts_person_usage.times_used, + CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { return status; @@ -984,7 +883,7 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& } // if some filtering is already added, use AND operator - if (is_added){ + if (is_added) { ret = contacts_filter_add_operator(filter_handle, CONTACTS_FILTER_OPERATOR_AND); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_operator"); if (!status) { @@ -997,10 +896,8 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Type of usage in filter should be one of ContactUsageType values"); } - ret = contacts_filter_add_int(filter_handle, - _contacts_person_usage.usage_type, - CONTACTS_MATCH_EQUAL, - type); + ret = contacts_filter_add_int(filter_handle, _contacts_person_usage.usage_type, + CONTACTS_MATCH_EQUAL, type); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { return status; @@ -1027,28 +924,23 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& } contacts_list_h person_list = nullptr; - error_code = - contacts_db_get_records_with_query(contacts_query, offset, limit, &person_list); + error_code = contacts_db_get_records_with_query(contacts_query, offset, limit, &person_list); - status = ContactUtil::ErrorChecker( - error_code, "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (status.IsError()) return status; - ContactUtil::ContactsListHPtr person_list_ptr( - &person_list, ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr person_list_ptr(&person_list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(person_list, &record_count); - status = - ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (status.IsError()) return status; contacts_list_first(person_list); for (int i = 0; i < record_count; i++) { contacts_record_h contacts_record; - error_code = - contacts_list_get_current_record_p(person_list, &contacts_record); + error_code = contacts_list_get_current_record_p(person_list, &contacts_record); if (CONTACTS_ERROR_NONE != error_code || nullptr == contacts_record) { LoggerW("Failed group record (ret:%d)", error_code); continue; @@ -1068,8 +960,7 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ContactManagerImportFromVCard(const JsonObject& args, - JsonObject& out) { +PlatformResult ContactManagerImportFromVCard(const JsonObject& args, JsonObject& out) { LoggerD("Enter"); // I'm not sure how to call it. Should it be 'Contact', 'vCard' or what? PlatformResult status = ContactUtil::CheckDBConnection(); @@ -1083,8 +974,7 @@ PlatformResult ContactManagerImportFromVCard(const JsonObject& args, if (CONTACTS_ERROR_INVALID_PARAMETER == err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Invalid vCard string"); } else if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Fail to convert vCard from string"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to convert vCard from string"); } SCOPE_EXIT { @@ -1120,8 +1010,7 @@ bool IsNumeric(const char* s) { return true; } -void ContactManagerListenerCallback(const char* view_uri, char* changes, - void* user_data) { +void ContactManagerListenerCallback(const char* view_uri, char* changes, void* user_data) { LoggerD("ContactManagerListenerCallback"); (void)view_uri; @@ -1140,17 +1029,19 @@ void ContactManagerListenerCallback(const char* view_uri, char* changes, JsonValue result{JsonObject{}}; JsonObject& result_obj = result.get(); - result_obj.insert(std::make_pair(std::string("listenerId"), - picojson::value(kContactPersonListenerId))); - JsonArray& added = result_obj.insert(std::make_pair(std::string("added"), - picojson::value(JsonArray{}))).first->second.get(); - JsonArray& updated = result_obj.insert(std::make_pair(std::string("updated"), - picojson::value(JsonArray{}))).first->second.get(); - JsonArray& removed = result_obj.insert(std::make_pair(std::string("removed"), - picojson::value(JsonArray{}))).first->second.get(); - - std::unique_ptr tmp(strdup(changes), - [](char* p) { free(p); }); + result_obj.insert( + std::make_pair(std::string("listenerId"), picojson::value(kContactPersonListenerId))); + JsonArray& added = + result_obj.insert(std::make_pair(std::string("added"), picojson::value(JsonArray{}))) + .first->second.get(); + JsonArray& updated = + result_obj.insert(std::make_pair(std::string("updated"), picojson::value(JsonArray{}))) + .first->second.get(); + JsonArray& removed = + result_obj.insert(std::make_pair(std::string("removed"), picojson::value(JsonArray{}))) + .first->second.get(); + + std::unique_ptr tmp(strdup(changes), [](char* p) { free(p); }); // 'changes' may contain repeated values, we need to filter it std::set added_ids; @@ -1173,11 +1064,10 @@ void ContactManagerListenerCallback(const char* view_uri, char* changes, case CONTACTS_CHANGE_INSERTED: { if (added_ids.find(person_id) == added_ids.end()) { added.push_back(JsonValue{JsonObject{}}); - PlatformResult status = ContactManagerGetInternal( - person_id, &added.back().get()); + PlatformResult status = + ContactManagerGetInternal(person_id, &added.back().get()); if (status.IsError()) { - LoggerE("Caught exception in listener callback: %s", - status.message().c_str()); + LoggerE("Caught exception in listener callback: %s", status.message().c_str()); return; } added_ids.insert(person_id); @@ -1188,11 +1078,10 @@ void ContactManagerListenerCallback(const char* view_uri, char* changes, case CONTACTS_CHANGE_UPDATED: { if (updated_ids.find(person_id) == updated_ids.end()) { updated.push_back(JsonValue{JsonObject{}}); - PlatformResult status = ContactManagerGetInternal( - person_id, &updated.back().get()); + PlatformResult status = + ContactManagerGetInternal(person_id, &updated.back().get()); if (status.IsError()) { - LoggerE("Caught exception in listener callback: %s", - status.message().c_str()); + LoggerE("Caught exception in listener callback: %s", status.message().c_str()); return; } updated_ids.insert(person_id); @@ -1207,9 +1096,7 @@ void ContactManagerListenerCallback(const char* view_uri, char* changes, } break; } - default: { - break; - } + default: { break; } } } } @@ -1228,13 +1115,13 @@ PlatformResult ContactManagerStartListening(ContactInstance& instance, const Jso PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; - int error_code = contacts_db_add_changed_cb_with_info( - _contacts_person._uri, ContactManagerListenerCallback, &instance); + int error_code = contacts_db_add_changed_cb_with_info(_contacts_person._uri, + ContactManagerListenerCallback, &instance); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to start listening", - ("contacts_db_add_changed_cb(_contacts_person._uri) error: %d", - error_code)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to start listening", + ("contacts_db_add_changed_cb(_contacts_person._uri) error: %d", error_code)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -1250,9 +1137,9 @@ PlatformResult ContactManagerStopListening(ContactInstance& instance, const Json _contacts_person._uri, ContactManagerListenerCallback, &instance); if (CONTACTS_ERROR_NONE != error_code) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to stop listening", - ("contacts_db_remove_changed_cb(_contacts_person._uri) error: %d", - error_code)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to stop listening", + ("contacts_db_remove_changed_cb(_contacts_person._uri) error: %d", error_code)); } return PlatformResult(ErrorCode::NO_ERROR); diff --git a/src/contact/contact_manager.h b/src/contact/contact_manager.h old mode 100755 new mode 100644 index 1da0132..81736f4 --- a/src/contact/contact_manager.h +++ b/src/contact/contact_manager.h @@ -27,35 +27,25 @@ class ContactInstance; namespace ContactManager { -common::PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, - JsonArray& out); +common::PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, JsonArray& out); -common::PlatformResult ContactManagerGetAddressBook(const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerGetAddressBook(const JsonObject& args, JsonObject& out); -common::PlatformResult ContactManagerAddAddressBook(const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerAddAddressBook(const JsonObject& args, JsonObject& out); -common::PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, JsonObject& out); -common::PlatformResult ContactManagerGet(const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerGet(const JsonObject& args, JsonObject& out); -common::PlatformResult ContactManagerUpdate(const JsonObject& args, - JsonObject&); +common::PlatformResult ContactManagerUpdate(const JsonObject& args, JsonObject&); -common::PlatformResult ContactManagerRemove(const JsonObject& args, - JsonObject&); +common::PlatformResult ContactManagerRemove(const JsonObject& args, JsonObject&); -common::PlatformResult ContactManagerFind(const JsonObject& args, - JsonArray& out); +common::PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out); -common::PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, - JsonArray& out); +common::PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& out); -common::PlatformResult ContactManagerImportFromVCard(const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerImportFromVCard(const JsonObject& args, JsonObject& out); common::PlatformResult ContactManagerUpdateBatch(const JsonObject& args); common::PlatformResult ContactManagerRemoveBatch(const JsonObject& args); @@ -71,8 +61,8 @@ common::PlatformResult ContactManagerRemoveBatch(const JsonObject& args); * {status: 'success'} * @endcode */ -common::PlatformResult ContactManagerStartListening(ContactInstance& instance, const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerStartListening(ContactInstance& instance, + const JsonObject& args, JsonObject& out); /** * Signature: @code void getAddressBook(contactString); @endcode @@ -85,8 +75,8 @@ common::PlatformResult ContactManagerStartListening(ContactInstance& instance, c * {status: 'success'} * @endcode */ -common::PlatformResult ContactManagerStopListening(ContactInstance& instance, const JsonObject& args, - JsonObject& out); +common::PlatformResult ContactManagerStopListening(ContactInstance& instance, + const JsonObject& args, JsonObject& out); } // namespace ContactManager } // namespace contact diff --git a/src/contact/contact_search_engine.cc b/src/contact/contact_search_engine.cc index 1457318..5bc09e6 100644 --- a/src/contact/contact_search_engine.cc +++ b/src/contact/contact_search_engine.cc @@ -51,11 +51,9 @@ std::tm* ToDateTm(const picojson::value& value) { std::string ToDateDbStr(const tm& date) { std::stringstream ss; ss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(4) - << (date.tm_year + 1900); - ss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) - << (date.tm_mon + 1); - ss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) - << date.tm_mday; + << (date.tm_year + 1900); + ss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << (date.tm_mon + 1); + ss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << date.tm_mday; return ss.str(); } @@ -76,55 +74,140 @@ int ToDateDbInt(const tm& date) { } // namespace ContactSearchEngine::PropertiesMap ContactSearchEngine::s_properties_map_ = { - {"id", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.id, PrimitiveType_Long } }, - {"personId", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.person_id, PrimitiveType_Long } }, - {"addressBookId", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.address_book_id, PrimitiveType_Long } }, - {"lastUpdated", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.changed_time, PrimitiveType_Long } }, - {"isFavorite", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.is_favorite, PrimitiveType_Boolean } }, - {"name.prefix", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.prefix, PrimitiveType_String } }, - {"name.suffix", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.suffix, PrimitiveType_String } }, - {"name.firstName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.first, PrimitiveType_String } }, - {"name.middleName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.addition, PrimitiveType_String } }, - {"name.lastName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.last, PrimitiveType_String } }, - {"name.nicknames", { _contacts_nickname._uri, _contacts_nickname.contact_id, _contacts_nickname.name, PrimitiveType_String } }, - {"name.phoneticFirstName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_first, PrimitiveType_String } }, - {"name.phoneticMiddleName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_middle, PrimitiveType_String } }, - {"name.phoneticLastName", { _contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_last, PrimitiveType_String } }, - {"name.displayName", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.display_name, PrimitiveType_String } }, - {"addresses.country", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.country, PrimitiveType_String } }, - {"addresses.region", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.region, PrimitiveType_String } }, - {"addresses.city", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.locality, PrimitiveType_String } }, - {"addresses.streetAddress", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.street, PrimitiveType_String } }, - {"addresses.additionalInformation", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.extended, PrimitiveType_String } }, - {"addresses.postalCode", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.postal_code, PrimitiveType_String } }, - {"addresses.isDefault", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.is_default, PrimitiveType_Boolean } }, - {"addresses.types", { _contacts_address._uri, _contacts_address.contact_id, _contacts_address.type, PrimitiveType_Long } }, - {"photoURI", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.image_thumbnail_path, PrimitiveType_String } }, - {"phoneNumbers.number", { _contacts_number._uri, _contacts_number.contact_id, _contacts_number.number, PrimitiveType_String } }, - {"phoneNumbers.isDefault", { _contacts_number._uri, _contacts_number.contact_id, _contacts_number.is_default, PrimitiveType_Boolean } }, - {"phoneNumbers.types", { _contacts_number._uri, _contacts_number.contact_id, _contacts_number.type, PrimitiveType_Long } }, - {"emails.email", { _contacts_email._uri, _contacts_email.contact_id, _contacts_email.email, PrimitiveType_String } }, - {"emails.isDefault", { _contacts_email._uri, _contacts_email.contact_id, _contacts_email.is_default, PrimitiveType_Boolean } }, - {"emails.types", { _contacts_email._uri, _contacts_email.contact_id, _contacts_email.type, PrimitiveType_Long } }, - {"birthday", { _contacts_event._uri, _contacts_event.contact_id, _contacts_event.date, PrimitiveType_Long } }, - {"anniversaries.date", { _contacts_event._uri, _contacts_event.contact_id, _contacts_event.date, PrimitiveType_Long } }, - {"anniversaries.label", { _contacts_event._uri, _contacts_event.contact_id, _contacts_event.label, PrimitiveType_String } }, - {"organizations.name", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.name, PrimitiveType_String } }, - {"organizations.department",{ _contacts_company._uri, _contacts_company.contact_id, _contacts_company.department, PrimitiveType_String } }, - {"organizations.title", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.job_title, PrimitiveType_String } }, - {"organizations.role", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.role, PrimitiveType_String } }, - {"organizations.logoURI", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.logo, PrimitiveType_String } }, - {"organizations.assistant", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.assistant_name, PrimitiveType_String } }, - {"organizations.location", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.location, PrimitiveType_String } }, - {"organizations.description", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.description, PrimitiveType_String } }, - {"organizations.phoneticName", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.phonetic_name, PrimitiveType_String } }, - {"organizations.type", { _contacts_company._uri, _contacts_company.contact_id, _contacts_company.type, PrimitiveType_Long } }, - {"notes", { _contacts_note._uri, _contacts_note.contact_id, _contacts_note.note, PrimitiveType_String } }, - {"urls.url", { _contacts_url._uri, _contacts_url.contact_id, _contacts_url.url, PrimitiveType_String } }, - {"urls.type", { _contacts_url._uri, _contacts_url.contact_id, _contacts_url.type, PrimitiveType_Long } }, - {"ringtoneURI", { _contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.ringtone_path, PrimitiveType_String } }, - {"groupIds", { _contacts_group_relation._uri, _contacts_group_relation.contact_id, _contacts_group_relation.group_id, PrimitiveType_Long } } -}; + {"id", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, _contacts_simple_contact.id, + PrimitiveType_Long}}, + {"personId", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.person_id, PrimitiveType_Long}}, + {"addressBookId", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.address_book_id, PrimitiveType_Long}}, + {"lastUpdated", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.changed_time, PrimitiveType_Long}}, + {"isFavorite", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.is_favorite, PrimitiveType_Boolean}}, + {"name.prefix", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.prefix, PrimitiveType_String}}, + {"name.suffix", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.suffix, PrimitiveType_String}}, + {"name.firstName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.first, PrimitiveType_String}}, + {"name.middleName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.addition, + PrimitiveType_String}}, + {"name.lastName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.last, PrimitiveType_String}}, + {"name.nicknames", + {_contacts_nickname._uri, _contacts_nickname.contact_id, _contacts_nickname.name, + PrimitiveType_String}}, + {"name.phoneticFirstName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_first, + PrimitiveType_String}}, + {"name.phoneticMiddleName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_middle, + PrimitiveType_String}}, + {"name.phoneticLastName", + {_contacts_name._uri, _contacts_name.contact_id, _contacts_name.phonetic_last, + PrimitiveType_String}}, + {"name.displayName", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.display_name, PrimitiveType_String}}, + {"addresses.country", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.country, + PrimitiveType_String}}, + {"addresses.region", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.region, + PrimitiveType_String}}, + {"addresses.city", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.locality, + PrimitiveType_String}}, + {"addresses.streetAddress", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.street, + PrimitiveType_String}}, + {"addresses.additionalInformation", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.extended, + PrimitiveType_String}}, + {"addresses.postalCode", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.postal_code, + PrimitiveType_String}}, + {"addresses.isDefault", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.is_default, + PrimitiveType_Boolean}}, + {"addresses.types", + {_contacts_address._uri, _contacts_address.contact_id, _contacts_address.type, + PrimitiveType_Long}}, + {"photoURI", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.image_thumbnail_path, PrimitiveType_String}}, + {"phoneNumbers.number", + {_contacts_number._uri, _contacts_number.contact_id, _contacts_number.number, + PrimitiveType_String}}, + {"phoneNumbers.isDefault", + {_contacts_number._uri, _contacts_number.contact_id, _contacts_number.is_default, + PrimitiveType_Boolean}}, + {"phoneNumbers.types", + {_contacts_number._uri, _contacts_number.contact_id, _contacts_number.type, + PrimitiveType_Long}}, + {"emails.email", + {_contacts_email._uri, _contacts_email.contact_id, _contacts_email.email, + PrimitiveType_String}}, + {"emails.isDefault", + {_contacts_email._uri, _contacts_email.contact_id, _contacts_email.is_default, + PrimitiveType_Boolean}}, + {"emails.types", + {_contacts_email._uri, _contacts_email.contact_id, _contacts_email.type, PrimitiveType_Long}}, + {"birthday", + {_contacts_event._uri, _contacts_event.contact_id, _contacts_event.date, PrimitiveType_Long}}, + {"anniversaries.date", + {_contacts_event._uri, _contacts_event.contact_id, _contacts_event.date, PrimitiveType_Long}}, + {"anniversaries.label", + {_contacts_event._uri, _contacts_event.contact_id, _contacts_event.label, + PrimitiveType_String}}, + {"organizations.name", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.name, + PrimitiveType_String}}, + {"organizations.department", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.department, + PrimitiveType_String}}, + {"organizations.title", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.job_title, + PrimitiveType_String}}, + {"organizations.role", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.role, + PrimitiveType_String}}, + {"organizations.logoURI", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.logo, + PrimitiveType_String}}, + {"organizations.assistant", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.assistant_name, + PrimitiveType_String}}, + {"organizations.location", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.location, + PrimitiveType_String}}, + {"organizations.description", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.description, + PrimitiveType_String}}, + {"organizations.phoneticName", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.phonetic_name, + PrimitiveType_String}}, + {"organizations.type", + {_contacts_company._uri, _contacts_company.contact_id, _contacts_company.type, + PrimitiveType_Long}}, + {"notes", + {_contacts_note._uri, _contacts_note.contact_id, _contacts_note.note, PrimitiveType_String}}, + {"urls.url", + {_contacts_url._uri, _contacts_url.contact_id, _contacts_url.url, PrimitiveType_String}}, + {"urls.type", + {_contacts_url._uri, _contacts_url.contact_id, _contacts_url.type, PrimitiveType_Long}}, + {"ringtoneURI", + {_contacts_simple_contact._uri, _contacts_simple_contact.id, + _contacts_simple_contact.ringtone_path, PrimitiveType_String}}, + {"groupIds", + {_contacts_group_relation._uri, _contacts_group_relation.contact_id, + _contacts_group_relation.group_id, PrimitiveType_Long}}}; // implementation ported from wrt-plugins-tizen @@ -260,9 +343,10 @@ common::PlatformResult ContactSearchEngine::Find(picojson::array* out) { } } -PlatformResult ContactSearchEngine::ApplyAttributeFilter( - const std::string& name, common::AttributeMatchFlag match_flag, - const picojson::value& match_value, int depth) { +PlatformResult ContactSearchEngine::ApplyAttributeFilter(const std::string& name, + common::AttributeMatchFlag match_flag, + const picojson::value& match_value, + int depth) { LoggerD("Entered"); LongSetPtr id_set = LongSetPtr(new LongSet()); @@ -278,9 +362,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeFilter( } } return PlatformResult(ErrorCode::NO_ERROR); - } else if ("addresses.types" == name || - "emails.types" == name || - "phoneNumbers.types" == name || + } else if ("addresses.types" == name || "emails.types" == name || "phoneNumbers.types" == name || "urls.type" == name) { if (!depth) { filtered_contact_ids_ = LongSetPtr(); @@ -288,7 +370,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeFilter( return PlatformResult(ErrorCode::NO_ERROR); } - const auto iter = s_properties_map_.find(name); + const auto iter = s_properties_map_.find(name); if (s_properties_map_.end() == iter) { std::string msg = "Unknown attribute name: " + name; return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, msg); @@ -308,9 +390,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeFilter( std::string value = ""; if (common::AttributeMatchFlag::kExists != match_flag) { - if ("photoURI" == name || - "ringtoneURI" == name || - "organizations.logoURI" == name) { + if ("photoURI" == name || "ringtoneURI" == name || "organizations.logoURI" == name) { value = ContactUtil::ConvertUriToPath(JsonCast(match_value)); } else { value = JsonCast(match_value); @@ -381,9 +461,10 @@ PlatformResult ContactSearchEngine::ApplyAttributeFilter( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( - const std::string& name, const picojson::value& initial_value, - const picojson::value& end_value, int depth) { +PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter(const std::string& name, + const picojson::value& initial_value, + const picojson::value& end_value, + int depth) { LoggerD("Entered"); bool initial_value_set = (!IsNull(initial_value)); @@ -396,9 +477,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( return PlatformResult(ErrorCode::NO_ERROR); } - if ("addresses.types" == name || - "emails.types" == name || - "phoneNumbers.types" == name || + if ("addresses.types" == name || "emails.types" == name || "phoneNumbers.types" == name || "urls.type" == name) { if (!depth) { filtered_contact_ids_ = LongSetPtr(); @@ -406,7 +485,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( return PlatformResult(ErrorCode::NO_ERROR); } - const auto iter = s_properties_map_.find(name); + const auto iter = s_properties_map_.find(name); if (s_properties_map_.end() == iter) { std::string msg = "Unknown attribute name: " + name; return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, msg); @@ -426,9 +505,8 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( end_value_bool = JsonCast(end_value); } - auto status = QueryAttributeRangeBool(properties, id_set, initial_value_set, - initial_value_bool, end_value_set, - end_value_bool); + auto status = QueryAttributeRangeBool(properties, id_set, initial_value_set, initial_value_bool, + end_value_set, end_value_bool); if (!status) return status; } else if (PrimitiveType_String == properties.type) { const char* initial_value_str = nullptr; @@ -441,8 +519,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( end_value_str = JsonCast(end_value).c_str(); } - auto status = QueryAttributeRangeString(properties, id_set, - initial_value_str, end_value_str); + auto status = QueryAttributeRangeString(properties, id_set, initial_value_str, end_value_str); if (!status) return status; } else if (PrimitiveType_Long == properties.type) { int initial_value_int = 0; @@ -472,14 +549,11 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( } if ("birthday" == name || "anniversaries.date" == name) { - auto status = QueryAttributeRangeDate(name, properties, id_set, - initial_value_set, - initial_value_int, end_value_set, - end_value_int); + auto status = QueryAttributeRangeDate(name, properties, id_set, initial_value_set, + initial_value_int, end_value_set, end_value_int); if (!status) return status; } else { - auto status = QueryAttributeRangeInt(properties, id_set, - initial_value_set, initial_value_int, + auto status = QueryAttributeRangeInt(properties, id_set, initial_value_set, initial_value_int, end_value_set, end_value_int); if (!status) return status; } @@ -495,8 +569,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter( } PlatformResult ContactSearchEngine::GetAllContactsSorted( - const FilterPropertyStruct& attribute_properties, bool is_ascending, - picojson::array* out) { + const FilterPropertyStruct& attribute_properties, bool is_ascending, picojson::array* out) { LoggerD("Entered"); LongVectorPtr sorted_ids = LongVectorPtr(new LongVector()); @@ -513,57 +586,44 @@ PlatformResult ContactSearchEngine::GetAllContacts(picojson::array* out) { PlatformResult status(ErrorCode::NO_ERROR); if (!is_addressbook_id_is_set_) { - error_code = contacts_db_get_all_records(_contacts_contact._uri, 0, 0, - &list); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_db_get_all_records"); + error_code = contacts_db_get_all_records(_contacts_contact._uri, 0, 0, &list); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_all_records"); if (!status) return status; } else { contacts_query_h query = nullptr; contacts_filter_h filter = nullptr; error_code = contacts_query_create(_contacts_contact._uri, &query); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(_contacts_contact._uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); - error_code = contacts_filter_add_int(filter, - _contacts_contact.address_book_id, - CONTACTS_MATCH_EQUAL, - addressbook_id_); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = contacts_filter_add_int(filter, _contacts_contact.address_book_id, + CONTACTS_MATCH_EQUAL, addressbook_id_); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; error_code = contacts_query_set_filter(query, filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (!status) return status; error_code = contacts_db_get_records_with_query(query, 0, 0, &list); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (!status) return status; } - ContactUtil::ContactsListHPtr list_ptr(&list, - ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr list_ptr(&list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(list, &record_count); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (!status) return status; contacts_list_first(list); @@ -600,7 +660,7 @@ PlatformResult ContactSearchEngine::GetAllContacts(picojson::array* out) { return PlatformResult(ErrorCode::NO_ERROR); } -template +template PlatformResult ContactSearchEngine::GetContacts(Iterator begin, Iterator end, picojson::array* out) { LoggerD("Entered"); @@ -615,15 +675,13 @@ PlatformResult ContactSearchEngine::GetContacts(Iterator begin, Iterator end, continue; } - ContactUtil::ContactsRecordHPtr record_ptr(&record, - ContactUtil::ContactsDeleter); + ContactUtil::ContactsRecordHPtr record_ptr(&record, ContactUtil::ContactsDeleter); if (is_addressbook_id_is_set_) { int address_book_id = 0; - error_code = contacts_record_get_int(record, - _contacts_contact.address_book_id, - &address_book_id); + error_code = + contacts_record_get_int(record, _contacts_contact.address_book_id, &address_book_id); if (CONTACTS_ERROR_NONE != error_code) { LoggerE("Failed to get address book ID of contact with ID: %d", id); continue; @@ -653,44 +711,38 @@ PlatformResult ContactSearchEngine::GetContacts(Iterator begin, Iterator end, return PlatformResult(ErrorCode::NO_ERROR); } - -common::PlatformResult ContactSearchEngine::GetQueryResults( - contacts_query_h query, contacts_filter_h filter, unsigned int property_id, - LongSetPtr result) { +common::PlatformResult ContactSearchEngine::GetQueryResults(contacts_query_h query, + contacts_filter_h filter, + unsigned int property_id, + LongSetPtr result) { LoggerD("Entered"); int error_code = contacts_query_set_filter(query, filter); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (!status) return status; contacts_list_h list = nullptr; error_code = contacts_db_get_records_with_query(query, 0, 0, &list); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (!status) return status; - ContactUtil::ContactsListHPtr list_ptr(&list, - ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr list_ptr(&list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(list, &record_count); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (!status) return status; contacts_list_first(*list_ptr); for (int i = 0; i < record_count; ++i) { contacts_record_h record = nullptr; error_code = contacts_list_get_current_record_p(list, &record); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_list_get_current_record_p"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_current_record_p"); if (!status) return status; int value = 0; error_code = contacts_record_get_int(record, property_id, &value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_record_get_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_record_get_int"); if (!status) return status; result->insert(value); @@ -704,8 +756,7 @@ common::PlatformResult ContactSearchEngine::GetQueryResults( } PlatformResult ContactSearchEngine::QueryAttributeBool( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool match_value) { + const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool match_value) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -716,24 +767,19 @@ PlatformResult ContactSearchEngine::QueryAttributeBool( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); error_code = contacts_filter_add_bool(filter, property_id, match_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (!status) return status; return GetQueryResults(query, filter, property_contact_id, result); @@ -752,24 +798,19 @@ PlatformResult ContactSearchEngine::QueryAttributeInt( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); error_code = contacts_filter_add_int(filter, property_id, match, match_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; return GetQueryResults(query, filter, property_contact_id, result); @@ -788,38 +829,31 @@ PlatformResult ContactSearchEngine::QueryAttributeString( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); - if (_contacts_number.number == property_id - && CONTACTS_MATCH_CONTAINS == match) { + if (_contacts_number.number == property_id && CONTACTS_MATCH_CONTAINS == match) { property_id = _contacts_number.normalized_number; } error_code = contacts_filter_add_str(filter, property_id, match, match_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (!status) return status; return GetQueryResults(query, filter, property_contact_id, result); } PlatformResult ContactSearchEngine::QueryAttributeDate( - const std::string& attr_name, - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - contacts_match_int_flag_e match, int match_value) { + const std::string& attr_name, const FilterPropertyStruct& attribute_properties, + LongSetPtr result, contacts_match_int_flag_e match, int match_value) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -830,52 +864,38 @@ PlatformResult ContactSearchEngine::QueryAttributeDate( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); - error_code = contacts_filter_add_int(filter, property_id, match, - match_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = contacts_filter_add_int(filter, property_id, match, match_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; if ("birthday" == attr_name) { - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, _contacts_event.type, - CONTACTS_MATCH_EQUAL, + error_code = contacts_filter_add_int(filter, _contacts_event.type, CONTACTS_MATCH_EQUAL, CONTACTS_EVENT_TYPE_BIRTH); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } else if ("anniversaries.date" == attr_name) { - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, _contacts_event.type, - CONTACTS_MATCH_EQUAL, + error_code = contacts_filter_add_int(filter, _contacts_event.type, CONTACTS_MATCH_EQUAL, CONTACTS_EVENT_TYPE_ANNIVERSARY); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; } @@ -883,10 +903,8 @@ PlatformResult ContactSearchEngine::QueryAttributeDate( } PlatformResult ContactSearchEngine::QueryAttributeRangeBool( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, - bool initial_value, bool end_value_is_set, - bool end_value) { + const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool initial_value_is_set, + bool initial_value, bool end_value_is_set, bool end_value) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -897,47 +915,39 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeBool( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); if (initial_value_is_set && end_value_is_set) { if (initial_value == end_value) { if (initial_value) { error_code = contacts_filter_add_bool(filter, property_id, true); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (!status) return status; } else if (!end_value) { error_code = contacts_filter_add_bool(filter, property_id, false); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (!status) return status; } } } else if (initial_value_is_set) { if (initial_value) { error_code = contacts_filter_add_bool(filter, property_id, true); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (!status) return status; } } else if (end_value_is_set) { if (!end_value) { error_code = contacts_filter_add_bool(filter, property_id, false); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_bool"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_bool"); if (!status) return status; } } @@ -946,8 +956,7 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeBool( } PlatformResult ContactSearchEngine::QueryAttributeRangeInt( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, + const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool initial_value_is_set, int initial_value, bool end_value_is_set, int end_value) { LoggerD("Entered"); @@ -959,69 +968,52 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeInt( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); if (initial_value_is_set && end_value_is_set) { contacts_filter_h sub_filter = nullptr; error_code = contacts_filter_create(view_uri, &sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, ContactUtil::ContactsFilterDeleter); error_code = contacts_filter_add_int(sub_filter, property_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, - initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; - error_code = contacts_filter_add_operator(sub_filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(sub_filter, property_id, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, + error_code = contacts_filter_add_int(sub_filter, property_id, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; error_code = contacts_filter_add_filter(filter, sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_filter"); if (!status) return status; } else if (initial_value_is_set) { - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, + error_code = contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } else if (end_value_is_set) { - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, - end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } @@ -1029,8 +1021,8 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeInt( } PlatformResult ContactSearchEngine::QueryAttributeRangeString( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - const char* initial_value, const char* end_value) { + const FilterPropertyStruct& attribute_properties, LongSetPtr result, const char* initial_value, + const char* end_value) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -1041,67 +1033,51 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeString( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); if (initial_value && end_value) { contacts_filter_h sub_filter = nullptr; error_code = contacts_filter_create(view_uri, &sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr sub_filter_ptr(sub_filter, ContactUtil::ContactsFilterDeleter); - error_code = contacts_filter_add_str(sub_filter, property_id, - CONTACTS_MATCH_STARTSWITH, - initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = + contacts_filter_add_str(sub_filter, property_id, CONTACTS_MATCH_STARTSWITH, initial_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (!status) return status; - error_code = contacts_filter_add_operator(sub_filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(sub_filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_str(sub_filter, property_id, - CONTACTS_MATCH_ENDSWITH, end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = + contacts_filter_add_str(sub_filter, property_id, CONTACTS_MATCH_ENDSWITH, end_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (!status) return status; error_code = contacts_filter_add_filter(filter, sub_filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_filter"); if (!status) return status; } else if (initial_value) { - error_code = contacts_filter_add_str(filter, property_id, - CONTACTS_MATCH_STARTSWITH, - initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = + contacts_filter_add_str(filter, property_id, CONTACTS_MATCH_STARTSWITH, initial_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (!status) return status; } else if (end_value) { - error_code = contacts_filter_add_str(filter, property_id, - CONTACTS_MATCH_ENDSWITH, end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_str"); + error_code = contacts_filter_add_str(filter, property_id, CONTACTS_MATCH_ENDSWITH, end_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_str"); if (!status) return status; } @@ -1109,10 +1085,9 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeString( } PlatformResult ContactSearchEngine::QueryAttributeRangeDate( - const std::string& attr_name, - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, int initial_value, bool end_value_is_set, - int end_value) { + const std::string& attr_name, const FilterPropertyStruct& attribute_properties, + LongSetPtr result, bool initial_value_is_set, int initial_value, bool end_value_is_set, + int end_value) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -1123,91 +1098,69 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeDate( contacts_filter_h filter = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); if (initial_value_is_set && end_value_is_set) { - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, + error_code = contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, - end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } else if (initial_value_is_set) { - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, + error_code = contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_GREATER_THAN_OR_EQUAL, initial_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } else if (end_value_is_set) { - error_code = contacts_filter_add_int(filter, property_id, - CONTACTS_MATCH_LESS_THAN_OR_EQUAL, - end_value); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(filter, property_id, CONTACTS_MATCH_LESS_THAN_OR_EQUAL, end_value); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } if ("birthday" == attr_name) { - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, _contacts_event.type, - CONTACTS_MATCH_EQUAL, + error_code = contacts_filter_add_int(filter, _contacts_event.type, CONTACTS_MATCH_EQUAL, CONTACTS_EVENT_TYPE_BIRTH); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } else if ("anniversaries.date" == attr_name) { - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_AND); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, _contacts_event.type, - CONTACTS_MATCH_EQUAL, + error_code = contacts_filter_add_int(filter, _contacts_event.type, CONTACTS_MATCH_EQUAL, CONTACTS_EVENT_TYPE_ANNIVERSARY); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } return GetQueryResults(query, filter, property_contact_id, result); } -PlatformResult ContactSearchEngine::SortContacts( - const FilterPropertyStruct& attribute_properties, LongVectorPtr result, - bool is_ascending, LongSetPtr ids) { +PlatformResult ContactSearchEngine::SortContacts(const FilterPropertyStruct& attribute_properties, + LongVectorPtr result, bool is_ascending, + LongSetPtr ids) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -1219,65 +1172,52 @@ PlatformResult ContactSearchEngine::SortContacts( contacts_list_h list = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_filter_create(view_uri, &filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_create"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_create"); if (!status) return status; - ContactUtil::ContactsFilterPtr filter_ptr(filter, - ContactUtil::ContactsFilterDeleter); + ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); auto iter = ids->begin(); if (ids->end() != iter) { - error_code = contacts_filter_add_int(filter, property_contact_id, - CONTACTS_MATCH_EQUAL, *iter); + error_code = contacts_filter_add_int(filter, property_contact_id, CONTACTS_MATCH_EQUAL, *iter); if (CONTACTS_ERROR_NONE != error_code) { LoggerW("contacts_filter_add_int() failed: %d", error_code); } for (; iter != ids->end(); ++iter) { - error_code = contacts_filter_add_operator(filter, - CONTACTS_FILTER_OPERATOR_OR); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_operator"); + error_code = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_OR); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_operator"); if (!status) return status; - error_code = contacts_filter_add_int(filter, property_contact_id, - CONTACTS_MATCH_EQUAL, *iter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_filter_add_int"); + error_code = + contacts_filter_add_int(filter, property_contact_id, CONTACTS_MATCH_EQUAL, *iter); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_filter_add_int"); if (!status) return status; } } error_code = contacts_query_set_sort(query, property_id, is_ascending); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_sort"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_sort"); if (!status) return status; error_code = contacts_query_set_filter(query, filter); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_filter"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); if (!status) return status; error_code = contacts_db_get_records_with_query(query, 0, 0, &list); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (!status) return status; - ContactUtil::ContactsListHPtr list_ptr(&list, - ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr list_ptr(&list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(list, &record_count); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (!status) return status; LongSet overlapping_ids; @@ -1311,9 +1251,8 @@ PlatformResult ContactSearchEngine::SortContacts( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ContactSearchEngine::SortContacts( - const FilterPropertyStruct& attribute_properties, LongVectorPtr result, - bool is_ascending) { +PlatformResult ContactSearchEngine::SortContacts(const FilterPropertyStruct& attribute_properties, + LongVectorPtr result, bool is_ascending) { LoggerD("Entered"); const char* view_uri = attribute_properties.view_uri; @@ -1324,30 +1263,24 @@ PlatformResult ContactSearchEngine::SortContacts( contacts_list_h list = nullptr; int error_code = contacts_query_create(view_uri, &query); - auto status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_create"); + auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_create"); if (!status) return status; - ContactUtil::ContactsQueryHPtr query_ptr(&query, - ContactUtil::ContactsQueryDeleter); + ContactUtil::ContactsQueryHPtr query_ptr(&query, ContactUtil::ContactsQueryDeleter); error_code = contacts_query_set_sort(query, property_id, is_ascending); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_query_set_sort"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_sort"); if (!status) return status; error_code = contacts_db_get_records_with_query(query, 0, 0, &list); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_db_get_records_with_query"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_db_get_records_with_query"); if (!status) return status; - ContactUtil::ContactsListHPtr list_ptr(&list, - ContactUtil::ContactsListDeleter); + ContactUtil::ContactsListHPtr list_ptr(&list, ContactUtil::ContactsListDeleter); int record_count = 0; error_code = contacts_list_get_count(list, &record_count); - status = ContactUtil::ErrorChecker(error_code, - "Failed contacts_list_get_count"); + status = ContactUtil::ErrorChecker(error_code, "Failed contacts_list_get_count"); if (!status) return status; LongSet overlapping_ids; @@ -1381,8 +1314,7 @@ PlatformResult ContactSearchEngine::SortContacts( return PlatformResult(ErrorCode::NO_ERROR); } -void ContactSearchEngine::GetIntersection(LongSetPtrVectorPtr idSets, - LongSetPtr result) { +void ContactSearchEngine::GetIntersection(LongSetPtrVectorPtr idSets, LongSetPtr result) { LongSetPtrVector::iterator i; if (idSets->size() == 0) { @@ -1394,8 +1326,7 @@ void ContactSearchEngine::GetIntersection(LongSetPtrVectorPtr idSets, } LongSetPtrVector::iterator minIter; - LongSetPtrVector::size_type minSize = std::numeric_limits< - LongSetPtrVector::size_type>::max(); + LongSetPtrVector::size_type minSize = std::numeric_limits::max(); for (i = idSets->begin(); i != idSets->end(); i++) { LongSetPtr idSet = *i; @@ -1432,8 +1363,7 @@ void ContactSearchEngine::GetIntersection(LongSetPtrVectorPtr idSets, } } -void ContactSearchEngine::GetUnion(LongSetPtrVectorPtr id_sets, - LongSetPtr result) { +void ContactSearchEngine::GetUnion(LongSetPtrVectorPtr id_sets, LongSetPtr result) { if (!id_sets->size()) { result = LongSetPtr(); return; diff --git a/src/contact/contact_search_engine.h b/src/contact/contact_search_engine.h index 6dcfbc8..8ee8e31 100644 --- a/src/contact/contact_search_engine.h +++ b/src/contact/contact_search_engine.h @@ -67,65 +67,57 @@ class ContactSearchEngine { typedef std::map PropertiesMap; - common::PlatformResult ApplyAttributeFilter( - const std::string& name, common::AttributeMatchFlag match_flag, - const picojson::value& match_value, int depth); - common::PlatformResult ApplyAttributeRangeFilter( - const std::string& name, const picojson::value& initial_value, - const picojson::value& end_value, int depth); - - common::PlatformResult GetQueryResults(contacts_query_h query, - contacts_filter_h filter, - unsigned int property_id, - LongSetPtr result); - - common::PlatformResult GetAllContactsSorted( - const FilterPropertyStruct& attribute_properties, bool is_ascending, - picojson::array* out); + common::PlatformResult ApplyAttributeFilter(const std::string& name, + common::AttributeMatchFlag match_flag, + const picojson::value& match_value, int depth); + common::PlatformResult ApplyAttributeRangeFilter(const std::string& name, + const picojson::value& initial_value, + const picojson::value& end_value, int depth); + + common::PlatformResult GetQueryResults(contacts_query_h query, contacts_filter_h filter, + unsigned int property_id, LongSetPtr result); + + common::PlatformResult GetAllContactsSorted(const FilterPropertyStruct& attribute_properties, + bool is_ascending, picojson::array* out); common::PlatformResult GetAllContacts(picojson::array* out); - template - common::PlatformResult GetContacts(Iterator begin, Iterator end, - picojson::array* out); - common::PlatformResult QueryAttributeBool( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool match_value); - common::PlatformResult QueryAttributeInt( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - contacts_match_int_flag_e match, int match_value); - common::PlatformResult QueryAttributeString( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - contacts_match_str_flag_e match, const char* match_value); - common::PlatformResult QueryAttributeDate( - const std::string& attr_name, - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - contacts_match_int_flag_e match, int match_value); - common::PlatformResult QueryAttributeRangeBool( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, bool initial_value, bool end_value_is_set, - bool end_value); - common::PlatformResult QueryAttributeRangeInt( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, int initial_value, bool end_value_is_set, - int end_value); - common::PlatformResult QueryAttributeRangeString( - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - const char* initial_value, const char* end_value); - common::PlatformResult QueryAttributeRangeDate( - const std::string& attrName, - const FilterPropertyStruct& attribute_properties, LongSetPtr result, - bool initial_value_is_set, int initial_value, bool end_value_is_set, - int end_value); - common::PlatformResult SortContacts( - const FilterPropertyStruct& attribute_properties, LongVectorPtr result, - bool is_ascending, LongSetPtr ids); - common::PlatformResult SortContacts( - const FilterPropertyStruct& attribute_properties, LongVectorPtr result, - bool is_ascending); + template + common::PlatformResult GetContacts(Iterator begin, Iterator end, picojson::array* out); + common::PlatformResult QueryAttributeBool(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, bool match_value); + common::PlatformResult QueryAttributeInt(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, contacts_match_int_flag_e match, + int match_value); + common::PlatformResult QueryAttributeString(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, contacts_match_str_flag_e match, + const char* match_value); + common::PlatformResult QueryAttributeDate(const std::string& attr_name, + const FilterPropertyStruct& attribute_properties, + LongSetPtr result, contacts_match_int_flag_e match, + int match_value); + common::PlatformResult QueryAttributeRangeBool(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, bool initial_value_is_set, + bool initial_value, bool end_value_is_set, + bool end_value); + common::PlatformResult QueryAttributeRangeInt(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, bool initial_value_is_set, + int initial_value, bool end_value_is_set, + int end_value); + common::PlatformResult QueryAttributeRangeString(const FilterPropertyStruct& attribute_properties, + LongSetPtr result, const char* initial_value, + const char* end_value); + common::PlatformResult QueryAttributeRangeDate(const std::string& attrName, + const FilterPropertyStruct& attribute_properties, + LongSetPtr result, bool initial_value_is_set, + int initial_value, bool end_value_is_set, + int end_value); + common::PlatformResult SortContacts(const FilterPropertyStruct& attribute_properties, + LongVectorPtr result, bool is_ascending, LongSetPtr ids); + common::PlatformResult SortContacts(const FilterPropertyStruct& attribute_properties, + LongVectorPtr result, bool is_ascending); void GetIntersection(LongSetPtrVectorPtr id_sets, LongSetPtr result); void GetUnion(LongSetPtrVectorPtr id_sets, LongSetPtr result); - static PropertiesMap s_properties_map_; long addressbook_id_; diff --git a/src/contact/contact_util.cc b/src/contact/contact_util.cc old mode 100755 new mode 100644 index 6251ee1..6dd2c1c --- a/src/contact/contact_util.cc +++ b/src/contact/contact_util.cc @@ -15,12 +15,12 @@ */ #include "contact/contact_util.h" +#include #include #include #include -#include -#include "common/converter.h" #include "common/assert.h" +#include "common/converter.h" #include "common/logger.h" namespace extension { @@ -39,11 +39,9 @@ static const std::string kSchema("file://"); PlatformResult VerifyLocalPath(const std::string& path) { // path should be either empty or point to existing local path - bool result = path.length() == 0 - || (path.length() > 0 && path[0] == '/' - && (access(path.c_str(), F_OK) == 0)); - return PlatformResult( - result ? ErrorCode::NO_ERROR : ErrorCode::INVALID_VALUES_ERR); + bool result = path.length() == 0 || + (path.length() > 0 && path[0] == '/' && (access(path.c_str(), F_OK) == 0)); + return PlatformResult(result ? ErrorCode::NO_ERROR : ErrorCode::INVALID_VALUES_ERR); } } // namespace @@ -64,8 +62,6 @@ std::string ConvertPathToUri(const std::string& str) { return kSchema + str; } - - void ContactsDeleter(contacts_record_h* contacts_record) { if (CONTACTS_ERROR_NONE != contacts_record_destroy(*contacts_record, true)) { LoggerE("failed to destroy contacts_record_h"); @@ -127,8 +123,7 @@ static const char kContactRelationshipTypeCustom[] = "CUSTOM"; static const char kContactRelationshipTypeAssistant[] = "ASSISTANT"; static const char kContactRelationshipTypeBrother[] = "BROTHER"; static const char kContactRelationshipTypeChild[] = "CHILD"; -static const char kContactRelationshipTypeDomesticPartner[] = - "DOMESTIC_PARTNER"; +static const char kContactRelationshipTypeDomesticPartner[] = "DOMESTIC_PARTNER"; static const char kContactRelationshipTypeFather[] = "FATHER"; static const char kContactRelationshipTypeFriend[] = "FRIEND"; static const char kContactRelationshipTypeManager[] = "MANAGER"; @@ -164,86 +159,75 @@ PlatformResult ErrorChecker(int err, const char* message) { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult GetStrFromRecord(contacts_record_h record, - unsigned int property_id, char** value) { +PlatformResult GetStrFromRecord(contacts_record_h record, unsigned int property_id, char** value) { LoggerD("Enter"); int err = contacts_record_get_str_p(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during getting contact record", - ("Error during getting contact record, error code: %i", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", + ("Error during getting contact record, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult GetIntFromRecord(contacts_record_h record, - unsigned int property_id, int* value) { +PlatformResult GetIntFromRecord(contacts_record_h record, unsigned int property_id, int* value) { LoggerD("Enter"); int err = contacts_record_get_int(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during getting contact record", - ("Error during getting contact record, error code: %i", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", + ("Error during getting contact record, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult GetBoolFromRecord(contacts_record_h record, - unsigned int property_id, bool* value) { +PlatformResult GetBoolFromRecord(contacts_record_h record, unsigned int property_id, bool* value) { LoggerD("Enter"); int err = contacts_record_get_bool(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during getting contact record", - ("Error during getting contact record, error code: %i", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", + ("Error during getting contact record, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SetStrInRecord(contacts_record_h record, - unsigned int property_id, const char* value) { +PlatformResult SetStrInRecord(contacts_record_h record, unsigned int property_id, + const char* value) { LoggerD("Enter"); int err = contacts_record_set_str(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during setting contact record", - ("Error during setting str contact record property, error code: %i", err)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error during setting contact record", + ("Error during setting str contact record property, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SetIntInRecord(contacts_record_h record, - unsigned int property_id, int value) { +PlatformResult SetIntInRecord(contacts_record_h record, unsigned int property_id, int value) { LoggerD("Enter"); int err = contacts_record_set_int(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during setting contact record", - ("Error during getting contact record, error code: %i", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during setting contact record", + ("Error during getting contact record, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SetBoolInRecord(contacts_record_h record, - unsigned int property_id, bool value) { +PlatformResult SetBoolInRecord(contacts_record_h record, unsigned int property_id, bool value) { LoggerD("Enter"); int err = contacts_record_set_bool(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error during setting contact record", - ("Error during getting contact record, error code: %i", err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during setting contact record", + ("Error during getting contact record, error code: %i", err)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, - unsigned int property_id) { +PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, unsigned int property_id) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -252,8 +236,7 @@ PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, } int record_count; - PlatformResult status = - GetNumberOfChildRecord(contacts_record, property_id, &record_count); + PlatformResult status = GetNumberOfChildRecord(contacts_record, property_id, &record_count); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -262,19 +245,16 @@ PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, for (int i = 0; i < record_count; ++i) { unsigned int actual_index = record_count - 1 - i; contacts_record_h phone_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, property_id, actual_index, &phone_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Error during getting phone record"); + int err = contacts_record_get_child_record_at_p(contacts_record, property_id, actual_index, + &phone_record); + PlatformResult status = ContactUtil::ErrorChecker(err, "Error during getting phone record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_remove_child_record(contacts_record, property_id, - phone_record); - status = - ContactUtil::ErrorChecker(err, "Error during getting phone record"); + err = contacts_record_remove_child_record(contacts_record, property_id, phone_record); + status = ContactUtil::ErrorChecker(err, "Error during getting phone record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -284,43 +264,36 @@ PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult GetNumberOfChildRecord(contacts_record_h contacts_record, - unsigned int property_id, +PlatformResult GetNumberOfChildRecord(contacts_record_h contacts_record, unsigned int property_id, int* child_count) { LoggerD("Enter"); Assert(child_count); - int err = contacts_record_get_child_record_count(contacts_record, property_id, - child_count); + int err = contacts_record_get_child_record_count(contacts_record, property_id, child_count); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Problem during getting child count"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Problem during getting child count"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactNameFromContactsRecord( - contacts_record_h contacts_record, JsonObject* out_ptr, - bool* is_contact_name) { +PlatformResult ImportContactNameFromContactsRecord(contacts_record_h contacts_record, + JsonObject* out_ptr, bool* is_contact_name) { LoggerD("Enter"); JsonObject& out = *out_ptr; if (!contacts_record) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record is null"); } int count = 0; - int err = contacts_record_get_child_record_count(contacts_record, - _contacts_contact.name, &count); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Contacts child record get count error"); + int err = contacts_record_get_child_record_count(contacts_record, _contacts_contact.name, &count); + PlatformResult status = ContactUtil::ErrorChecker(err, "Contacts child record get count error"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (count > 1) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "More than one ContactName for one Contact"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "More than one ContactName for one Contact"); } LoggerD("Contact name record count: %i", count); @@ -330,10 +303,9 @@ PlatformResult ImportContactNameFromContactsRecord( } contacts_record_h contact_name = nullptr; - err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.name, 0, &contact_name); - status = - ContactUtil::ErrorChecker(err, "Contacts name record get childerror"); + err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.name, 0, + &contact_name); + status = ContactUtil::ErrorChecker(err, "Contacts name record get childerror"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -345,90 +317,73 @@ PlatformResult ImportContactNameFromContactsRecord( // so it won't be protected by unique_ptr. char* char_value = nullptr; - status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.prefix, - &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.prefix, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("prefix", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("prefix", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.suffix, - &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.suffix, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("suffix", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("suffix", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.first, - &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.first, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("firstName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("firstName", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.addition, - &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.addition, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("middleName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("middleName", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.last, - &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.last, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("lastName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("lastName", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord( - contact_name, _contacts_name.phonetic_first, &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.phonetic_first, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("phoneticFirstName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("phoneticFirstName", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord( - contact_name, _contacts_name.phonetic_middle, &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.phonetic_middle, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("phoneticMiddleName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert( + std::make_pair("phoneticMiddleName", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord( - contact_name, _contacts_name.phonetic_last, &char_value); + status = ContactUtil::GetStrFromRecord(contact_name, _contacts_name.phonetic_last, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("phoneticLastName", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("phoneticLastName", char_value ? JsonValue{char_value} : JsonValue{})); - err = contacts_record_get_child_record_count( - contacts_record, _contacts_contact.nickname, &count); - status = - ContactUtil::ErrorChecker(err, "Contacts child record get count error"); + err = contacts_record_get_child_record_count(contacts_record, _contacts_contact.nickname, &count); + status = ContactUtil::ErrorChecker(err, "Contacts child record get count error"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -437,17 +392,15 @@ PlatformResult ImportContactNameFromContactsRecord( JsonArray nicknames; for (int i = 0; i < count; ++i) { contacts_record_h nickname = nullptr; - err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.nickname, i, &nickname); - status = ContactUtil::ErrorChecker( - err, "Contacts nicknames record get child error"); + err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.nickname, i, + &nickname); + status = ContactUtil::ErrorChecker(err, "Contacts nicknames record get child error"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - status = ContactUtil::GetStrFromRecord(nickname, _contacts_nickname.name, - &char_value); + status = ContactUtil::GetStrFromRecord(nickname, _contacts_nickname.name, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -463,9 +416,8 @@ PlatformResult ImportContactNameFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactNameToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactNameToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -474,13 +426,12 @@ PlatformResult ExportContactNameToContactsRecord( } contacts_record_h contact_name = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.name, 0, &contact_name); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.name, 0, + &contact_name); bool update = true; if (CONTACTS_ERROR_NONE != err && nullptr == contact_name) { err = contacts_record_create(_contacts_name._uri, &contact_name); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Contacts record create error"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Contacts record create error"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -492,18 +443,16 @@ PlatformResult ExportContactNameToContactsRecord( ContactsRecordHPtr contacts_name_ptr(&contact_name, ContactsDeleter); if (!IsNull(in, "prefix")) { - PlatformResult status = - ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.prefix, - FromJson(in, "prefix").c_str()); + PlatformResult status = ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.prefix, + FromJson(in, "prefix").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "suffix")) { - PlatformResult status = - ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.suffix, - FromJson(in, "suffix").c_str()); + PlatformResult status = ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.suffix, + FromJson(in, "suffix").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -511,17 +460,16 @@ PlatformResult ExportContactNameToContactsRecord( } if (!IsNull(in, "firstName")) { PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.first, - FromJson(in, "firstName").c_str()); + *contacts_name_ptr, _contacts_name.first, FromJson(in, "firstName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "middleName")) { - PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.addition, - FromJson(in, "middleName").c_str()); + PlatformResult status = + ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.addition, + FromJson(in, "middleName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -529,35 +477,34 @@ PlatformResult ExportContactNameToContactsRecord( } if (!IsNull(in, "lastName")) { PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.last, - FromJson(in, "lastName").c_str()); + *contacts_name_ptr, _contacts_name.last, FromJson(in, "lastName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "phoneticFirstName")) { - PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.phonetic_first, - FromJson(in, "phoneticFirstName").c_str()); + PlatformResult status = + ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.phonetic_first, + FromJson(in, "phoneticFirstName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "phoneticMiddleName")) { - PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.phonetic_middle, - FromJson(in, "phoneticMiddleName").c_str()); + PlatformResult status = + ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.phonetic_middle, + FromJson(in, "phoneticMiddleName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "phoneticLastName")) { - PlatformResult status = ContactUtil::SetStrInRecord( - *contacts_name_ptr, _contacts_name.phonetic_last, - FromJson(in, "phoneticLastName").c_str()); + PlatformResult status = + ContactUtil::SetStrInRecord(*contacts_name_ptr, _contacts_name.phonetic_last, + FromJson(in, "phoneticLastName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -567,10 +514,9 @@ PlatformResult ExportContactNameToContactsRecord( // contact_name is being added as a child to contacts_record // and in future will be destroyed by contacts_record's contactsDeleter if (!update) { - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.name, *contacts_name_ptr); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Contacts record add child error"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.name, + *contacts_name_ptr); + PlatformResult status = ContactUtil::ErrorChecker(err, "Contacts record add child error"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -614,10 +560,9 @@ PlatformResult ExportContactNameToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactEmailAddressFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactEmailAddressFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -627,15 +572,15 @@ PlatformResult ImportContactEmailAddressFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.email, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.email, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* email = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_email.email, &email); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_email.email, &email); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -647,8 +592,7 @@ PlatformResult ImportContactEmailAddressFromContactsRecord( out.insert(std::make_pair("email", JsonValue{email})); bool is_default = false; - status = ContactUtil::GetBoolFromRecord( - child_record, _contacts_email.is_default, &is_default); + status = ContactUtil::GetBoolFromRecord(child_record, _contacts_email.is_default, &is_default); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -657,8 +601,7 @@ PlatformResult ImportContactEmailAddressFromContactsRecord( out.insert(std::make_pair("isDefault", JsonValue{is_default})); char* label = nullptr; - status = ContactUtil::GetStrFromRecord(child_record, _contacts_email.label, - &label); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_email.label, &label); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -667,8 +610,7 @@ PlatformResult ImportContactEmailAddressFromContactsRecord( out.insert(std::make_pair("label", label ? JsonValue{label} : JsonValue{})); int type = 0; - status = - ContactUtil::GetIntFromRecord(child_record, _contacts_email.type, &type); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_email.type, &type); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -697,9 +639,8 @@ PlatformResult ImportContactEmailAddressFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactEmailAddressToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactEmailAddressToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); contacts_record_h c_email_record_h = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -709,8 +650,8 @@ PlatformResult ExportContactEmailAddressToContactsRecord( } int err = contacts_record_create(_contacts_email._uri, &c_email_record_h); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Failed to create email record in database"); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Failed to create email record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -718,26 +659,23 @@ PlatformResult ExportContactEmailAddressToContactsRecord( ContactsRecordHPtr record(&c_email_record_h, ContactsDeleter); - status = - ContactUtil::SetStrInRecord(c_email_record_h, _contacts_email.email, - FromJson(in, "email").c_str()); + status = ContactUtil::SetStrInRecord(c_email_record_h, _contacts_email.email, + FromJson(in, "email").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - status = - ContactUtil::SetBoolInRecord(c_email_record_h, _contacts_email.is_default, - FromJson(in, "isDefault")); + status = ContactUtil::SetBoolInRecord(c_email_record_h, _contacts_email.is_default, + FromJson(in, "isDefault")); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(c_email_record_h, _contacts_email.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(c_email_record_h, _contacts_email.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -759,17 +697,15 @@ PlatformResult ExportContactEmailAddressToContactsRecord( type_to_set |= CONTACTS_EMAIL_TYPE_HOME; } } - status = ContactUtil::SetIntInRecord(c_email_record_h, _contacts_email.type, - type_to_set); + status = ContactUtil::SetIntInRecord(c_email_record_h, _contacts_email.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.email, c_email_record_h); - status = - ContactUtil::ErrorChecker(err, "Fail to save email record into database"); + err = + contacts_record_add_child_record(contacts_record, _contacts_contact.email, c_email_record_h); + status = ContactUtil::ErrorChecker(err, "Fail to save email record into database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -781,10 +717,8 @@ PlatformResult ExportContactEmailAddressToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactPhoneNumberFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactPhoneNumberFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; contacts_record_h child_record = nullptr; @@ -794,15 +728,15 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord( return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record is null"); } - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.number, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.number, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* phone = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_number.number, &phone); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_number.number, &phone); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -811,8 +745,7 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord( out.insert(std::make_pair("number", JsonValue{phone})); bool is_default = false; - status = ContactUtil::GetBoolFromRecord( - child_record, _contacts_number.is_default, &is_default); + status = ContactUtil::GetBoolFromRecord(child_record, _contacts_number.is_default, &is_default); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -820,8 +753,7 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord( out.insert(std::make_pair("isDefault", JsonValue{is_default})); int type = 0; - status = - ContactUtil::GetIntFromRecord(child_record, _contacts_number.type, &type); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_number.type, &type); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -882,8 +814,7 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord( out["types"] = picojson::value(types); char* label = nullptr; - status = ContactUtil::GetStrFromRecord(child_record, _contacts_number.label, - &label); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_number.label, &label); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -894,9 +825,8 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactPhoneNumberToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactPhoneNumberToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); contacts_record_h phone_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -906,8 +836,7 @@ PlatformResult ExportContactPhoneNumberToContactsRecord( } int err = contacts_record_create(_contacts_number._uri, &phone_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create phone_record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create phone_record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -915,26 +844,23 @@ PlatformResult ExportContactPhoneNumberToContactsRecord( ContactsRecordHPtr record(&phone_record, ContactsDeleter); - status = - ContactUtil::SetStrInRecord(phone_record, _contacts_number.number, - FromJson(in, "number").c_str()); + status = ContactUtil::SetStrInRecord(phone_record, _contacts_number.number, + FromJson(in, "number").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - status = - ContactUtil::SetBoolInRecord(phone_record, _contacts_number.is_default, - FromJson(in, "isDefault")); + status = ContactUtil::SetBoolInRecord(phone_record, _contacts_number.is_default, + FromJson(in, "isDefault")); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(phone_record, _contacts_address.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(phone_record, _contacts_address.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -982,17 +908,14 @@ PlatformResult ExportContactPhoneNumberToContactsRecord( } } - status = ContactUtil::SetIntInRecord(phone_record, _contacts_number.type, - type_to_set); + status = ContactUtil::SetIntInRecord(phone_record, _contacts_number.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.number, phone_record); - status = ContactUtil::ErrorChecker( - err, "Fail to set number value to phone_record"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.number, phone_record); + status = ContactUtil::ErrorChecker(err, "Fail to set number value to phone_record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1004,10 +927,9 @@ PlatformResult ExportContactPhoneNumberToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactOrganizationFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactOrganizationFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -1017,71 +939,60 @@ PlatformResult ImportContactOrganizationFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.company, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.company, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* char_value = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_company.name, &char_value); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_company.name, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("name", char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("name", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord( - child_record, _contacts_company.department, &char_value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.department, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("department", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("department", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord( - child_record, _contacts_company.job_title, &char_value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.job_title, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("title", - char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("title", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.role, - &char_value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.role, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("role", char_value ? JsonValue{char_value} : JsonValue{})); + out.insert(std::make_pair("role", char_value ? JsonValue{char_value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.logo, - &char_value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_company.logo, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair( - "logoURI", - char_value ? JsonValue{ConvertPathToUri(char_value)} : JsonValue{})); + out.insert(std::make_pair("logoURI", + char_value ? JsonValue{ConvertPathToUri(char_value)} : JsonValue{})); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactOrganizationToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactOrganizationToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1091,8 +1002,8 @@ PlatformResult ExportContactOrganizationToContactsRecord( contacts_record_h organization_record = nullptr; int err = contacts_record_create(_contacts_company._uri, &organization_record); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Failed to create organization record in database"); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Failed to create organization record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1101,56 +1012,49 @@ PlatformResult ExportContactOrganizationToContactsRecord( ContactsRecordHPtr record(&organization_record, ContactsDeleter); if (!IsNull(in, "name")) { - status = - ContactUtil::SetStrInRecord(organization_record, _contacts_company.name, - FromJson(in, "name").c_str()); + status = ContactUtil::SetStrInRecord(organization_record, _contacts_company.name, + FromJson(in, "name").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "department")) { - status = ContactUtil::SetStrInRecord( - organization_record, _contacts_company.department, - FromJson(in, "department").c_str()); + status = ContactUtil::SetStrInRecord(organization_record, _contacts_company.department, + FromJson(in, "department").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "title")) { - status = ContactUtil::SetStrInRecord( - organization_record, _contacts_company.job_title, - FromJson(in, "title").c_str()); + status = ContactUtil::SetStrInRecord(organization_record, _contacts_company.job_title, + FromJson(in, "title").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "role")) { - status = - ContactUtil::SetStrInRecord(organization_record, _contacts_company.role, - FromJson(in, "role").c_str()); + status = ContactUtil::SetStrInRecord(organization_record, _contacts_company.role, + FromJson(in, "role").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "logoURI")) { - std::string path = - ContactUtil::ConvertUriToPath(FromJson(in, "logoURI")); - status = ContactUtil::SetStrInRecord(organization_record, - _contacts_company.logo, path.c_str()); + std::string path = ContactUtil::ConvertUriToPath(FromJson(in, "logoURI")); + status = ContactUtil::SetStrInRecord(organization_record, _contacts_company.logo, path.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.company, organization_record); - status = ContactUtil::ErrorChecker( - err, "Fail to set company value to child_record"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.company, + organization_record); + status = ContactUtil::ErrorChecker(err, "Fail to set company value to child_record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1162,10 +1066,8 @@ PlatformResult ExportContactOrganizationToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactWebSiteFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactWebSiteFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -1175,43 +1077,38 @@ PlatformResult ImportContactWebSiteFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.url, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.url, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* char_value = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_url.url, &char_value); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_url.url, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair(std::string("url"), - picojson::value(char_value ? char_value : ""))); + out.insert(std::make_pair(std::string("url"), picojson::value(char_value ? char_value : ""))); int type = 0; - status = - ContactUtil::GetIntFromRecord(child_record, _contacts_url.type, &type); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_url.type, &type); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair(std::string("type"), - picojson::value((CONTACTS_URL_TYPE_HOME == type) - ? kContactWebSiteTypeHomePage - : kContactWebSiteTypeBlog))); + out.insert(std::make_pair(std::string("type"), picojson::value((CONTACTS_URL_TYPE_HOME == type) + ? kContactWebSiteTypeHomePage + : kContactWebSiteTypeBlog))); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactWebSiteToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactWebSiteToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1232,8 +1129,8 @@ PlatformResult ExportContactWebSiteToContactsRecord( contacts_record_h website_record_h = nullptr; int err = contacts_record_create(_contacts_url._uri, &website_record_h); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Fail to create website record in database."); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Fail to create website record in database."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1241,29 +1138,24 @@ PlatformResult ExportContactWebSiteToContactsRecord( ContactsRecordHPtr record(&website_record_h, ContactsDeleter); - status = ContactUtil::SetStrInRecord(website_record_h, _contacts_url.url, - url.c_str()); + status = ContactUtil::SetStrInRecord(website_record_h, _contacts_url.url, url.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - int type_to_set = - (FromJson(in, "type") == kContactWebSiteTypeHomePage) - ? CONTACTS_URL_TYPE_HOME - : CONTACTS_URL_TYPE_WORK; + int type_to_set = (FromJson(in, "type") == kContactWebSiteTypeHomePage) + ? CONTACTS_URL_TYPE_HOME + : CONTACTS_URL_TYPE_WORK; - status = ContactUtil::SetIntInRecord(website_record_h, _contacts_url.type, - type_to_set); + status = ContactUtil::SetIntInRecord(website_record_h, _contacts_url.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record(contacts_record, _contacts_contact.url, - website_record_h); - status = ContactUtil::ErrorChecker( - err, "Problem during saving WebSite urls into database."); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.url, website_record_h); + status = ContactUtil::ErrorChecker(err, "Problem during saving WebSite urls into database."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1275,10 +1167,9 @@ PlatformResult ExportContactWebSiteToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactAnniversariesFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr, - bool* ret) { - +PlatformResult ImportContactAnniversariesFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject* out_ptr, + bool* ret) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -1288,16 +1179,15 @@ PlatformResult ImportContactAnniversariesFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.event, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.event, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { *ret = false; return PlatformResult(ErrorCode::NO_ERROR); } int value = 0; - PlatformResult status = - ContactUtil::GetIntFromRecord(child_record, _contacts_event.type, &value); + PlatformResult status = ContactUtil::GetIntFromRecord(child_record, _contacts_event.type, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1309,8 +1199,7 @@ PlatformResult ImportContactAnniversariesFromContactsRecord( } if (CONTACTS_EVENT_TYPE_ANNIVERSARY == value) { - status = ContactUtil::GetIntFromRecord(child_record, _contacts_event.date, - &value); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_event.date, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1319,8 +1208,7 @@ PlatformResult ImportContactAnniversariesFromContactsRecord( out.insert(std::make_pair("date", JsonValue{static_cast(value)})); char* label = nullptr; - status = ContactUtil::GetStrFromRecord(child_record, _contacts_event.label, - &label); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_event.label, &label); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1333,9 +1221,8 @@ PlatformResult ImportContactAnniversariesFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactAnniversariesToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactAnniversariesToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1350,8 +1237,8 @@ PlatformResult ExportContactAnniversariesToContactsRecord( contacts_record_h anniversary_record = nullptr; int err = contacts_record_create(_contacts_event._uri, &anniversary_record); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Failed to create anniversary record in database"); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Failed to create anniversary record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1366,27 +1253,24 @@ PlatformResult ExportContactAnniversariesToContactsRecord( return status; } - status = ContactUtil::SetIntInRecord(anniversary_record, _contacts_event.date, - date); + status = ContactUtil::SetIntInRecord(anniversary_record, _contacts_event.date, date); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(anniversary_record, _contacts_event.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(anniversary_record, _contacts_event.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.event, anniversary_record); - status = ContactUtil::ErrorChecker( - err, "Fail to save anniversary record in database"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.event, + anniversary_record); + status = ContactUtil::ErrorChecker(err, "Fail to save anniversary record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1398,10 +1282,9 @@ PlatformResult ExportContactAnniversariesToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactRelationshipFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactRelationshipFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -1411,15 +1294,15 @@ PlatformResult ImportContactRelationshipFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.relationship, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.relationship, + index, &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* relative = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_relationship.name, &relative); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_relationship.name, &relative); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1429,109 +1312,102 @@ PlatformResult ImportContactRelationshipFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } - out.insert(std::make_pair(std::string("relativeName"), - picojson::value(JsonString{relative}))); + out.insert(std::make_pair(std::string("relativeName"), picojson::value(JsonString{relative}))); int type = 0; - status = ContactUtil::GetIntFromRecord(child_record, - _contacts_relationship.type, &type); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_relationship.type, &type); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - std::pair value_pair; + std::pair value_pair; switch (type) { case CONTACTS_RELATIONSHIP_TYPE_CUSTOM: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeCustom})); + picojson::value(JsonString{kContactRelationshipTypeCustom})); break; case CONTACTS_RELATIONSHIP_TYPE_ASSISTANT: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeAssistant})); + picojson::value(JsonString{kContactRelationshipTypeAssistant})); break; case CONTACTS_RELATIONSHIP_TYPE_BROTHER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeBrother})); + picojson::value(JsonString{kContactRelationshipTypeBrother})); break; case CONTACTS_RELATIONSHIP_TYPE_CHILD: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeChild})); + picojson::value(JsonString{kContactRelationshipTypeChild})); break; case CONTACTS_RELATIONSHIP_TYPE_DOMESTIC_PARTNER: - value_pair = std::make_pair( - std::string("type"), - picojson::value( - JsonString{kContactRelationshipTypeDomesticPartner})); + value_pair = + std::make_pair(std::string("type"), + picojson::value(JsonString{kContactRelationshipTypeDomesticPartner})); break; case CONTACTS_RELATIONSHIP_TYPE_FATHER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeFather})); + picojson::value(JsonString{kContactRelationshipTypeFather})); break; case CONTACTS_RELATIONSHIP_TYPE_FRIEND: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeFriend})); + picojson::value(JsonString{kContactRelationshipTypeFriend})); break; case CONTACTS_RELATIONSHIP_TYPE_MANAGER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeManager})); + picojson::value(JsonString{kContactRelationshipTypeManager})); break; case CONTACTS_RELATIONSHIP_TYPE_MOTHER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeMother})); + picojson::value(JsonString{kContactRelationshipTypeMother})); break; case CONTACTS_RELATIONSHIP_TYPE_PARENT: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeParent})); + picojson::value(JsonString{kContactRelationshipTypeParent})); break; case CONTACTS_RELATIONSHIP_TYPE_PARTNER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypePartner})); + picojson::value(JsonString{kContactRelationshipTypePartner})); break; case CONTACTS_RELATIONSHIP_TYPE_REFERRED_BY: - value_pair = std::make_pair( - std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeReferredBy})); + value_pair = std::make_pair(std::string("type"), + picojson::value(JsonString{kContactRelationshipTypeReferredBy})); break; case CONTACTS_RELATIONSHIP_TYPE_RELATIVE: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeRelative})); + picojson::value(JsonString{kContactRelationshipTypeRelative})); break; case CONTACTS_RELATIONSHIP_TYPE_SISTER: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeSister})); + picojson::value(JsonString{kContactRelationshipTypeSister})); break; case CONTACTS_RELATIONSHIP_TYPE_SPOUSE: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeSpouse})); + picojson::value(JsonString{kContactRelationshipTypeSpouse})); break; case CONTACTS_RELATIONSHIP_TYPE_OTHER: default: value_pair = std::make_pair(std::string("type"), - picojson::value(JsonString{kContactRelationshipTypeOther})); + picojson::value(JsonString{kContactRelationshipTypeOther})); break; } out.insert(value_pair); char* label = nullptr; - status = ContactUtil::GetStrFromRecord(child_record, - _contacts_relationship.label, &label); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_relationship.label, &label); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair(std::string("label"), - picojson::value(label ? JsonValue{label} : JsonValue{}))); + out.insert(std::make_pair(std::string("label"), + picojson::value(label ? JsonValue{label} : JsonValue{}))); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactRelationshipToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactRelationshipToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1541,8 +1417,7 @@ PlatformResult ExportContactRelationshipToContactsRecord( contacts_record_h child_record = nullptr; int err = contacts_record_create(_contacts_relationship._uri, &child_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1550,9 +1425,8 @@ PlatformResult ExportContactRelationshipToContactsRecord( ContactsRecordHPtr record(&child_record, ContactsDeleter); - status = ContactUtil::SetStrInRecord( - child_record, _contacts_relationship.name, - FromJson(in, "relativeName").c_str()); + status = ContactUtil::SetStrInRecord(child_record, _contacts_relationship.name, + FromJson(in, "relativeName").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1594,27 +1468,24 @@ PlatformResult ExportContactRelationshipToContactsRecord( type_to_set = CONTACTS_MESSENGER_TYPE_OTHER; } - status = ContactUtil::SetIntInRecord( - child_record, _contacts_relationship.type, type_to_set); + status = ContactUtil::SetIntInRecord(child_record, _contacts_relationship.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(child_record, _contacts_relationship.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(child_record, _contacts_relationship.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.relationship, child_record); - status = ContactUtil::ErrorChecker( - err, "Fail to set number value to child_record"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.relationship, + child_record); + status = ContactUtil::ErrorChecker(err, "Fail to set number value to child_record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1625,9 +1496,8 @@ PlatformResult ExportContactRelationshipToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactExtensionFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { +PlatformResult ImportContactExtensionFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject* out_ptr) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1636,28 +1506,28 @@ PlatformResult ImportContactExtensionFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.extension, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.extension, + index, &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } int data1 = 0; - PlatformResult status = ContactUtil::GetIntFromRecord(child_record, - _contacts_extension.data1, &data1); + PlatformResult status = + ContactUtil::GetIntFromRecord(child_record, _contacts_extension.data1, &data1); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out_ptr->insert(std::make_pair(std::string("data1"), - picojson::value(data1 ? JsonValue{static_cast(data1)} : JsonValue{}))); + out_ptr->insert( + std::make_pair(std::string("data1"), + picojson::value(data1 ? JsonValue{static_cast(data1)} : JsonValue{}))); auto insert_data = [&](unsigned int id, const std::string& label) { char* data = nullptr; status = ContactUtil::GetStrFromRecord(child_record, id, &data); if (status && data) { - out_ptr->insert(std::make_pair(std::string(label), - picojson::value(JsonString{data}))); + out_ptr->insert(std::make_pair(std::string(label), picojson::value(JsonString{data}))); } }; @@ -1730,8 +1600,8 @@ PlatformResult ImportContactExtensionFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactExtensionToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { +PlatformResult ExportContactExtensionToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1742,8 +1612,7 @@ PlatformResult ExportContactExtensionToContactsRecord( contacts_record_h child_record = nullptr; int err = contacts_record_create(_contacts_extension._uri, &child_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1751,8 +1620,8 @@ PlatformResult ExportContactExtensionToContactsRecord( ContactsRecordHPtr record(&child_record, ContactsDeleter); - status = ContactUtil::SetIntInRecord( - child_record, _contacts_extension.data1, static_cast(FromJson(in, "data1"))); + status = ContactUtil::SetIntInRecord(child_record, _contacts_extension.data1, + static_cast(FromJson(in, "data1"))); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1760,9 +1629,8 @@ PlatformResult ExportContactExtensionToContactsRecord( auto set_data = [&](int id, const char* label) { if (!IsNull(in, label)) { - status = ContactUtil::SetStrInRecord( - child_record, id, - FromJson(in, label).c_str()); + status = + ContactUtil::SetStrInRecord(child_record, id, FromJson(in, label).c_str()); } }; @@ -1832,10 +1700,9 @@ PlatformResult ExportContactExtensionToContactsRecord( return status; } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.extension, child_record); - status = ContactUtil::ErrorChecker( - err, "Fail to set number value to child_record"); + err = + contacts_record_add_child_record(contacts_record, _contacts_contact.extension, child_record); + status = ContactUtil::ErrorChecker(err, "Fail to set number value to child_record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1846,10 +1713,9 @@ PlatformResult ExportContactExtensionToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactInstantMessengerFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactInstantMessengerFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -1859,16 +1725,16 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.messenger, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.messenger, + index, &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { LoggerW("Skipping message with index %i. error code: %i", index, err); return PlatformResult(ErrorCode::NO_ERROR); } char* im_address = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_messenger.im_id, &im_address); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_messenger.im_id, &im_address); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1882,14 +1748,13 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord( out.insert(std::make_pair("imAddress", JsonValue{im_address})); int type = 0; - status = ContactUtil::GetIntFromRecord(child_record, _contacts_messenger.type, - &type); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_messenger.type, &type); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - std::pair value_pair; + std::pair value_pair; switch (type) { case CONTACTS_MESSENGER_TYPE_CUSTOM: value_pair = std::make_pair("type", JsonValue{kContactInstantMessageTypeCustom}); @@ -1904,8 +1769,7 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord( value_pair = std::make_pair("type", JsonValue{kContactInstantMessageTypeYahoo}); break; case CONTACTS_MESSENGER_TYPE_FACEBOOK: - value_pair = std::make_pair("type", - JsonValue{kContactInstantMessageTypeFacebook}); + value_pair = std::make_pair("type", JsonValue{kContactInstantMessageTypeFacebook}); break; case CONTACTS_MESSENGER_TYPE_ICQ: value_pair = std::make_pair("type", JsonValue{kContactInstantMessageTypeIcq}); @@ -1932,8 +1796,7 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord( } char* label = nullptr; - status = ContactUtil::GetStrFromRecord(child_record, - _contacts_messenger.label, &label); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_messenger.label, &label); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1944,9 +1807,8 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactInstantMessengerToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactInstantMessengerToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1956,8 +1818,7 @@ PlatformResult ExportContactInstantMessengerToContactsRecord( contacts_record_h child_record = nullptr; int err = contacts_record_create(_contacts_messenger._uri, &child_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create child_record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -1965,9 +1826,8 @@ PlatformResult ExportContactInstantMessengerToContactsRecord( ContactsRecordHPtr record(&child_record, ContactsDeleter); - status = ContactUtil::SetStrInRecord( - child_record, _contacts_messenger.im_id, - FromJson(in, "imAddress").c_str()); + status = ContactUtil::SetStrInRecord(child_record, _contacts_messenger.im_id, + FromJson(in, "imAddress").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2001,27 +1861,24 @@ PlatformResult ExportContactInstantMessengerToContactsRecord( type_to_set = CONTACTS_MESSENGER_TYPE_OTHER; } - status = ContactUtil::SetIntInRecord(child_record, _contacts_messenger.type, - type_to_set); + status = ContactUtil::SetIntInRecord(child_record, _contacts_messenger.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(child_record, _contacts_messenger.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(child_record, _contacts_messenger.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.messenger, child_record); - status = ContactUtil::ErrorChecker( - err, "Fail to set number value to child_record"); + err = + contacts_record_add_child_record(contacts_record, _contacts_contact.messenger, child_record); + status = ContactUtil::ErrorChecker(err, "Fail to set number value to child_record"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2032,10 +1889,8 @@ PlatformResult ExportContactInstantMessengerToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactAddressFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, - JsonObject* out_ptr) { - +PlatformResult ImportContactAddressFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -2045,66 +1900,57 @@ PlatformResult ImportContactAddressFromContactsRecord( } contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.address, index, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.address, index, + &child_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* value = nullptr; - PlatformResult status = ContactUtil::GetStrFromRecord( - child_record, _contacts_address.country, &value); + PlatformResult status = + ContactUtil::GetStrFromRecord(child_record, _contacts_address.country, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert(std::make_pair("country", value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.region, - &value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.region, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert(std::make_pair("region", value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, - _contacts_address.locality, &value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.locality, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert(std::make_pair("city", value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.street, - &value); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.street, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("streetAddress", value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, - _contacts_address.extended, &value); + out.insert(std::make_pair("streetAddress", value ? JsonValue{value} : JsonValue{})); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.extended, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("additionalInformation", - value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, - _contacts_address.postal_code, &value); + out.insert(std::make_pair("additionalInformation", value ? JsonValue{value} : JsonValue{})); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.postal_code, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("postalCode", value ? JsonValue{value} : JsonValue{})); - status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.label, - &value); + out.insert(std::make_pair("postalCode", value ? JsonValue{value} : JsonValue{})); + status = ContactUtil::GetStrFromRecord(child_record, _contacts_address.label, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2113,8 +1959,7 @@ PlatformResult ImportContactAddressFromContactsRecord( out.insert(std::make_pair("label", value ? JsonValue{value} : JsonValue{})); bool bool_value = false; - status = ContactUtil::GetBoolFromRecord( - child_record, _contacts_address.is_default, &bool_value); + status = ContactUtil::GetBoolFromRecord(child_record, _contacts_address.is_default, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2123,8 +1968,7 @@ PlatformResult ImportContactAddressFromContactsRecord( out.insert(std::make_pair("isDefault", JsonValue{bool_value})); int int_value = 0; - status = ContactUtil::GetIntFromRecord(child_record, _contacts_address.type, - &int_value); + status = ContactUtil::GetIntFromRecord(child_record, _contacts_address.type, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2152,9 +1996,8 @@ PlatformResult ImportContactAddressFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactAddressToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { - +PlatformResult ExportContactAddressToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2164,8 +2007,8 @@ PlatformResult ExportContactAddressToContactsRecord( contacts_record_h address_record = nullptr; int err = contacts_record_create(_contacts_address._uri, &address_record); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Failed to create address record in database"); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Failed to create address record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2174,72 +2017,64 @@ PlatformResult ExportContactAddressToContactsRecord( ContactsRecordHPtr record(&address_record, ContactsDeleter); if (!IsNull(in, "country")) { - status = ContactUtil::SetStrInRecord( - address_record, _contacts_address.country, - FromJson(in, "country").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.country, + FromJson(in, "country").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "region")) { - status = - ContactUtil::SetStrInRecord(address_record, _contacts_address.region, - FromJson(in, "region").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.region, + FromJson(in, "region").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "city")) { - status = - ContactUtil::SetStrInRecord(address_record, _contacts_address.locality, - FromJson(in, "city").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.locality, + FromJson(in, "city").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "streetAddress")) { - status = ContactUtil::SetStrInRecord( - address_record, _contacts_address.street, - FromJson(in, "streetAddress").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.street, + FromJson(in, "streetAddress").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "additionalInformation")) { - status = ContactUtil::SetStrInRecord( - address_record, _contacts_address.extended, - FromJson(in, "additionalInformation").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.extended, + FromJson(in, "additionalInformation").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "postalCode")) { - status = ContactUtil::SetStrInRecord( - address_record, _contacts_address.postal_code, - FromJson(in, "postalCode").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.postal_code, + FromJson(in, "postalCode").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(in, "label")) { - status = - ContactUtil::SetStrInRecord(address_record, _contacts_address.label, - FromJson(in, "label").c_str()); + status = ContactUtil::SetStrInRecord(address_record, _contacts_address.label, + FromJson(in, "label").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } - status = - ContactUtil::SetBoolInRecord(address_record, _contacts_address.is_default, - FromJson(in, "isDefault")); + status = ContactUtil::SetBoolInRecord(address_record, _contacts_address.is_default, + FromJson(in, "isDefault")); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2260,17 +2095,15 @@ PlatformResult ExportContactAddressToContactsRecord( } } - status = ContactUtil::SetIntInRecord(address_record, _contacts_address.type, - type_to_set); + status = ContactUtil::SetIntInRecord(address_record, _contacts_address.type, type_to_set); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.address, address_record); - status = - ContactUtil::ErrorChecker(err, "Fail to save address record in database"); + err = + contacts_record_add_child_record(contacts_record, _contacts_contact.address, address_record); + status = ContactUtil::ErrorChecker(err, "Fail to save address record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2282,9 +2115,8 @@ PlatformResult ExportContactAddressToContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactNotesFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonValue* val) { - +PlatformResult ImportContactNotesFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonValue* val) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2293,15 +2125,14 @@ PlatformResult ImportContactNotesFromContactsRecord( } contacts_record_h notes_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.note, index, ¬es_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.note, index, + ¬es_record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { return PlatformResult(ErrorCode::NO_ERROR); } char* note = nullptr; - PlatformResult status = - ContactUtil::GetStrFromRecord(notes_record, _contacts_note.note, ¬e); + PlatformResult status = ContactUtil::GetStrFromRecord(notes_record, _contacts_note.note, ¬e); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2316,7 +2147,6 @@ PlatformResult ImportContactNotesFromContactsRecord( PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, const std::string& value) { - LoggerD("Enter"); contacts_record_h notes_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -2326,8 +2156,7 @@ PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, } int err = contacts_record_create(_contacts_note._uri, ¬es_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create note record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create note record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2335,17 +2164,14 @@ PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, ContactsRecordHPtr record(¬es_record, ContactsDeleter); - status = ContactUtil::SetStrInRecord(notes_record, _contacts_note.note, - value.c_str()); + status = ContactUtil::SetStrInRecord(notes_record, _contacts_note.note, value.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record(contacts_record, - _contacts_contact.note, notes_record); - status = - ContactUtil::ErrorChecker(err, "Fail to save note record in database"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.note, notes_record); + status = ContactUtil::ErrorChecker(err, "Fail to save note record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2357,9 +2183,8 @@ PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportGroupIdsFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonValue* val) { - +PlatformResult ImportGroupIdsFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonValue* val) { LoggerD("Enter"); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2369,8 +2194,8 @@ PlatformResult ImportGroupIdsFromContactsRecord( } contacts_record_h record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.group_relation, index, &record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.group_relation, + index, &record); if (CONTACTS_ERROR_NONE != err && CONTACTS_ERROR_NO_DATA != err) { // ignoring this record LoggerW("Skipping record with index %i. error code: %i", index, err); @@ -2393,9 +2218,7 @@ PlatformResult ImportGroupIdsFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, - int value) { - +PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, int value) { LoggerD("Enter"); contacts_record_h notes_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -2406,8 +2229,7 @@ PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, } int err = contacts_record_create(_contacts_group_relation._uri, ¬es_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to create note record in database"); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to create note record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2415,17 +2237,15 @@ PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, ContactsRecordHPtr record(¬es_record, ContactsDeleter); - status = ContactUtil::SetIntInRecord(notes_record, _contacts_group_relation.group_id, - value); + status = ContactUtil::SetIntInRecord(notes_record, _contacts_group_relation.group_id, value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - err = contacts_record_add_child_record(contacts_record, - _contacts_contact.group_relation, notes_record); - status = - ContactUtil::ErrorChecker(err, "Fail to save note record in database"); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.group_relation, + notes_record); + status = ContactUtil::ErrorChecker(err, "Fail to save note record in database"); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2437,9 +2257,8 @@ PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactFromContactsRecord( - contacts_record_h contacts_record, JsonObject* out_ptr) { - +PlatformResult ImportContactFromContactsRecord(contacts_record_h contacts_record, + JsonObject* out_ptr) { LoggerD("Enter"); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -2449,24 +2268,19 @@ PlatformResult ImportContactFromContactsRecord( } int id = 0; - PlatformResult status = - ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.id, &id); - if (status.IsError()) - { + PlatformResult status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.id, &id); + if (status.IsError()) { LoggerE("Fail: GetIntFromRecord"); return status; } out.insert(std::make_pair("id", JsonValue{std::to_string(id)})); - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_contact.address_book_id, &id); - if (status.IsError()) - { + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.address_book_id, &id); + if (status.IsError()) { LoggerE("Fail: GetIntFromRecord"); return status; } out.insert(std::make_pair("addressBookId", JsonValue{std::to_string(id)})); - status = ContactUtil::GetIntFromRecord(contacts_record, - _contacts_contact.person_id, &id); + status = ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.person_id, &id); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2475,8 +2289,8 @@ PlatformResult ImportContactFromContactsRecord( out.insert(std::make_pair("personId", JsonValue{std::to_string(id)})); bool is_favorite = false; - status = ContactUtil::GetBoolFromRecord( - contacts_record, _contacts_contact.is_favorite, &is_favorite); + status = + ContactUtil::GetBoolFromRecord(contacts_record, _contacts_contact.is_favorite, &is_favorite); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2485,21 +2299,19 @@ PlatformResult ImportContactFromContactsRecord( out.insert(std::make_pair("isFavorite", JsonValue{is_favorite})); int last_update = 0; - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_contact.changed_time, &last_update); + status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.changed_time, &last_update); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert(std::make_pair("lastUpdated", - JsonValue{static_cast(last_update)})); + out.insert(std::make_pair("lastUpdated", JsonValue{static_cast(last_update)})); //### ContactName: ### JsonObject name; bool is_contact_name; - status = ImportContactNameFromContactsRecord(contacts_record, &name, - &is_contact_name); + status = ImportContactNameFromContactsRecord(contacts_record, &name, &is_contact_name); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2508,42 +2320,33 @@ PlatformResult ImportContactFromContactsRecord( if (is_contact_name) { out.insert(std::make_pair(std::string("name"), picojson::value(name))); } else { - out.insert(std::make_pair(std::string("name"), - picojson::value(JsonValue{}))); + out.insert(std::make_pair(std::string("name"), picojson::value(JsonValue{}))); } - typedef PlatformResult (*ImportFunc)(contacts_record_h, unsigned int, - JsonObject*); + typedef PlatformResult (*ImportFunc)(contacts_record_h, unsigned int, JsonObject*); struct ImportData { const char* name; unsigned int property_id; ImportFunc import_func; }; ImportData imports[] = { - {"emails", _contacts_contact.email, - ImportContactEmailAddressFromContactsRecord}, - {"phoneNumbers", _contacts_contact.number, - ImportContactPhoneNumberFromContactsRecord}, - {"organizations", _contacts_contact.company, - ImportContactOrganizationFromContactsRecord}, + {"emails", _contacts_contact.email, ImportContactEmailAddressFromContactsRecord}, + {"phoneNumbers", _contacts_contact.number, ImportContactPhoneNumberFromContactsRecord}, + {"organizations", _contacts_contact.company, ImportContactOrganizationFromContactsRecord}, {"urls", _contacts_contact.url, ImportContactWebSiteFromContactsRecord}, - {"addresses", _contacts_contact.address, - ImportContactAddressFromContactsRecord}, - {"messengers", _contacts_contact.messenger, - ImportContactInstantMessengerFromContactsRecord}, + {"addresses", _contacts_contact.address, ImportContactAddressFromContactsRecord}, + {"messengers", _contacts_contact.messenger, ImportContactInstantMessengerFromContactsRecord}, {"relationships", _contacts_contact.relationship, - ImportContactRelationshipFromContactsRecord}, - {"extensions", _contacts_contact.extension, - ImportContactExtensionFromContactsRecord} - }; + ImportContactRelationshipFromContactsRecord}, + {"extensions", _contacts_contact.extension, ImportContactExtensionFromContactsRecord}}; for (auto& data : imports) { - JsonArray& array = out.insert(std::make_pair(data.name, - picojson::value(JsonArray()))).first->second.get(); + JsonArray& array = out.insert(std::make_pair(data.name, picojson::value(JsonArray()))) + .first->second.get(); int child_rec_count; - status = ContactUtil::GetNumberOfChildRecord( - contacts_record, data.property_id, &child_rec_count); + status = + ContactUtil::GetNumberOfChildRecord(contacts_record, data.property_id, &child_rec_count); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2558,12 +2361,12 @@ PlatformResult ImportContactFromContactsRecord( //### ContactAnniversary: ### JsonArray& anniversaries = - out.insert(std::make_pair(std::string("anniversaries"), - picojson::value(JsonArray()))).first->second.get(); + out.insert(std::make_pair(std::string("anniversaries"), picojson::value(JsonArray()))) + .first->second.get(); int child_rec_count; - status = ContactUtil::GetNumberOfChildRecord( - contacts_record, _contacts_contact.event, &child_rec_count); + status = ContactUtil::GetNumberOfChildRecord(contacts_record, _contacts_contact.event, + &child_rec_count); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2574,7 +2377,8 @@ PlatformResult ImportContactFromContactsRecord( JsonValue anniversary{JsonObject{}}; PlatformResult status = ImportContactAnniversariesFromContactsRecord( - contacts_record, static_cast(i), &anniversary.get(), &is_contact_anniv); + contacts_record, static_cast(i), &anniversary.get(), + &is_contact_anniv); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2583,17 +2387,16 @@ PlatformResult ImportContactFromContactsRecord( if (is_contact_anniv) { anniversaries.push_back(anniversary); } else { - out.insert(std::make_pair(std::string("birthday"), - picojson::value(anniversaries))); + out.insert(std::make_pair(std::string("birthday"), picojson::value(anniversaries))); } } //### m_notes: ### - JsonArray& notes = out.insert(std::make_pair(std::string("notes"), - picojson::value(JsonArray()))).first->second.get(); + JsonArray& notes = out.insert(std::make_pair(std::string("notes"), picojson::value(JsonArray()))) + .first->second.get(); - status = ContactUtil::GetNumberOfChildRecord( - contacts_record, _contacts_contact.note, &child_rec_count); + status = ContactUtil::GetNumberOfChildRecord(contacts_record, _contacts_contact.note, + &child_rec_count); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2602,7 +2405,8 @@ PlatformResult ImportContactFromContactsRecord( for (int i = 0; i < child_rec_count; ++i) { JsonValue val{JsonObject{}}; - status = ImportContactNotesFromContactsRecord(contacts_record, static_cast(i), &val); + status = + ImportContactNotesFromContactsRecord(contacts_record, static_cast(i), &val); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2616,60 +2420,52 @@ PlatformResult ImportContactFromContactsRecord( { char* value = nullptr; - status = ContactUtil::GetStrFromRecord( - contacts_record, _contacts_contact.image_thumbnail_path, &value); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_contact.image_thumbnail_path, + &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert( - std::make_pair( - "photoURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + std::make_pair("photoURI", value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); value = nullptr; - status = ContactUtil::GetStrFromRecord( - contacts_record, _contacts_contact.ringtone_path, &value); + status = + ContactUtil::GetStrFromRecord(contacts_record, _contacts_contact.ringtone_path, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert( - std::make_pair( - "ringtoneURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + std::make_pair("ringtoneURI", value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); value = nullptr; - status = ContactUtil::GetStrFromRecord( - contacts_record, _contacts_contact.message_alert, &value); + status = + ContactUtil::GetStrFromRecord(contacts_record, _contacts_contact.message_alert, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair( - "messageAlertURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + out.insert(std::make_pair("messageAlertURI", + value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); value = nullptr; - status = ContactUtil::GetStrFromRecord(contacts_record, - _contacts_contact.vibration, &value); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_contact.vibration, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert( - std::make_pair( - "vibrationURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + std::make_pair("vibrationURI", value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); value = nullptr; //### groupIds: ### - JsonArray& group_ids = out.insert(std::make_pair(std::string("groupIds"), - picojson::value(JsonArray()))).first->second.get(); + JsonArray& group_ids = + out.insert(std::make_pair(std::string("groupIds"), picojson::value(JsonArray()))) + .first->second.get(); - status = ContactUtil::GetNumberOfChildRecord( - contacts_record, _contacts_contact.group_relation, &child_rec_count); + status = ContactUtil::GetNumberOfChildRecord(contacts_record, _contacts_contact.group_relation, + &child_rec_count); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2678,7 +2474,8 @@ PlatformResult ImportContactFromContactsRecord( for (int i = 0; i < child_rec_count; ++i) { JsonValue val{JsonObject{}}; - status = ImportGroupIdsFromContactsRecord(contacts_record, static_cast(i), &val); + status = + ImportGroupIdsFromContactsRecord(contacts_record, static_cast(i), &val); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2701,8 +2498,8 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, //### ContactName: ### if (!IsNull(in, "name")) { - PlatformResult status = ExportContactNameToContactsRecord( - contacts_record, FromJson(in, "name")); + PlatformResult status = + ExportContactNameToContactsRecord(contacts_record, FromJson(in, "name")); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2716,28 +2513,19 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, ExportFunc export_func; }; const ExportDataHelper exports[] = { - {_contacts_contact.email, "emails", - ExportContactEmailAddressToContactsRecord}, - {_contacts_contact.number, "phoneNumbers", - ExportContactPhoneNumberToContactsRecord}, - {_contacts_contact.company, "organizations", - ExportContactOrganizationToContactsRecord}, + {_contacts_contact.email, "emails", ExportContactEmailAddressToContactsRecord}, + {_contacts_contact.number, "phoneNumbers", ExportContactPhoneNumberToContactsRecord}, + {_contacts_contact.company, "organizations", ExportContactOrganizationToContactsRecord}, {_contacts_contact.url, "urls", ExportContactWebSiteToContactsRecord}, - {_contacts_contact.event, "anniversaries", - ExportContactAnniversariesToContactsRecord}, - {_contacts_contact.address, "addresses", - ExportContactAddressToContactsRecord}, - {_contacts_contact.messenger, "messengers", - ExportContactInstantMessengerToContactsRecord}, - {_contacts_contact.relationship, "relationships", - ExportContactRelationshipToContactsRecord}, - {_contacts_contact.extension, "extensions", - ExportContactExtensionToContactsRecord}, + {_contacts_contact.event, "anniversaries", ExportContactAnniversariesToContactsRecord}, + {_contacts_contact.address, "addresses", ExportContactAddressToContactsRecord}, + {_contacts_contact.messenger, "messengers", ExportContactInstantMessengerToContactsRecord}, + {_contacts_contact.relationship, "relationships", ExportContactRelationshipToContactsRecord}, + {_contacts_contact.extension, "extensions", ExportContactExtensionToContactsRecord}, }; for (auto& data : exports) { - PlatformResult status = - ContactUtil::ClearAllContactRecord(contacts_record, data.property_id); + PlatformResult status = ContactUtil::ClearAllContactRecord(contacts_record, data.property_id); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2751,8 +2539,8 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, { //### m_notes: ### - PlatformResult status = ContactUtil::ClearAllContactRecord( - contacts_record, _contacts_contact.note); + PlatformResult status = + ContactUtil::ClearAllContactRecord(contacts_record, _contacts_contact.note); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2772,16 +2560,15 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, if (IsNull(in, "photoURI")) { contacts_record_h child_record = nullptr; int err = contacts_record_create(_contacts_image._uri, &child_record); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Fail to create image uri record in database."); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Fail to create image uri record in database."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } ContactsRecordHPtr record(&child_record, ContactsDeleter); - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.image, child_record); + err = contacts_record_add_child_record(contacts_record, _contacts_contact.image, child_record); status = ContactUtil::ErrorChecker(err, "Fail to add child to image uri."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); @@ -2793,12 +2580,12 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, } else { bool is_first = false; contacts_record_h child_record = nullptr; - int err = contacts_record_get_child_record_at_p( - contacts_record, _contacts_contact.image, 0, &child_record); + int err = contacts_record_get_child_record_at_p(contacts_record, _contacts_contact.image, 0, + &child_record); if (CONTACTS_ERROR_NONE != err || nullptr == child_record) { err = contacts_record_create(_contacts_image._uri, &child_record); - PlatformResult status = ContactUtil::ErrorChecker( - err, "Fail to create image uri record in database."); + PlatformResult status = + ContactUtil::ErrorChecker(err, "Fail to create image uri record in database."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2810,10 +2597,9 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, std::string real_path; if (!IsNull(in, "photoURI")) { - real_path = - ContactUtil::ConvertUriToPath(FromJson(in, "photoURI")); - PlatformResult status = ContactUtil::SetStrInRecord( - child_record, _contacts_image.path, real_path.c_str()); + real_path = ContactUtil::ConvertUriToPath(FromJson(in, "photoURI")); + PlatformResult status = + ContactUtil::SetStrInRecord(child_record, _contacts_image.path, real_path.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2821,10 +2607,9 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, } if (is_first) { - err = contacts_record_add_child_record( - contacts_record, _contacts_contact.image, child_record); - PlatformResult status = - ContactUtil::ErrorChecker(err, "Fail to add child to image uri."); + err = + contacts_record_add_child_record(contacts_record, _contacts_contact.image, child_record); + PlatformResult status = ContactUtil::ErrorChecker(err, "Fail to add child to image uri."); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2837,15 +2622,14 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, std::string real_path; // Contact.ringtoneURI if (!IsNull(in, "ringtoneURI")) { - real_path = - ContactUtil::ConvertUriToPath(FromJson(in, "ringtoneURI")); + real_path = ContactUtil::ConvertUriToPath(FromJson(in, "ringtoneURI")); PlatformResult status = VerifyLocalPath(real_path); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - status = ContactUtil::SetStrInRecord( - contacts_record, _contacts_contact.ringtone_path, real_path.c_str()); + status = ContactUtil::SetStrInRecord(contacts_record, _contacts_contact.ringtone_path, + real_path.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2853,8 +2637,7 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, } // Contact.messageAlertURI if (!IsNull(in, "messageAlertURI")) { - real_path = ContactUtil::ConvertUriToPath( - FromJson(in, "messageAlertURI")); + real_path = ContactUtil::ConvertUriToPath(FromJson(in, "messageAlertURI")); PlatformResult status = ContactUtil::SetStrInRecord( contacts_record, _contacts_contact.message_alert, real_path.c_str()); if (status.IsError()) { @@ -2865,8 +2648,7 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, // Contact.vibrationURI if (!IsNull(in, "vibrationURI")) { - real_path = - ContactUtil::ConvertUriToPath(FromJson(in, "vibrationURI")); + real_path = ContactUtil::ConvertUriToPath(FromJson(in, "vibrationURI")); PlatformResult status = ContactUtil::SetStrInRecord( contacts_record, _contacts_contact.vibration, real_path.c_str()); if (status.IsError()) { @@ -2877,8 +2659,8 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, { //### groupIds: ### - PlatformResult status = ContactUtil::ClearAllContactRecord( - contacts_record, _contacts_contact.group_relation); + PlatformResult status = + ContactUtil::ClearAllContactRecord(contacts_record, _contacts_contact.group_relation); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2894,12 +2676,11 @@ PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, } } - return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ImportContactGroupFromContactsRecord( - contacts_record_h contacts_record, JsonObject* out_ptr) { +PlatformResult ImportContactGroupFromContactsRecord(contacts_record_h contacts_record, + JsonObject* out_ptr) { JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2909,8 +2690,8 @@ PlatformResult ImportContactGroupFromContactsRecord( // id int int_val = 0; - PlatformResult status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_group.id, &int_val); + PlatformResult status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_group.id, &int_val); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2919,20 +2700,18 @@ PlatformResult ImportContactGroupFromContactsRecord( out.insert(std::make_pair("id", JsonValue{std::to_string(int_val)})); // addressBookId - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_group.address_book_id, &int_val); + status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_group.address_book_id, &int_val); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("addressBookId", JsonValue{std::to_string(int_val)})); + out.insert(std::make_pair("addressBookId", JsonValue{std::to_string(int_val)})); // name char* value = nullptr; - status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_group.name, - &value); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_group.name, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2942,36 +2721,29 @@ PlatformResult ImportContactGroupFromContactsRecord( // photoURI value = nullptr; - status = ContactUtil::GetStrFromRecord(contacts_record, - _contacts_group.image_path, &value); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_group.image_path, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair( - "photoURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + out.insert(std::make_pair("photoURI", value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); // ringtoneURI value = nullptr; - status = ContactUtil::GetStrFromRecord(contacts_record, - _contacts_group.ringtone_path, &value); + status = ContactUtil::GetStrFromRecord(contacts_record, _contacts_group.ringtone_path, &value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert( - std::make_pair( - "ringtoneURI", - value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); + std::make_pair("ringtoneURI", value ? JsonValue{ConvertPathToUri(value)} : JsonValue{})); // is_read_only bool bool_value = false; - status = ContactUtil::GetBoolFromRecord( - contacts_record, _contacts_group.is_read_only, &bool_value); + status = + ContactUtil::GetBoolFromRecord(contacts_record, _contacts_group.is_read_only, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2982,12 +2754,11 @@ PlatformResult ImportContactGroupFromContactsRecord( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ExportContactGroupToContactsRecord( - contacts_record_h contacts_record, const JsonObject& in) { +PlatformResult ExportContactGroupToContactsRecord(contacts_record_h contacts_record, + const JsonObject& in) { // name - PlatformResult status = - ContactUtil::SetStrInRecord(contacts_record, _contacts_group.name, - FromJson(in, "name").c_str()); + PlatformResult status = ContactUtil::SetStrInRecord(contacts_record, _contacts_group.name, + FromJson(in, "name").c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -2997,8 +2768,8 @@ PlatformResult ExportContactGroupToContactsRecord( // photoURI if (!IsNull(in, "photoURI")) { real_path = ConvertUriToPath(FromJson(in, "photoURI")); - PlatformResult status = ContactUtil::SetStrInRecord( - contacts_record, _contacts_group.image_path, real_path.c_str()); + PlatformResult status = + ContactUtil::SetStrInRecord(contacts_record, _contacts_group.image_path, real_path.c_str()); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3006,8 +2777,7 @@ PlatformResult ExportContactGroupToContactsRecord( } // ringtoneURI if (!IsNull(in, "ringtoneURI")) { - real_path = - ContactUtil::ConvertUriToPath(FromJson(in, "ringtoneURI")); + real_path = ContactUtil::ConvertUriToPath(FromJson(in, "ringtoneURI")); // NOTE in the original code real path was not read PlatformResult status = ContactUtil::SetStrInRecord( contacts_record, _contacts_group.ringtone_path, real_path.c_str()); @@ -3024,54 +2794,46 @@ PlatformResult ExportContactGroupToContactsRecord( * @brief Fills Person object with values from record * @param[in] contacts_record_h Record which is used to fill Person */ -PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, - JsonObject* out_ptr) { +PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, JsonObject* out_ptr) { if (nullptr == record) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Platform person record did not set"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Platform person record did not set"); } JsonObject& arguments_obj = *out_ptr; int int_value = 0; // id - PlatformResult status = - ContactUtil::GetIntFromRecord(record, _contacts_person.id, &int_value); + PlatformResult status = ContactUtil::GetIntFromRecord(record, _contacts_person.id, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - arguments_obj.insert( - std::make_pair("id", JsonValue(std::to_string(int_value)))); + arguments_obj.insert(std::make_pair("id", JsonValue(std::to_string(int_value)))); char* char_value = nullptr; // displayName - status = ContactUtil::GetStrFromRecord(record, _contacts_person.display_name, - &char_value); + status = ContactUtil::GetStrFromRecord(record, _contacts_person.display_name, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - arguments_obj.insert(std::make_pair( - "displayName", char_value ? JsonValue(char_value) : JsonValue{})); + arguments_obj.insert( + std::make_pair("displayName", char_value ? JsonValue(char_value) : JsonValue{})); // contactCount - status = ContactUtil::GetIntFromRecord(record, _contacts_person.link_count, - &int_value); + status = ContactUtil::GetIntFromRecord(record, _contacts_person.link_count, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - arguments_obj.insert(std::make_pair( - "contactCount", JsonValue(static_cast(int_value)))); + arguments_obj.insert(std::make_pair("contactCount", JsonValue(static_cast(int_value)))); bool bool_value = false; // hasPhoneNumber - status = ContactUtil::GetBoolFromRecord( - record, _contacts_person.has_phonenumber, &bool_value); + status = ContactUtil::GetBoolFromRecord(record, _contacts_person.has_phonenumber, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3080,8 +2842,7 @@ PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, arguments_obj.insert(std::make_pair("hasPhoneNumber", JsonValue(bool_value))); // hasEmail - status = ContactUtil::GetBoolFromRecord(record, _contacts_person.has_email, - &bool_value); + status = ContactUtil::GetBoolFromRecord(record, _contacts_person.has_email, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3090,8 +2851,7 @@ PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, arguments_obj.insert(std::make_pair("hasEmail", JsonValue(bool_value))); // isFavorite - status = ContactUtil::GetBoolFromRecord(record, _contacts_person.is_favorite, - &bool_value); + status = ContactUtil::GetBoolFromRecord(record, _contacts_person.is_favorite, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3100,42 +2860,35 @@ PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, arguments_obj.insert(std::make_pair("isFavorite", JsonValue(bool_value))); // photoURI - status = ContactUtil::GetStrFromRecord( - record, _contacts_person.image_thumbnail_path, &char_value); + status = + ContactUtil::GetStrFromRecord(record, _contacts_person.image_thumbnail_path, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - arguments_obj.insert( - std::make_pair( - "photoURI", - char_value ? JsonValue(ConvertPathToUri(char_value)) : JsonValue{})); + arguments_obj.insert(std::make_pair( + "photoURI", char_value ? JsonValue(ConvertPathToUri(char_value)) : JsonValue{})); // ringtoneURI - status = ContactUtil::GetStrFromRecord(record, _contacts_person.ringtone_path, - &char_value); + status = ContactUtil::GetStrFromRecord(record, _contacts_person.ringtone_path, &char_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - arguments_obj.insert( - std::make_pair( - "ringtoneURI", - char_value ? JsonValue(ConvertPathToUri(char_value)) : JsonValue{})); + arguments_obj.insert(std::make_pair( + "ringtoneURI", char_value ? JsonValue(ConvertPathToUri(char_value)) : JsonValue{})); // displayContactId - status = ContactUtil::GetIntFromRecord( - record, _contacts_person.display_contact_id, &int_value); + status = ContactUtil::GetIntFromRecord(record, _contacts_person.display_contact_id, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } arguments_obj.insert( - std::make_pair("displayContactId", - picojson::value(std::to_string(int_value)))); + std::make_pair("displayContactId", picojson::value(std::to_string(int_value)))); return PlatformResult(ErrorCode::NO_ERROR); } @@ -3144,22 +2897,19 @@ PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, * @brief Updates contacts_record_h with values from Person object * @param[out] contacts_record_h Record which is updated */ -PlatformResult ExportPersonToContactsRecord(contacts_record_h record, - const JsonObject& args) { +PlatformResult ExportPersonToContactsRecord(contacts_record_h record, const JsonObject& args) { if (nullptr == record) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform person object did not set"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform person object did not set"); } - PlatformResult status = ContactUtil::SetBoolInRecord( - record, _contacts_person.is_favorite, FromJson(args, "isFavorite")); + PlatformResult status = ContactUtil::SetBoolInRecord(record, _contacts_person.is_favorite, + FromJson(args, "isFavorite")); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - if (!IsNull(args, "photoURI") && - !FromJson(args, "photoURI").empty()) { + if (!IsNull(args, "photoURI") && !FromJson(args, "photoURI").empty()) { PlatformResult status = ContactUtil::SetStrInRecord( record, _contacts_person.image_thumbnail_path, ConvertUriToPath(FromJson(args, "photoURI")).c_str()); @@ -3180,17 +2930,16 @@ PlatformResult ExportPersonToContactsRecord(contacts_record_h record, return status; } } else { - PlatformResult status = - ContactUtil::SetStrInRecord(record, _contacts_person.ringtone_path, ""); + PlatformResult status = ContactUtil::SetStrInRecord(record, _contacts_person.ringtone_path, ""); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } } if (!IsNull(args, "displayContactId")) { - PlatformResult status = ContactUtil::SetIntInRecord( - record, _contacts_person.display_contact_id, - common::stol(FromJson(args, "displayContactId"))); + PlatformResult status = + ContactUtil::SetIntInRecord(record, _contacts_person.display_contact_id, + common::stol(FromJson(args, "displayContactId"))); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3200,39 +2949,37 @@ PlatformResult ExportPersonToContactsRecord(contacts_record_h record, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UpdateAdditionalInformation( - const contacts_record_h contacts_record, JsonObject* out_ptr) { +PlatformResult UpdateAdditionalInformation(const contacts_record_h contacts_record, + JsonObject* out_ptr) { JsonObject& out = *out_ptr; int int_value = -1; - PlatformResult status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_contact.person_id, &int_value); + PlatformResult status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.person_id, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } out.insert(std::make_pair("personId", JsonValue{std::to_string(int_value)})); - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_contact.address_book_id, &int_value); + status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.address_book_id, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("addressBookId", JsonValue{std::to_string(int_value)})); - status = ContactUtil::GetIntFromRecord( - contacts_record, _contacts_contact.changed_time, &int_value); + out.insert(std::make_pair("addressBookId", JsonValue{std::to_string(int_value)})); + status = + ContactUtil::GetIntFromRecord(contacts_record, _contacts_contact.changed_time, &int_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; } - out.insert( - std::make_pair("lastUpdated", JsonValue{static_cast(int_value)})); + out.insert(std::make_pair("lastUpdated", JsonValue{static_cast(int_value)})); bool bool_value = false; - status = ContactUtil::GetBoolFromRecord( - contacts_record, _contacts_contact.is_favorite, &bool_value); + status = + ContactUtil::GetBoolFromRecord(contacts_record, _contacts_contact.is_favorite, &bool_value); if (status.IsError()) { LoggerE("Error: %s", status.message().c_str()); return status; @@ -3252,9 +2999,8 @@ PlatformResult CheckDBConnection() { LoggerI("Connection established!"); _connected = true; } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "DB connection error occured: " + std::to_string(err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "DB connection error occured: " + std::to_string(err)); } return PlatformResult(ErrorCode::NO_ERROR); diff --git a/src/contact/contact_util.h b/src/contact/contact_util.h index 219e2ea..9e0cdf1 100644 --- a/src/contact/contact_util.h +++ b/src/contact/contact_util.h @@ -17,10 +17,10 @@ #ifndef CONTACT_CONTACT_UTIL_H_ #define CONTACT_CONTACT_UTIL_H_ +#include #include #include #include -#include #include "common/picojson.h" #include "common/platform_exception.h" #include "common/platform_result.h" @@ -35,120 +35,115 @@ typedef std::string JsonString; namespace ContactUtil { -std::string ConvertUriToPath(const std::string& str); -std::string ConvertPathToUri(const std::string& str); +std::string ConvertUriToPath(const std::string &str); +std::string ConvertPathToUri(const std::string &str); void ContactsDeleter(contacts_record_h *contacts_record); -typedef std::unique_ptr - ContactsRecordHPtr; +typedef std::unique_ptr ContactsRecordHPtr; void ContactsListDeleter(contacts_list_h *contacts_list); -typedef std::unique_ptr - ContactsListHPtr; +typedef std::unique_ptr ContactsListHPtr; void ContactsFilterDeleter(contacts_filter_h contacts_filter); -typedef std::unique_ptr::type, - void (*)(contacts_filter_h)> ContactsFilterPtr; +typedef std::unique_ptr::type, void (*)(contacts_filter_h)> + ContactsFilterPtr; void ContactsQueryDeleter(contacts_query_h *contacts_query); -typedef std::unique_ptr - ContactsQueryHPtr; +typedef std::unique_ptr ContactsQueryHPtr; common::PlatformResult ErrorChecker(int err, const char *message); -common::PlatformResult GetStrFromRecord(contacts_record_h record, - unsigned int property_id, char **value); +common::PlatformResult GetStrFromRecord(contacts_record_h record, unsigned int property_id, + char **value); -common::PlatformResult GetIntFromRecord(contacts_record_h record, - unsigned int property_id, int *value); +common::PlatformResult GetIntFromRecord(contacts_record_h record, unsigned int property_id, + int *value); -common::PlatformResult GetBoolFromRecord(contacts_record_h record, - unsigned int property_id, bool *value); +common::PlatformResult GetBoolFromRecord(contacts_record_h record, unsigned int property_id, + bool *value); -common::PlatformResult SetStrInRecord(contacts_record_h record, - unsigned int property_id, +common::PlatformResult SetStrInRecord(contacts_record_h record, unsigned int property_id, const char *value); -common::PlatformResult SetIntInRecord(contacts_record_h record, - unsigned int property_id, int value); +common::PlatformResult SetIntInRecord(contacts_record_h record, unsigned int property_id, + int value); -common::PlatformResult SetBoolInRecord(contacts_record_h record, - unsigned int property_id, bool value); +common::PlatformResult SetBoolInRecord(contacts_record_h record, unsigned int property_id, + bool value); common::PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, unsigned int property_id); common::PlatformResult GetNumberOfChildRecord(contacts_record_h contacts_record, - unsigned int property_id, - int *child_count); + unsigned int property_id, int *child_count); -common::PlatformResult UpdateAdditionalInformation( - const contacts_record_h contacts_record, JsonObject *out); +common::PlatformResult UpdateAdditionalInformation(const contacts_record_h contacts_record, + JsonObject *out); -common::PlatformResult ImportContactNameFromContactsRecord( - contacts_record_h contacts_record, JsonObject *out, bool *is_contact_name); -common::PlatformResult ExportContactNameToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); +common::PlatformResult ImportContactNameFromContactsRecord(contacts_record_h contacts_record, + JsonObject *out, bool *is_contact_name); +common::PlatformResult ExportContactNameToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); common::PlatformResult ImportContactEmailAddressFromContactsRecord( contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactEmailAddressToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); - -common::PlatformResult ImportContactAddressFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactAddressToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportContactPhoneNumberFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactPhoneNumberToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); +common::PlatformResult ExportContactEmailAddressToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); + +common::PlatformResult ImportContactAddressFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject *out); +common::PlatformResult ExportContactAddressToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); +common::PlatformResult ImportContactPhoneNumberFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject *out); +common::PlatformResult ExportContactPhoneNumberToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); common::PlatformResult ImportContactOrganizationFromContactsRecord( contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactOrganizationToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportContactWebSiteFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactWebSiteToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); +common::PlatformResult ExportContactOrganizationToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); +common::PlatformResult ImportContactWebSiteFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonObject *out); +common::PlatformResult ExportContactWebSiteToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); common::PlatformResult ImportContactAnniversariesFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject *out, - bool *ret); -common::PlatformResult ExportContactAnniversariesToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); + contacts_record_h contacts_record, unsigned int index, JsonObject *out, bool *ret); +common::PlatformResult ExportContactAnniversariesToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); common::PlatformResult ImportContactRelationshipFromContactsRecord( contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactRelationshipToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportContactExtensionFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonObject *out); -common::PlatformResult ExportContactExtensionToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); +common::PlatformResult ExportContactRelationshipToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); +common::PlatformResult ImportContactExtensionFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, + JsonObject *out); +common::PlatformResult ExportContactExtensionToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); common::PlatformResult ImportContactInstantMessengerFromContactsRecord( contacts_record_h contacts_record, unsigned int index, JsonObject *out); common::PlatformResult ExportContactInstantMessengerToContactsRecord( contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportContactNotesFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonValue *val); -common::PlatformResult ExportNotesToContactsRecord( - contacts_record_h contacts_record, const std::string &value); -common::PlatformResult ImportGroupIdsFromContactsRecord( - contacts_record_h contacts_record, unsigned int index, JsonValue *val); -common::PlatformResult ExportGroupIdsToContactsRecord( - contacts_record_h contacts_record, int value); -common::PlatformResult ImportContactFromContactsRecord( - contacts_record_h contacts_record, JsonObject *out); +common::PlatformResult ImportContactNotesFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonValue *val); +common::PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, + const std::string &value); +common::PlatformResult ImportGroupIdsFromContactsRecord(contacts_record_h contacts_record, + unsigned int index, JsonValue *val); +common::PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, int value); +common::PlatformResult ImportContactFromContactsRecord(contacts_record_h contacts_record, + JsonObject *out); common::PlatformResult ExportPersonToContactsRecord(contacts_record_h record, const JsonObject &args); -common::PlatformResult ExportContactToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportContactGroupFromContactsRecord( - contacts_record_h contacts_record, JsonObject *out); -common::PlatformResult ExportContactGroupToContactsRecord( - contacts_record_h contacts_record, const JsonObject &in); -common::PlatformResult ImportPersonFromContactsRecord( - contacts_record_h contacts_record, JsonObject *out); +common::PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); +common::PlatformResult ImportContactGroupFromContactsRecord(contacts_record_h contacts_record, + JsonObject *out); +common::PlatformResult ExportContactGroupToContactsRecord(contacts_record_h contacts_record, + const JsonObject &in); +common::PlatformResult ImportPersonFromContactsRecord(contacts_record_h contacts_record, + JsonObject *out); common::PlatformResult CheckDBConnection(); diff --git a/src/contact/person.cc b/src/contact/person.cc old mode 100755 new mode 100644 index e6ee981..f407a34 --- a/src/contact/person.cc +++ b/src/contact/person.cc @@ -15,22 +15,22 @@ */ #include "contact/person.h" #include "common/converter.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" namespace extension { namespace contact { -extern const std::string kUsageTypeOutgoingCall = "OUTGOING_CALL"; -extern const std::string kUsageTypeOutgoingMsg = "OUTGOING_MSG"; +extern const std::string kUsageTypeOutgoingCall = "OUTGOING_CALL"; +extern const std::string kUsageTypeOutgoingMsg = "OUTGOING_MSG"; extern const std::string kUsageTypeOutgoingEmail = "OUTGOING_EMAIL"; -extern const std::string kUsageTypeIncomingCall = "INCOMING_CALL"; -extern const std::string kUsageTypeIncomingMsg = "INCOMING_MSG"; +extern const std::string kUsageTypeIncomingCall = "INCOMING_CALL"; +extern const std::string kUsageTypeIncomingMsg = "INCOMING_MSG"; extern const std::string kUsageTypeIncomingEmail = "INCOMING_EMAIL"; -extern const std::string kUsageTypeMissedCall = "MISSED_CALL"; -extern const std::string kUsageTypeRejectedCall = "REJECTED_CALL"; -extern const std::string kUsageTypeBlockedCall = "BLOCKED_CALL"; -extern const std::string kUsageTypeBlockedMsg = "BLOCKED_MSG"; +extern const std::string kUsageTypeMissedCall = "MISSED_CALL"; +extern const std::string kUsageTypeRejectedCall = "REJECTED_CALL"; +extern const std::string kUsageTypeBlockedCall = "BLOCKED_CALL"; +extern const std::string kUsageTypeBlockedMsg = "BLOCKED_MSG"; namespace Person { @@ -48,22 +48,22 @@ static const PersonPropertyMap personPropertyMap = { {"displayContactId", {_contacts_person.display_contact_id, kPrimitiveTypeId}}, }; -extern const std::string kUsageTypeOutgoingCall = "OUTGOING_CALL"; -extern const std::string kUsageTypeOutgoingMsg = "OUTGOING_MSG"; +extern const std::string kUsageTypeOutgoingCall = "OUTGOING_CALL"; +extern const std::string kUsageTypeOutgoingMsg = "OUTGOING_MSG"; extern const std::string kUsageTypeOutgoingEmail = "OUTGOING_EMAIL"; -extern const std::string kUsageTypeIncomingCall = "INCOMING_CALL"; -extern const std::string kUsageTypeIncomingMsg = "INCOMING_MSG"; +extern const std::string kUsageTypeIncomingCall = "INCOMING_CALL"; +extern const std::string kUsageTypeIncomingMsg = "INCOMING_MSG"; extern const std::string kUsageTypeIncomingEmail = "INCOMING_EMAIL"; -extern const std::string kUsageTypeMissedCall = "MISSED_CALL"; -extern const std::string kUsageTypeRejectedCall = "REJECTED_CALL"; -extern const std::string kUsageTypeBlockedCall = "BLOCKED_CALL"; -extern const std::string kUsageTypeBlockedMsg = "BLOCKED_MSG"; +extern const std::string kUsageTypeMissedCall = "MISSED_CALL"; +extern const std::string kUsageTypeRejectedCall = "REJECTED_CALL"; +extern const std::string kUsageTypeBlockedCall = "BLOCKED_CALL"; +extern const std::string kUsageTypeBlockedMsg = "BLOCKED_MSG"; namespace { - const char* kGetUsageCountArgPersonId = "personId"; - const char* kGetUsageCountArgUsageType = "usage_type"; +const char* kGetUsageCountArgPersonId = "personId"; +const char* kGetUsageCountArgUsageType = "usage_type"; - const char* kGetUsageCountResultUsageCount = "usageCount"; +const char* kGetUsageCountResultUsageCount = "usageCount"; }; PlatformResult PersonLink(const JsonObject& args, JsonObject&) { @@ -87,8 +87,7 @@ PlatformResult PersonLink(const JsonObject& args, JsonObject&) { err = contacts_person_link_person(person_id, id); - status = - ContactUtil::ErrorChecker(err, "Error during executing person link()"); + status = ContactUtil::ErrorChecker(err, "Error during executing person link()"); if (status.IsError()) return status; return PlatformResult(ErrorCode::NO_ERROR); @@ -102,49 +101,44 @@ PlatformResult PersonUnlink(const JsonObject& args, JsonObject& out) { long contact_id = common::stol(FromJson(args, "id")); contacts_record_h contacts_record = nullptr; - int error_code = contacts_db_get_record(_contacts_simple_contact._uri, - contact_id, &contacts_record); + int error_code = + contacts_db_get_record(_contacts_simple_contact._uri, contact_id, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { contacts_record_destroy(contacts_record, true); contacts_record = nullptr; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Contact not found", - ("Contact not found, error code: %d", error_code)); + ("Contact not found, error code: %d", error_code)); } int contacts_person_id = 0; - error_code = contacts_record_get_int( - contacts_record, _contacts_simple_contact.person_id, &contacts_person_id); + error_code = contacts_record_get_int(contacts_record, _contacts_simple_contact.person_id, + &contacts_person_id); contacts_record_destroy(contacts_record, true); contacts_record = nullptr; - status = ContactUtil::ErrorChecker(error_code, - "Contact is not a member of person"); + status = ContactUtil::ErrorChecker(error_code, "Contact is not a member of person"); if (status.IsError()) return status; long person_id = common::stol(FromJson(args, "personId")); if (contacts_person_id != person_id) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Contact is not a member of person", - ("Contact is not a member of person (wrong id's)")); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Contact is not a member of person", + ("Contact is not a member of person (wrong id's)")); } int new_person_id = 0; - error_code = - contacts_person_unlink_contact(person_id, contact_id, &new_person_id); + error_code = contacts_person_unlink_contact(person_id, contact_id, &new_person_id); - status = - ContactUtil::ErrorChecker(error_code, "Error during executing unlink()"); + status = ContactUtil::ErrorChecker(error_code, "Error during executing unlink()"); if (status.IsError()) return status; - error_code = contacts_db_get_record(_contacts_person._uri, new_person_id, - &contacts_record); + error_code = contacts_db_get_record(_contacts_person._uri, new_person_id, &contacts_record); if (CONTACTS_ERROR_NONE != error_code) { contacts_record_destroy(contacts_record, true); contacts_record = nullptr; return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Person not found", - ("Person not found, error code: %d", error_code)); + ("Person not found, error code: %d", error_code)); } status = ContactUtil::ImportPersonFromContactsRecord(contacts_record, &out); @@ -184,9 +178,7 @@ PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { return status; } ContactUtil::ContactsFilterPtr filter_ptr(filter, ContactUtil::ContactsFilterDeleter); - ret = contacts_filter_add_int(filter, - _contacts_person_usage.person_id, - CONTACTS_MATCH_EQUAL, + ret = contacts_filter_add_int(filter, _contacts_person_usage.person_id, CONTACTS_MATCH_EQUAL, person_id); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { @@ -194,7 +186,8 @@ PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { } if (!IsNull(args, kGetUsageCountArgUsageType)) { - contacts_usage_type_e type = UsageTypeFromString(FromJson(args, kGetUsageCountArgUsageType)); + contacts_usage_type_e type = + UsageTypeFromString(FromJson(args, kGetUsageCountArgUsageType)); ret = contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_AND); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_operator"); @@ -202,9 +195,7 @@ PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { return status; } - ret = contacts_filter_add_int(filter, - _contacts_person_usage.usage_type, - CONTACTS_MATCH_EQUAL, + ret = contacts_filter_add_int(filter, _contacts_person_usage.usage_type, CONTACTS_MATCH_EQUAL, type); status = ContactUtil::ErrorChecker(ret, "Failed contacts_filter_add_int"); if (!status) { @@ -247,7 +238,7 @@ PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { return status; } - ret = contacts_record_get_int(record, _contacts_person_usage.times_used, &usage_count_tmp ); + ret = contacts_record_get_int(record, _contacts_person_usage.times_used, &usage_count_tmp); status = ContactUtil::ErrorChecker(ret, "Failed contacts_record_get_int"); if (!status) { return status; @@ -258,7 +249,8 @@ PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { contacts_list_next(list); } - out.insert(std::make_pair(kGetUsageCountResultUsageCount, JsonValue(static_cast(usage_count)))); + out.insert( + std::make_pair(kGetUsageCountResultUsageCount, JsonValue(static_cast(usage_count)))); return PlatformResult(ErrorCode::NO_ERROR); } @@ -267,12 +259,12 @@ PlatformResult ResetUsageCount(const long& person_id, const std::string& type) { contacts_usage_type_e type_enum = UsageTypeFromString(type); int ret = CONTACTS_ERROR_NONE; - for (int i = CONTACTS_USAGE_STAT_TYPE_OUTGOING_CALL; i <= CONTACTS_USAGE_STAT_TYPE_BLOCKED_MSG; i++) { + for (int i = CONTACTS_USAGE_STAT_TYPE_OUTGOING_CALL; i <= CONTACTS_USAGE_STAT_TYPE_BLOCKED_MSG; + i++) { if (type == "" || type_enum == static_cast(i)) { ret = contacts_person_reset_usage(person_id, static_cast(i)); if (CONTACTS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Error during reset usage count", + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Error during reset usage count", ("Error during reset usage count for %s: %d", type.c_str(), ret)); } } @@ -296,17 +288,14 @@ PlatformResult PersonResetUsageCount(const JsonObject& args) { } else { return ResetUsageCount(person_id, FromJson(args, "usage_type")); } - } -PlatformResult PersonPropertyFromString(const std::string& name, - PersonProperty* person_prop) { +PlatformResult PersonPropertyFromString(const std::string& name, PersonProperty* person_prop) { LoggerD("Enter"); auto iter = personPropertyMap.find(name); if (iter == personPropertyMap.end()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid property name", - ("Invalid property name (not in map): %s", name.c_str())); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid property name", + ("Invalid property name (not in map): %s", name.c_str())); } (*person_prop).propertyId = iter->second.propertyId; (*person_prop).type = iter->second.type; diff --git a/src/contact/person.h b/src/contact/person.h index 2aba7ae..a704e06 100644 --- a/src/contact/person.h +++ b/src/contact/person.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef CONTACT_PERSON_H_ #define CONTACT_PERSON_H_ diff --git a/src/content/content_extension.cc b/src/content/content_extension.cc old mode 100755 new mode 100644 index ae072b7..6dd1011 --- a/src/content/content_extension.cc +++ b/src/content/content_extension.cc @@ -30,7 +30,8 @@ ContentExtension::ContentExtension() { SetJavaScriptAPI(kSource_content_api); } -ContentExtension::~ContentExtension() {} +ContentExtension::~ContentExtension() { +} common::Instance* ContentExtension::CreateInstance() { return new extension::content::ContentInstance; diff --git a/src/content/content_extension.h b/src/content/content_extension.h old mode 100755 new mode 100644 index 9e58cef..4a48ada --- a/src/content/content_extension.h +++ b/src/content/content_extension.h @@ -28,4 +28,4 @@ class ContentExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // CONTENT_CONTENT_EXTENSION_H_ +#endif // CONTENT_CONTENT_EXTENSION_H_ diff --git a/src/content/content_filter.cc b/src/content/content_filter.cc old mode 100755 new mode 100644 index 627d8a8..130b0d5 --- a/src/content/content_filter.cc +++ b/src/content/content_filter.cc @@ -80,14 +80,12 @@ std::string escapeValueString(const std::string& data) { } // namespace -PlatformResult ContentFilter::MapField(const std::string& name, - std::string* result) { +PlatformResult ContentFilter::MapField(const std::string& name, std::string* result) { LoggerD("Enter"); auto it = attributeNameMap.find(name); - if (it != attributeNameMap.end()) + if (it != attributeNameMap.end()) { *result = it->second; - else - { + } else { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR); } return PlatformResult(ErrorCode::NO_ERROR); @@ -96,21 +94,18 @@ PlatformResult ContentFilter::MapField(const std::string& name, PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, std::string* queryToCall) { LoggerD("Enter"); - std::vector > partialqueries; + std::vector> partialqueries; partialqueries.push_back(std::vector()); - visitor.SetOnAttributeFilter([&](const std::string& name, - AttributeMatchFlag match_flag, + visitor.SetOnAttributeFilter([&](const std::string& name, AttributeMatchFlag match_flag, const picojson::value& match_value) { LoggerD("entered OnAttributeFilter"); - std::string query; std::string matchValue; PlatformResult result = MapField(name, &query); - if (!result) - return result; + if (!result) return result; if (AttributeMatchFlag::kExactly == match_flag || AttributeMatchFlag::kFullString == match_flag) { @@ -141,21 +136,21 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, const char* uri_prefix = "file://"; size_t found = matchValue.find(uri_prefix); if (found != std::string::npos) { - //simple convertion of URI to globalpath + // simple convertion of URI to globalpath matchValue = matchValue.substr(found + strlen(uri_prefix)); } } switch (match_flag) { - case AttributeMatchFlag::kStartsWith : + case AttributeMatchFlag::kStartsWith: query += matchValue + "%"; break; - case AttributeMatchFlag::kEndsWith : + case AttributeMatchFlag::kEndsWith: query += "%" + matchValue; break; - case AttributeMatchFlag::kContains : + case AttributeMatchFlag::kContains: query += "%" + matchValue + "%"; break; - default : + default: query += matchValue; } query.append("\""); @@ -186,8 +181,7 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, partialqueries.pop_back(); return PlatformResult(ErrorCode::NO_ERROR); } - if (partialqueries.back().size() != 1) - finalQuery.append("("); + if (partialqueries.back().size() != 1) finalQuery.append("("); for (unsigned long i = 0; i < partialqueries.back().size(); i++) { finalQuery += partialqueries.back().at(i); @@ -196,8 +190,7 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, } } - if (partialqueries.back().size() != 1) - finalQuery.append(")"); + if (partialqueries.back().size() != 1) finalQuery.append(")"); partialqueries.pop_back(); partialqueries.back().push_back(finalQuery); @@ -212,8 +205,7 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, std::string query = ""; std::string paramName; PlatformResult result = MapField(name, ¶mName); - if (!result) - return result; + if (!result) return result; std::string initialValue = escapeValueString(JsonCast(initial_value)); std::string endValue = escapeValueString(JsonCast(end_value)); diff --git a/src/content/content_filter.h b/src/content/content_filter.h index 27ea7d3..44a0032 100644 --- a/src/content/content_filter.h +++ b/src/content/content_filter.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef CONTENT_FILTER_H_ #define CONTENT_FILTER_H_ @@ -29,10 +29,8 @@ namespace content { class ContentFilter { public: - static common::PlatformResult MapField(const std::string& name, - std::string* result); - common::PlatformResult BuildQuery(const picojson::object& jsFilter, - std::string* query); + static common::PlatformResult MapField(const std::string& name, std::string* result); + common::PlatformResult BuildQuery(const picojson::object& jsFilter, std::string* query); private: common::FilterVisitor visitor; diff --git a/src/content/content_instance.cc b/src/content/content_instance.cc old mode 100755 new mode 100644 index 8491b1d..587bca6 --- a/src/content/content_instance.cc +++ b/src/content/content_instance.cc @@ -16,11 +16,11 @@ #include "content/content_instance.h" -#include -#include #include -#include #include +#include +#include +#include #include "common/logger.h" #include "common/picojson.h" @@ -28,8 +28,8 @@ #include "common/task-queue.h" #include "common/tools.h" -#include "content/content_manager.h" #include "common/filesystem/filesystem_provider.h" +#include "content/content_manager.h" using namespace common; @@ -41,22 +41,21 @@ namespace { const std::string kPrivilegeContentRead = "http://tizen.org/privilege/content.read"; const std::string kPrivilegeContentWrite = "http://tizen.org/privilege/content.write"; -} // namespace +} // namespace using common::tools::ReportSuccess; using common::tools::ReportError; using common::PlatformResult; -ContentInstance::ContentInstance() : - noti_handle_(nullptr), - listener_handle_(nullptr), - listener_data_(nullptr), - callback_data_(nullptr) { +ContentInstance::ContentInstance() + : noti_handle_(nullptr), + listener_handle_(nullptr), + listener_data_(nullptr), + callback_data_(nullptr) { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&ContentInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&ContentInstance::x, this, _1, _2)); REGISTER_SYNC("ContentManager_find", ContentManagerFind); REGISTER_SYNC("ContentManager_update", ContentManagerUpdate); @@ -127,8 +126,7 @@ static gboolean CompletedCallback(const std::shared_ptr& user if (user_data->isSuccess) { ReportSuccess(user_data->result, out); } else { - LogAndReportError(user_data->isSuccess, &out, - ("Failed: user_data->isSuccess")); + LogAndReportError(user_data->isSuccess, &out, ("Failed: user_data->isSuccess")); } common::Instance::PostMessage(user_data->instance, picojson::value(out).serialize().c_str()); @@ -141,10 +139,10 @@ static void* WorkThread(const std::shared_ptr& user_data) { int ret = MEDIA_CONTENT_ERROR_NONE; ContentCallbacks cbType = user_data->cbType; - switch(cbType) { + switch (cbType) { case ContentManagerUpdatebatchCallback: { ret = ContentManager::getInstance()->updateBatch(user_data->args); - if(ret != MEDIA_CONTENT_ERROR_NONE){ + if (ret != MEDIA_CONTENT_ERROR_NONE) { LoggerD("UpdateBatch Failed"); user_data->isSuccess = ContentManager::getInstance()->convertError(ret); } @@ -163,9 +161,9 @@ static void* WorkThread(const std::shared_ptr& user_data) { std::string real_path = common::FilesystemProvider::Create().GetRealPath(contentURI); ret = ContentManager::getInstance()->scanFile(real_path); if (ret != MEDIA_CONTENT_ERROR_NONE) { - PlatformResult err = LogAndCreateResult( - common::ErrorCode::UNKNOWN_ERR, "Scan file failed.", - ("Scan file failed, error: %d (%s)", ret, get_error_message(ret))); + PlatformResult err = + LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Scan file failed.", + ("Scan file failed, error: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } break; @@ -178,8 +176,7 @@ static void* WorkThread(const std::shared_ptr& user_data) { if (user_data->args.contains("sourcePlaylist")) { picojson::object playlist = user_data->args.get("sourcePlaylist").get(); user_data->result = picojson::value(playlist); - } - else{ + } else { std::string name = user_data->args.get("name").get(); ContentManager::getInstance()->createPlaylist(name, user_data); } @@ -206,15 +203,15 @@ static void* WorkThread(const std::shared_ptr& user_data) { case ContentManagerPlaylistSetOrderCallback: { ContentManager::getInstance()->playlistSetOrder(user_data); break; - //ContentManagerPlaylistSetOrderCallback + // ContentManagerPlaylistSetOrderCallback } case ContentManagerPlaylistMoveCallback: { ContentManager::getInstance()->playlistMove(user_data); break; } case ContentManagerErrorCallback: { - common::PlatformResult err = LogAndCreateResult( - common::ErrorCode::UNKNOWN_ERR, "DB Connection is failed."); + common::PlatformResult err = + LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "DB Connection is failed."); user_data->isSuccess = err; break; } @@ -226,11 +223,10 @@ static void* WorkThread(const std::shared_ptr& user_data) { return NULL; } - static void ScanDirectoryCallback(media_content_error_e error, void* user_data) { LoggerD("Enter"); - ReplyCallbackData* cbData = (ReplyCallbackData*) user_data; + ReplyCallbackData* cbData = (ReplyCallbackData*)user_data; picojson::object out; out["callbackId"] = picojson::value(cbData->callbackId); @@ -246,15 +242,11 @@ static void ScanDirectoryCallback(media_content_error_e error, void* user_data) } // DEPRECATED CALLBACK. contentChangeCallback() is currently in use -static void changedContentV1Callback(media_content_error_e error, - int pid, - media_content_db_update_item_type_e update_item, - media_content_db_update_type_e update_type, - media_content_type_e media_type, - char* uuid, - char* path, - char* mime_type, - void* user_data) { +static void changedContentV1Callback(media_content_error_e error, int pid, + media_content_db_update_item_type_e update_item, + media_content_db_update_type_e update_type, + media_content_type_e media_type, char* uuid, char* path, + char* mime_type, void* user_data) { LoggerD("Entered file change callback"); if (error != MEDIA_CONTENT_ERROR_NONE) { @@ -305,15 +297,11 @@ static void changedContentV1Callback(media_content_error_e error, } // DEPRECATED CALLBACK. contentChangeCallback() is currently in use -static void changedContentV2Callback(media_content_error_e error, - int pid, - media_content_db_update_item_type_e update_item, - media_content_db_update_type_e update_type, - media_content_type_e media_type, - char* uuid, - char* path, - char* mime_type, - void* user_data) { +static void changedContentV2Callback(media_content_error_e error, int pid, + media_content_db_update_item_type_e update_item, + media_content_db_update_type_e update_type, + media_content_type_e media_type, char* uuid, char* path, + char* mime_type, void* user_data) { LoggerD("Entered directory change callback"); if (error != MEDIA_CONTENT_ERROR_NONE) { @@ -364,8 +352,7 @@ static void changedContentV2Callback(media_content_error_e error, } static PlatformResult prepareDirectoryChangeResponse(media_content_db_update_type_e update_type, - char* uuid, - picojson::object& obj) { + char* uuid, picojson::object& obj) { LoggerD("Media item is a directory"); if (MEDIA_CONTENT_DELETE == update_type) { @@ -404,8 +391,7 @@ static PlatformResult prepareDirectoryChangeResponse(media_content_db_update_typ } static PlatformResult prepareFileChangeResponse(media_content_db_update_type_e update_type, - char* uuid, - picojson::object& obj) { + char* uuid, picojson::object& obj) { LoggerD("Media item is a file"); if (MEDIA_CONTENT_DELETE == update_type) { @@ -443,15 +429,11 @@ static PlatformResult prepareFileChangeResponse(media_content_db_update_type_e u return PlatformResult(ErrorCode::NO_ERROR); } -static void contentChangeCallback(media_content_error_e error, - int pid, +static void contentChangeCallback(media_content_error_e error, int pid, media_content_db_update_item_type_e update_item, media_content_db_update_type_e update_type, - media_content_type_e media_type, - char* uuid, - char* path, - char* mime_type, - void* user_data) { + media_content_type_e media_type, char* uuid, char* path, + char* mime_type, void* user_data) { LoggerD("Entered directory and file change callback"); if (MEDIA_CONTENT_ERROR_NONE != error) { @@ -494,13 +476,14 @@ static void contentChangeCallback(media_content_error_e error, } } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(common::PlatformResult(common::ErrorCode::TYPE_MISMATCH_ERR, (name" is required argument")), &out);\ - return;\ +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(common::PlatformResult(common::ErrorCode::TYPE_MISMATCH_ERR, \ + (name " is required argument")), \ + &out); \ + return; \ } - void ContentInstance::ContentManagerUpdate(const picojson::value& args, picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -516,7 +499,8 @@ void ContentInstance::ContentManagerUpdate(const picojson::value& args, picojson } } -void ContentInstance::ContentManagerUpdatebatch(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerUpdatebatch(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); LoggerE("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -527,15 +511,15 @@ void ContentInstance::ContentManagerUpdatebatch(const picojson::value& args, pic cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerUpdatebatchCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } -void ContentInstance::ContentManagerGetdirectories(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerGetdirectories(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_EXIST(args, "callbackId", out) @@ -546,18 +530,16 @@ void ContentInstance::ContentManagerGetdirectories(const picojson::value& args, cbData->callbackId = callbackId; cbData->instance = this; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerGetdirectoriesCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); - } void ContentInstance::ContentManagerFind(const picojson::value& args, picojson::object& out) { LoggerD("entered"); - //CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); + // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -568,14 +550,13 @@ void ContentInstance::ContentManagerFind(const picojson::value& args, picojson:: cbData->callbackId = callbackId; cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerFindCallback; } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); - } void ContentInstance::ContentManagerScanfile(const picojson::value& args, picojson::object& out) { @@ -590,17 +571,16 @@ void ContentInstance::ContentManagerScanfile(const picojson::value& args, picojs cbData->callbackId = callbackId; cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerScanfileCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } - -void ContentInstance::ContentManagerScanDirectory(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerScanDirectory(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -613,14 +593,15 @@ void ContentInstance::ContentManagerScanDirectory(const picojson::value& args, p cbData->instance = this; cbData->args = args; - common::PlatformResult result = ContentManager::getInstance()->scanDirectory(ScanDirectoryCallback, cbData); + common::PlatformResult result = + ContentManager::getInstance()->scanDirectory(ScanDirectoryCallback, cbData); if (result.IsError()) { LogAndReportError(result, &out); } } - -void ContentInstance::ContentManagerCancelScanDirectory(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerCancelScanDirectory(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -629,7 +610,8 @@ void ContentInstance::ContentManagerCancelScanDirectory(const picojson::value& a if (ContentManager::getInstance()->cancelScanDirectory(content_dir_uri).IsError()) { LogAndReportError( - common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "Cancel scan directory failed"), &out); + common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "Cancel scan directory failed"), + &out); } } @@ -647,10 +629,8 @@ void ContentInstance::ContentManagerAddChangeListener(const picojson::value& arg callback_data_->cbType = ContentManagerErrorCallback; } - PlatformResult result = - ContentManager::getInstance()->addChangeListener(&listener_handle_, - contentChangeCallback, - static_cast(callback_data_)); + PlatformResult result = ContentManager::getInstance()->addChangeListener( + &listener_handle_, contentChangeCallback, static_cast(callback_data_)); if (result.IsError()) { delete callback_data_; @@ -677,9 +657,11 @@ void ContentInstance::ContentManagerRemoveChangeListener(const picojson::value& void ContentInstance::ContentManagerSetchangelistener(const picojson::value& args, picojson::object& out) { LoggerD("entered"); - LoggerW("DEPRECATION WARNING: setChangeListener() is deprecated and will be removed from next release. " + LoggerW( + "DEPRECATION WARNING: setChangeListener() is deprecated and will be removed from next " + "release. " "Use addChangeListener() instead."); - //CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); + // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "listenerId", out) @@ -696,27 +678,34 @@ void ContentInstance::ContentManagerSetchangelistener(const picojson::value& arg listener_data_->cbType = ContentManagerErrorCallback; } - if (ContentManager::getInstance()->setChangeListener(changedContentV1Callback, - static_cast(listener_data_)).IsError()) { - LogAndReportError( - common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "The callback did not register properly"), &out); + if (ContentManager::getInstance() + ->setChangeListener(changedContentV1Callback, static_cast(listener_data_)) + .IsError()) { + LogAndReportError(common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, + "The callback did not register properly"), + &out); } - if (nullptr == noti_handle_) { // To remain consistency with the previous implementation - if (ContentManager::getInstance()->addChangeListener(¬i_handle_, - changedContentV2Callback, - static_cast(listener_data_)).IsError()) { - LogAndReportError( - common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "The callback did not register properly"), &out); + if (nullptr == noti_handle_) { // To remain consistency with the previous implementation + if (ContentManager::getInstance() + ->addChangeListener(¬i_handle_, changedContentV2Callback, + static_cast(listener_data_)) + .IsError()) { + LogAndReportError(common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, + "The callback did not register properly"), + &out); } } } -void ContentInstance::ContentManagerUnsetchangelistener(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerUnsetchangelistener(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); - LoggerW("DEPRECATION WARNING: unsetChangeListener() is deprecated and will be removed from next release. " - "Use removeChangeListener() instead."); - //CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); + LoggerW( + "DEPRECATION WARNING: unsetChangeListener() is deprecated and will be removed from next " + "release. " + "Use removeChangeListener() instead."); + // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); if (ContentManager::getInstance()->unSetChangeListener().IsError()) { @@ -725,13 +714,14 @@ void ContentInstance::ContentManagerUnsetchangelistener(const picojson::value& a if (ContentManager::getInstance()->removeChangeListener(noti_handle_).IsError()) { LoggerD("unsuccesfull deregistering of callback"); } else { - noti_handle_ = nullptr; // To remain consistency with the previous implementation + noti_handle_ = nullptr; // To remain consistency with the previous implementation } } -void ContentInstance::ContentManagerGetplaylists(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerGetplaylists(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); - //CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); + // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -739,22 +729,21 @@ void ContentInstance::ContentManagerGetplaylists(const picojson::value& args, pi double callbackId = args.get("callbackId").get(); // implement it - std::shared_ptrcbData(new ReplyCallbackData); + std::shared_ptr cbData(new ReplyCallbackData); cbData->callbackId = callbackId; cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerGetplaylistsCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); - } -void ContentInstance::ContentManagerCreateplaylist(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerCreateplaylist(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -768,16 +757,16 @@ void ContentInstance::ContentManagerCreateplaylist(const picojson::value& args, cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerCreateplaylistCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } -void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -788,10 +777,9 @@ void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerRemoveplaylistCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } @@ -799,12 +787,13 @@ void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } -void ContentInstance::ContentManagerCreateThumbnail(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerCreateThumbnail(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); common::PlatformResult result = common::PlatformResult(common::ErrorCode::NO_ERROR); - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { result = ContentManager::getInstance()->createThumbnail(args); } else { result = LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "DB Connection is failed."); @@ -815,25 +804,26 @@ void ContentInstance::ContentManagerCreateThumbnail(const picojson::value& args, } } -void ContentInstance::ContentManagerPlaylistAdd(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistAdd(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { std::string playlist_id = args.get("playlistId").get(); std::string content_id = args.get("contentId").get(); int ret = ContentManager::getInstance()->playlistAdd(playlist_id, content_id); - if(ret != MEDIA_CONTENT_ERROR_NONE) { - LogAndReportError(ContentManager::getInstance()->convertError(ret),&out); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } - } - else { + } else { LogAndReportError( common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "DB connection is failed."), &out); } } -void ContentInstance::ContentManagerPlaylistAddbatch(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistAddbatch(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -844,19 +834,18 @@ void ContentInstance::ContentManagerPlaylistAddbatch(const picojson::value& args cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerPlaylistAddbatchCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } - -void ContentInstance::ContentManagerPlaylistGet(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistGet(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); - //CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); + // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -866,34 +855,34 @@ void ContentInstance::ContentManagerPlaylistGet(const picojson::value& args, pic cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerPlaylistGetCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } -void ContentInstance::ContentManagerPlaylistRemove(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistRemove(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { std::string playlist_id = args.get("playlistId").get(); int member_id = args.get("memberId").get(); int ret = ContentManager::getInstance()->playlistRemove(playlist_id, member_id); - if(ret != MEDIA_CONTENT_ERROR_NONE) { - LogAndReportError(ContentManager::getInstance()->convertError(ret),&out); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } - } - else { + } else { LogAndReportError( common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "DB connection is failed."), &out); } } -void ContentInstance::ContentManagerPlaylistRemovebatch(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistRemovebatch(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -904,17 +893,16 @@ void ContentInstance::ContentManagerPlaylistRemovebatch(const picojson::value& a cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerPlaylistRemovebatchCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } - -void ContentInstance::ContentManagerPlaylistSetorder(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistSetorder(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -925,16 +913,16 @@ void ContentInstance::ContentManagerPlaylistSetorder(const picojson::value& args cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerPlaylistSetOrderCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } -void ContentInstance::ContentManagerPlaylistMove(const picojson::value& args, picojson::object& out) { +void ContentInstance::ContentManagerPlaylistMove(const picojson::value& args, + picojson::object& out) { LoggerD("entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -945,10 +933,9 @@ void ContentInstance::ContentManagerPlaylistMove(const picojson::value& args, pi cbData->instance = this; cbData->args = args; - if(ContentManager::getInstance()->isConnected()) { + if (ContentManager::getInstance()->isConnected()) { cbData->cbType = ContentManagerPlaylistMoveCallback; - } - else { + } else { cbData->cbType = ContentManagerErrorCallback; } common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); @@ -980,10 +967,10 @@ void ContentInstance::PlaylistGetName(const picojson::value& args, picojson::obj int id = static_cast(args.get("id").get()); std::string name; ret = ContentManager::getInstance()->getPlaylistName(id, &name); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } else { - ReportSuccess(picojson::value(name),out); + ReportSuccess(picojson::value(name), out); } } @@ -997,7 +984,7 @@ void ContentInstance::PlaylistSetName(const picojson::value& args, picojson::obj int id = static_cast(args.get("id").get()); std::string name = args.get("name").get(); ret = ContentManager::getInstance()->setPlaylistName(id, name); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } else { ReportSuccess(out); @@ -1011,10 +998,10 @@ void ContentInstance::PlaylistGetThumbnailUri(const picojson::value& args, picoj int id = static_cast(args.get("id").get()); std::string uri; ret = ContentManager::getInstance()->getThumbnailUri(id, &uri); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } else { - ReportSuccess(picojson::value(uri),out); + ReportSuccess(picojson::value(uri), out); } } @@ -1028,7 +1015,7 @@ void ContentInstance::PlaylistSetThumbnailUri(const picojson::value& args, picoj int id = static_cast(args.get("id").get()); std::string uri = args.get("uri").get(); ret = ContentManager::getInstance()->setThumbnailUri(id, uri); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LogAndReportError(ContentManager::getInstance()->convertError(ret), &out); } else { ReportSuccess(out); @@ -1051,5 +1038,5 @@ void ContentInstance::PlaylistGetNumberOfTracks(const picojson::value& args, #undef CHECK_EXIST -} // namespace content -} // namespace extension +} // namespace content +} // namespace extension diff --git a/src/content/content_instance.h b/src/content/content_instance.h old mode 100755 new mode 100644 index a9d1ed3..ca5ec99 --- a/src/content/content_instance.h +++ b/src/content/content_instance.h @@ -98,15 +98,14 @@ class ContentInstance : public common::ParsedInstance { void PlaylistSetThumbnailUri(const picojson::value& args, picojson::object& out); void PlaylistGetNumberOfTracks(const picojson::value& args, picojson::object& out); - media_content_noti_h noti_handle_; // Deprecated handle + media_content_noti_h noti_handle_; // Deprecated handle media_content_noti_h listener_handle_; - ReplyCallbackData* listener_data_; // Deprecated callback data + ReplyCallbackData* listener_data_; // Deprecated callback data ReplyCallbackData* callback_data_; }; +} // namespace content +} // namespace extension -} // namespace content -} // namespace extension - -#endif // CONTENT_CONTENT_INSTANCE_H_ +#endif // CONTENT_CONTENT_INSTANCE_H_ diff --git a/src/content/content_manager.cc b/src/content/content_manager.cc index 1f2b001..3895e3e 100644 --- a/src/content/content_manager.cc +++ b/src/content/content_manager.cc @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "content/content_manager.h" +#include +#include +#include #include #include #include -#include #include #include -#include -#include #include "common/converter.h" +#include "common/filesystem/filesystem_provider.h" #include "common/logger.h" #include "common/scope_exit.h" #include "common/tools.h" -#include "common/filesystem/filesystem_provider.h" #include "content/content_filter.h" @@ -61,13 +61,13 @@ const std::map orientationMap = { std::string get_date(char* tmpStr) { LoggerD("Enter"); if (tmpStr) { - struct tm* result = (struct tm*) calloc(1, sizeof(struct tm)); + struct tm* result = (struct tm*)calloc(1, sizeof(struct tm)); if (nullptr != result) { if (strptime(tmpStr, "%Y:%m:%d %H:%M:%S", result) == NULL) { free(result); return std::string(); } else { - time_t t = mktime(result);// + get_utc_offset() * 3600; + time_t t = mktime(result); // + get_utc_offset() * 3600; std::stringstream str_date; str_date << t; free(result); @@ -100,8 +100,8 @@ void ContentToJson(media_info_h info, picojson::object& o) { o["type"] = picojson::value(std::string("IMAGE")); image_meta_h img; if (MEDIA_CONTENT_ERROR_NONE == media_info_get_image(info, &img)) { - std::unique_ptr::type, int(*)(image_meta_h)> - img_ptr(img, &image_meta_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(image_meta_h)> img_ptr( + img, &image_meta_destroy); // automatically release the memory if (MEDIA_CONTENT_ERROR_NONE == image_meta_get_date_taken(img, &tmpStr)) { if (tmpStr) { o["releaseDate"] = picojson::value(get_date(tmpStr)); @@ -160,8 +160,8 @@ void ContentToJson(media_info_h info, picojson::object& o) { o["type"] = picojson::value(std::string("VIDEO")); video_meta_h video; if (MEDIA_CONTENT_ERROR_NONE == media_info_get_video(info, &video)) { - std::unique_ptr::type, int(*)(video_meta_h)> - video_ptr(video, &video_meta_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(video_meta_h)> video_ptr( + video, &video_meta_destroy); // automatically release the memory if (MEDIA_CONTENT_ERROR_NONE == video_meta_get_width(video, &tmpInt)) { o["width"] = picojson::value(static_cast(tmpInt)); } @@ -208,10 +208,10 @@ void ContentToJson(media_info_h info, picojson::object& o) { o["type"] = picojson::value(std::string("AUDIO")); audio_meta_h audio; if (MEDIA_CONTENT_ERROR_NONE == media_info_get_audio(info, &audio)) { - std::unique_ptr::type, int(*)(audio_meta_h)> - audio_ptr(audio, &audio_meta_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(audio_meta_h)> audio_ptr( + audio, &audio_meta_destroy); // automatically release the memory if (MEDIA_CONTENT_ERROR_NONE == audio_meta_get_recorded_date(audio, &tmpStr)) { - if(tmpStr) { + if (tmpStr) { o["releaseDate"] = picojson::value(get_date(tmpStr)); free(tmpStr); tmpStr = NULL; @@ -266,8 +266,7 @@ void ContentToJson(media_info_h info, picojson::object& o) { o["trackNumber"] = picojson::value(static_cast(std::atoi(tmpStr))); free(tmpStr); tmpStr = NULL; - } - else { + } else { o["trackNumber"] = picojson::value(); } } @@ -280,16 +279,16 @@ void ContentToJson(media_info_h info, picojson::object& o) { } ret = media_info_get_media_id(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["id"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; } } ret = media_info_get_display_name(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["name"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; @@ -297,32 +296,32 @@ void ContentToJson(media_info_h info, picojson::object& o) { } ret = media_info_get_mime_type(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["mimeType"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; } } ret = media_info_get_title(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["title"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; } } ret = media_info_get_file_path(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["contentURI"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; } } ret = media_info_get_thumbnail_path(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { picojson::array thumbnails; thumbnails.push_back(picojson::value(std::string(tmpStr))); o["thumbnailURIs"] = picojson::value(thumbnails); @@ -331,27 +330,27 @@ void ContentToJson(media_info_h info, picojson::object& o) { } } ret = media_info_get_description(info, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["description"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; } } ret = media_info_get_rating(info, &tmpInt); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { o["rating"] = picojson::value(static_cast(tmpInt)); } ret = media_info_get_size(info, &tmpLong); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { o["size"] = picojson::value(static_cast(tmpLong)); } ret = media_info_get_favorite(info, &tmpBool); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { o["isFavorite"] = picojson::value(tmpBool); } ret = media_info_get_modified_time(info, &tmpDate); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { o["modifiedDate"] = picojson::value(static_cast(tmpDate)); } } @@ -365,8 +364,8 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { // id ret = media_folder_get_folder_id(folder, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["id"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; @@ -375,8 +374,8 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { // directoryURI ret = media_folder_get_path(folder, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["directoryURI"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; @@ -385,8 +384,8 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { // title ret = media_folder_get_name(folder, &tmpStr); - if(ret == MEDIA_CONTENT_ERROR_NONE) { - if(tmpStr) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { + if (tmpStr) { o["title"] = picojson::value(std::string(tmpStr)); free(tmpStr); tmpStr = NULL; @@ -395,7 +394,7 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { // storageType ret = media_folder_get_storage_type(folder, &storage_type); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { if (storage_type == MEDIA_CONTENT_STORAGE_INTERNAL) { o["storageType"] = picojson::value(std::string("INTERNAL")); } else if (storage_type == MEDIA_CONTENT_STORAGE_EXTERNAL) { @@ -407,7 +406,7 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { // modifiedData ret = media_folder_get_modified_time(folder, &tmpDate); - if(ret == MEDIA_CONTENT_ERROR_NONE) { + if (ret == MEDIA_CONTENT_ERROR_NONE) { o["modifiedDate"] = picojson::value(static_cast(tmpDate)); } } @@ -508,37 +507,30 @@ static void FolderToJson(media_folder_h folder, picojson::object* out) { int ret; ret = media_folder_get_folder_id(folder, &id); - if(ret!=MEDIA_CONTENT_ERROR_NONE) - { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LogAndReportError(ContentManager::convertError(ret), out, - ("Failed: media_folder_get_folder_id")); + ("Failed: media_folder_get_folder_id")); return; } ret = media_folder_get_name(folder, &name); - if(ret!=MEDIA_CONTENT_ERROR_NONE) - { - LogAndReportError(ContentManager::convertError(ret), out, - ("Failed: media_folder_get_name")); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + LogAndReportError(ContentManager::convertError(ret), out, ("Failed: media_folder_get_name")); free(id); return; } ret = media_folder_get_path(folder, &path); - if(ret!=MEDIA_CONTENT_ERROR_NONE) - { - LogAndReportError(ContentManager::convertError(ret), out, - ("Failed: media_folder_get_path")); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + LogAndReportError(ContentManager::convertError(ret), out, ("Failed: media_folder_get_path")); free(id); free(name); return; } ret = media_folder_get_modified_time(folder, &date); - if(ret!=MEDIA_CONTENT_ERROR_NONE) - { - LogAndReportError(ContentManager::convertError(ret), out, - ("Failed: media_folder_get_path")); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + LogAndReportError(ContentManager::convertError(ret), out, ("Failed: media_folder_get_path")); free(id); free(name); free(path); @@ -546,8 +538,7 @@ static void FolderToJson(media_folder_h folder, picojson::object* out) { } ret = media_folder_get_storage_type(folder, &storageType); - if(ret!=MEDIA_CONTENT_ERROR_NONE) - { + if (ret != MEDIA_CONTENT_ERROR_NONE) { free(id); free(name); free(path); @@ -556,7 +547,6 @@ static void FolderToJson(media_folder_h folder, picojson::object* out) { return; } - (*out)["id"] = picojson::value(std::string(id)); (*out)["directoryURI"] = picojson::value(std::string(path)); (*out)["title"] = picojson::value(std::string(name)); @@ -574,85 +564,78 @@ static void FolderToJson(media_folder_h folder, picojson::object* out) { free(path); } -static bool media_foreach_directory_cb(media_folder_h folder, void *user_data) { +static bool media_foreach_directory_cb(media_folder_h folder, void* user_data) { LoggerD("Enter"); - picojson::array *array = static_cast(user_data); + picojson::array* array = static_cast(user_data); picojson::object json; FolderToJson(folder, &json); array->push_back(picojson::value(json)); return true; } -static bool media_foreach_content_cb(media_info_h media, void *user_data) { +static bool media_foreach_content_cb(media_info_h media, void* user_data) { LoggerD("Enter"); - picojson::value::array *contents = static_cast(user_data); + picojson::value::array* contents = static_cast(user_data); picojson::value::object o; ContentToJson(media, o); contents->push_back(picojson::value(o)); return true; } -static bool playlist_foreach_cb(media_playlist_h playlist, void *user_data) { - +static bool playlist_foreach_cb(media_playlist_h playlist, void* user_data) { LoggerD("Enter"); - picojson::value::array *playlists = static_cast(user_data); + picojson::value::array* playlists = static_cast(user_data); picojson::value::object o; if (playlist != NULL) { - int id,cnt; + int id, cnt; char* thumb_path = NULL; char* name = NULL; filter_h filter = NULL; - if( media_playlist_get_playlist_id(playlist, &id) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_playlist_id(playlist, &id) == MEDIA_CONTENT_ERROR_NONE) { std::stringstream str_id; str_id << id; o["id"] = picojson::value(std::to_string(id)); - } - else { + } else { LoggerD("Invalid ID for playlist."); } - if( media_playlist_get_thumbnail_path(playlist, &thumb_path) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_thumbnail_path(playlist, &thumb_path) == MEDIA_CONTENT_ERROR_NONE) { if (thumb_path != NULL) { - std::string thumbnail_uri (thumb_path); + std::string thumbnail_uri(thumb_path); if (thumbnail_uri != " ") { thumbnail_uri = uri_prefix + thumbnail_uri; } o["thumbnailURI"] = picojson::value(thumbnail_uri); free(thumb_path); + } else { + o["thumbnailURI"] = picojson::value(); // picojson::value(std::string("")); } - else { - o["thumbnailURI"] = picojson::value();//picojson::value(std::string("")); - } - } - else { + } else { LoggerD("Invalid thumbnail path for playlist."); } - if( media_playlist_get_name(playlist, &name) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_name(playlist, &name) == MEDIA_CONTENT_ERROR_NONE) { o["name"] = picojson::value(std::string(name)); free(name); - } - else { + } else { LoggerD("Invalid name for playlist."); } media_filter_create(&filter); - std::unique_ptr::type, int(*)(filter_h)> - filter_ptr(filter, &media_filter_destroy); // automatically release the memory - if( media_playlist_get_media_count_from_db(id, filter, &cnt) == MEDIA_CONTENT_ERROR_NONE) { + std::unique_ptr::type, int (*)(filter_h)> filter_ptr( + filter, &media_filter_destroy); // automatically release the memory + if (media_playlist_get_media_count_from_db(id, filter, &cnt) == MEDIA_CONTENT_ERROR_NONE) { o["numberOfTracks"] = picojson::value(static_cast(cnt)); - } - else { + } else { LoggerE("Invalid count for playlist."); } playlists->push_back(picojson::value(o)); - } return true; } -static bool playlist_content_member_cb(int playlist_member_id, media_info_h media, void *user_data) { - +static bool playlist_content_member_cb(int playlist_member_id, media_info_h media, + void* user_data) { LoggerD("Enter"); - picojson::value::array *contents = static_cast(user_data); + picojson::value::array* contents = static_cast(user_data); picojson::value::object o; o["playlist_member_id"] = picojson::value(static_cast(playlist_member_id)); @@ -664,7 +647,7 @@ static bool playlist_content_member_cb(int playlist_member_id, media_info_h medi void CreateThumbnailCallback(media_content_error_e err, const char* path, void* user_data) { LoggerD("Enter"); - unsigned int* callbackId = (unsigned int*) user_data; + unsigned int* callbackId = (unsigned int*)user_data; if (nullptr == callbackId) { LoggerD("Callback id is null"); return; @@ -694,21 +677,20 @@ void CreateThumbnailCallback(media_content_error_e err, const char* path, void* picojson::value(out).serialize().c_str()); } - ContentManager::ContentManager() { LoggerD("ContentManager called"); - if(media_content_connect() == MEDIA_CONTENT_ERROR_NONE) { - m_dbConnected = true; + if (media_content_connect() == MEDIA_CONTENT_ERROR_NONE) { + m_dbConnected = true; + } else { + m_dbConnected = false; } - else - m_dbConnected = false; m_contentInstance = nullptr; } ContentManager::~ContentManager() { LoggerD("Enter"); - if(m_dbConnected) { - if(media_content_disconnect() == MEDIA_CONTENT_ERROR_NONE) { + if (m_dbConnected) { + if (media_content_disconnect() == MEDIA_CONTENT_ERROR_NONE) { m_dbConnected = false; } } @@ -736,7 +718,6 @@ bool ContentManager::isConnected() { } void ContentManager::getDirectories(const std::shared_ptr& user_data) { - LoggerD("Enter"); int ret; filter_h filter = NULL; @@ -757,9 +738,8 @@ void ContentManager::getDirectories(const std::shared_ptr& us ret = media_folder_foreach_folder_from_db(filter, media_foreach_directory_cb, &pico_dirs); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting the directories failed.", - ("Failed: Getting the directories failed %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting the directories failed.", + ("Failed: Getting the directories failed %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -787,11 +767,9 @@ void ContentManager::find(const std::shared_ptr& user_data) { ContentFilter filterMechanism; std::string query; picojson::object argsObject = JsonCast(user_data->args); - if (filterMechanism.BuildQuery( - FromJson(argsObject, "filter"), &query)) { + if (filterMechanism.BuildQuery(FromJson(argsObject, "filter"), &query)) { LOGGER(DEBUG) << "Filter query: " << query; - ret = media_filter_set_condition(filter, query.c_str(), - MEDIA_CONTENT_COLLATE_DEFAULT); + ret = media_filter_set_condition(filter, query.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT); if (MEDIA_CONTENT_ERROR_NONE != ret) { LoggerE("Platform filter setting failed, error %d", ret); } @@ -817,7 +795,7 @@ void ContentManager::find(const std::shared_ptr& user_data) { } ret = media_filter_set_order(filter, order, sortModeName.c_str(), - MEDIA_CONTENT_COLLATE_DEFAULT); + MEDIA_CONTENT_COLLATE_DEFAULT); if (MEDIA_CONTENT_ERROR_NONE != ret) { LoggerE("Platform SortMode setting failed, error: %d", ret); } @@ -841,18 +819,19 @@ void ContentManager::find(const std::shared_ptr& user_data) { } if (!IsNull(user_data->args.get("directoryId"))) { dirId = user_data->args.get("directoryId").get(); - ret = media_folder_foreach_media_from_db(dirId.c_str(), filter, media_foreach_content_cb, static_cast(&arrayContent)); + ret = media_folder_foreach_media_from_db(dirId.c_str(), filter, media_foreach_content_cb, + static_cast(&arrayContent)); } else { - ret = media_info_foreach_media_from_db(filter, media_foreach_content_cb, static_cast(&arrayContent)); + ret = media_info_foreach_media_from_db(filter, media_foreach_content_cb, + static_cast(&arrayContent)); } if (ret == MEDIA_CONTENT_ERROR_NONE) { user_data->result = picojson::value(arrayContent); } else { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The iteration failed in platform", - ("The iteration failed in platform: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "The iteration failed in platform", + ("The iteration failed in platform: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } } @@ -862,24 +841,25 @@ int ContentManager::scanFile(std::string& uri) { return media_content_scan_file(uri.c_str()); } -PlatformResult ContentManager::scanDirectory(media_scan_completed_cb callback, ReplyCallbackData* cbData) { +PlatformResult ContentManager::scanDirectory(media_scan_completed_cb callback, + ReplyCallbackData* cbData) { LoggerD("Enter"); const std::string& contentDirURI = cbData->args.get("contentDirURI").get(); std::string real_path = common::FilesystemProvider::Create().GetRealPath(contentDirURI); const bool recursive = cbData->args.get("recursive").get(); - int ret = media_content_scan_folder(real_path.c_str(), recursive, callback, (void*) cbData); + int ret = media_content_scan_folder(real_path.c_str(), recursive, callback, (void*)cbData); if (ret != MEDIA_CONTENT_ERROR_NONE) { if (MEDIA_CONTENT_ERROR_INVALID_PARAMETER == ret) { return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Scanning content directory failed", - ("Scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, "Scanning content directory failed", + ("Scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); } else { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Scanning content directory failed", - ("Scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Scanning content directory failed", + ("Scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); } } return PlatformResult(ErrorCode::NO_ERROR); @@ -891,24 +871,22 @@ PlatformResult ContentManager::cancelScanDirectory(const std::string& content_di int ret = media_content_cancel_scan_folder(content_dir_uri.c_str()); if (ret != MEDIA_CONTENT_ERROR_NONE) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cancel scan content directory failed", - ("Cancel scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Cancel scan content directory failed", + ("Cancel scan folder failed in platform: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult ContentManager::addChangeListener(media_content_noti_h* noti_handle, media_content_db_update_cb callback, - void *user_data) { + void* user_data) { LoggerD("Enter"); int ret = media_content_add_db_updated_cb(callback, user_data, noti_handle); if (MEDIA_CONTENT_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::ABORT_ERR, - "Failed to add the listener.", - ("Failed to add the listener: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::ABORT_ERR, "Failed to add the listener.", + ("Failed to add the listener: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -928,21 +906,20 @@ PlatformResult ContentManager::removeChangeListener(media_content_noti_h noti_ha return PlatformResult(ErrorCode::NO_ERROR); default: return LogAndCreateResult( - ErrorCode::ABORT_ERR, - "Failed to remove the listener.", + ErrorCode::ABORT_ERR, "Failed to remove the listener.", ("Failed to remove the listener: %d (%s)", ret, get_error_message(ret))); } } PlatformResult ContentManager::setChangeListener(media_content_db_update_cb callback, - void *user_data) { + void* user_data) { LoggerD("Enter"); int ret = media_content_set_db_updated_cb(callback, user_data); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "registering the listener is failed.", - ("Failed: registering the listener is failed %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "registering the listener is failed.", + ("Failed: registering the listener is failed %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -951,74 +928,70 @@ PlatformResult ContentManager::unSetChangeListener() { LoggerD("Enter"); int ret = media_content_unset_db_updated_cb(); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "unregistering the listener is failed.", - ("Failed: unregistering the listener is failed: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "unregistering the listener is failed.", + ("Failed: unregistering the listener is failed: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } void ContentManager::createPlaylist(std::string name, - const std::shared_ptr& user_data) { + const std::shared_ptr& user_data) { LoggerD("Enter"); media_playlist_h playlist = NULL; - int ret = media_playlist_insert_to_db(name.c_str(),&playlist); - std::unique_ptr::type, int(*)(media_playlist_h)> - playlist_ptr(playlist, &media_playlist_destroy); // automatically release the memory - if(ret != MEDIA_CONTENT_ERROR_NONE) { + int ret = media_playlist_insert_to_db(name.c_str(), &playlist); + std::unique_ptr::type, int (*)(media_playlist_h)> + playlist_ptr(playlist, &media_playlist_destroy); // automatically release the memory + if (ret != MEDIA_CONTENT_ERROR_NONE) { // MEDIA_CONTENT_ERROR_DB_FAILED means that playlist probably already exists - PlatformResult err = LogAndCreateResult(MEDIA_CONTENT_ERROR_DB_FAILED == ret ? - ErrorCode::INVALID_VALUES_ERR : - ErrorCode::UNKNOWN_ERR, "Creation of playlist has failed.", - ("Failed: creation of playlist is failed: %d (%s)", - ret, get_error_message(ret))); + PlatformResult err = LogAndCreateResult( + MEDIA_CONTENT_ERROR_DB_FAILED == ret ? ErrorCode::INVALID_VALUES_ERR + : ErrorCode::UNKNOWN_ERR, + "Creation of playlist has failed.", + ("Failed: creation of playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } picojson::value::object o; - if( playlist != NULL) { - int id,cnt; + if (playlist != NULL) { + int id, cnt; char* thumb_path = NULL; char* name = NULL; filter_h filter = NULL; - if( media_playlist_get_playlist_id(playlist, &id) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_playlist_id(playlist, &id) == MEDIA_CONTENT_ERROR_NONE) { o["id"] = picojson::value(std::to_string(id)); - } - else { - PlatformResult err = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "loading of playlist is failed."); + } else { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "loading of playlist is failed."); user_data->isSuccess = err; return; } - if( media_playlist_get_thumbnail_path(playlist, &thumb_path) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_thumbnail_path(playlist, &thumb_path) == MEDIA_CONTENT_ERROR_NONE) { if (thumb_path != NULL) { o["thumbnailURI"] = picojson::value(std::string(thumb_path)); free(thumb_path); - } - else { + } else { o["thumbnailURI"] = picojson::value(); } - } - else { + } else { LoggerE("Invalid thumbnail path for playlist."); } - if( media_playlist_get_name(playlist, &name) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_name(playlist, &name) == MEDIA_CONTENT_ERROR_NONE) { o["name"] = picojson::value(std::string(name)); free(name); - } - else { + } else { LoggerE("Invalid name for playlist."); } media_filter_create(&filter); - std::unique_ptr::type, int(*)(filter_h)> - filter_ptr(filter, &media_filter_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(filter_h)> filter_ptr( + filter, &media_filter_destroy); // automatically release the memory - if( media_playlist_get_media_count_from_db(id, filter, &cnt) == MEDIA_CONTENT_ERROR_NONE) { + if (media_playlist_get_media_count_from_db(id, filter, &cnt) == MEDIA_CONTENT_ERROR_NONE) { o["numberOfTracks"] = picojson::value(static_cast(cnt)); - } - else { + } else { LoggerE("Invalid count for playlist."); } } @@ -1027,21 +1000,21 @@ void ContentManager::createPlaylist(std::string name, } void ContentManager::getPlaylists(const std::shared_ptr& user_data) { - LoggerD("Enter"); int ret; filter_h filter = nullptr; media_filter_create(&filter); - std::unique_ptr::type, int(*)(filter_h)> - filter_ptr(filter, &media_filter_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(filter_h)> filter_ptr( + filter, &media_filter_destroy); // automatically release the memory picojson::value::array playlists; - ret = media_playlist_foreach_playlist_from_db(filter, playlist_foreach_cb, static_cast(&playlists)); + ret = media_playlist_foreach_playlist_from_db(filter, playlist_foreach_cb, + static_cast(&playlists)); - if(ret != MEDIA_CONTENT_ERROR_NONE) { + if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Failed: Getting playlist is failed %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Failed: Getting playlist is failed %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } @@ -1049,19 +1022,19 @@ void ContentManager::getPlaylists(const std::shared_ptr& user } void ContentManager::removePlaylist(std::string playlistId, - const std::shared_ptr& user_data) { - + const std::shared_ptr& user_data) { LoggerD("Enter"); int id = std::atoi(playlistId.c_str()); - if(id == 0) { + if (id == 0) { PlatformResult err = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "PlaylistId is wrong."); user_data->isSuccess = err; return; } int ret = media_playlist_delete_from_db(id); - if(ret != MEDIA_CONTENT_ERROR_NONE) { - PlatformResult err = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Removal of playlist is failed."); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Removal of playlist is failed."); user_data->isSuccess = err; } } @@ -1096,13 +1069,13 @@ int ContentManager::updateBatch(picojson::value args) { ret = media_info_get_media_from_db(id.c_str(), &media); if (media != NULL && ret == MEDIA_CONTENT_ERROR_NONE) { ret = setContent(media, content); - if(ret != MEDIA_CONTENT_ERROR_NONE){ + if (ret != MEDIA_CONTENT_ERROR_NONE) { LoggerE("setContent failed"); return ret; } - + ret = media_info_update_to_db(media); - if(ret != MEDIA_CONTENT_ERROR_NONE){ + if (ret != MEDIA_CONTENT_ERROR_NONE) { LoggerE("update to db failed"); } media_info_destroy(media); @@ -1122,16 +1095,15 @@ int ContentManager::playlistAdd(std::string playlist_id, std::string content_id) if (playlist != NULL && ret == MEDIA_CONTENT_ERROR_NONE) { ret = media_playlist_add_media(playlist, content_id.c_str()); if (ret != MEDIA_CONTENT_ERROR_NONE) { - LoggerE("The content(id:%s) can't add to playlist",content_id.c_str()); + LoggerE("The content(id:%s) can't add to playlist", content_id.c_str()); } ret = media_playlist_update_to_db(playlist); if (ret != MEDIA_CONTENT_ERROR_NONE) { - LoggerE("The content(id:%s) can't add to playlist",content_id.c_str()); + LoggerE("The content(id:%s) can't add to playlist", content_id.c_str()); } - } - else { - LoggerE("Playlist(id:%s) is not exist",playlist_id.c_str()); + } else { + LoggerE("Playlist(id:%s) is not exist", playlist_id.c_str()); } media_playlist_destroy(playlist); @@ -1153,28 +1125,25 @@ int ContentManager::playlistRemove(std::string playlist_id, int member_id) { if (ret != MEDIA_CONTENT_ERROR_NONE) { LoggerE("The content can't remove to playlist"); } - } - else { - LoggerE("Playlist(id:%s) is not exist",playlist_id.c_str()); + } else { + LoggerE("Playlist(id:%s) is not exist", playlist_id.c_str()); } media_playlist_destroy(playlist); return ret; } - void ContentManager::playlistAddbatch(const std::shared_ptr& user_data) { - LoggerD("Enter"); std::string playlist_id = user_data->args.get("playlistId").get(); media_playlist_h playlist = NULL; int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1190,17 +1159,16 @@ void ContentManager::playlistAddbatch(const std::shared_ptr& } ret = media_playlist_update_to_db(playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE ) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Adding playlist is failed.", - ("Adding playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Adding playlist is failed.", + ("Adding playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } media_playlist_destroy(playlist); } void ContentManager::playlistGet(const std::shared_ptr& user_data) { - LoggerD("Enter"); media_playlist_h playlist = NULL; media_content_order_e order = MEDIA_CONTENT_ORDER_ASC; @@ -1214,10 +1182,10 @@ void ContentManager::playlistGet(const std::shared_ptr& user_ std::string playlist_id = user_data->args.get("playlistId").get(); int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1225,9 +1193,9 @@ void ContentManager::playlistGet(const std::shared_ptr& user_ filter_h filter = NULL; ret = media_filter_create(&filter); if (ret != MEDIA_CONTENT_ERROR_NONE) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Creating a filter is failed.", - ("Creating a filter is failed: %d (%s)", ret, get_error_message(ret))); + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Creating a filter is failed.", + ("Creating a filter is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1244,23 +1212,22 @@ void ContentManager::playlistGet(const std::shared_ptr& user_ } picojson::value::array arrayContent; - ret = media_playlist_foreach_media_from_db(std::stoi(playlist_id), - filter, playlist_content_member_cb, static_cast(&arrayContent)); + ret = media_playlist_foreach_media_from_db(std::stoi(playlist_id), filter, + playlist_content_member_cb, + static_cast(&arrayContent)); media_filter_destroy(filter); if (ret == MEDIA_CONTENT_ERROR_NONE) { user_data->result = picojson::value(arrayContent); - } - else { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Creating a filter is failed.", - ("Creating a filter is failed: %d (%s)", ret, get_error_message(ret))); + } else { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Creating a filter is failed.", + ("Creating a filter is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } } void ContentManager::playlistRemovebatch(const std::shared_ptr& user_data) { - LoggerD("Enter"); media_playlist_h playlist = NULL; @@ -1272,10 +1239,10 @@ void ContentManager::playlistRemovebatch(const std::shared_ptrargs.get("playlistId").get(); int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1294,14 +1261,13 @@ void ContentManager::playlistRemovebatch(const std::shared_ptrisSuccess = err; } } void ContentManager::playlistSetOrder(const std::shared_ptr& user_data) { - LoggerD("Enter"); media_playlist_h playlist = NULL; @@ -1313,10 +1279,10 @@ void ContentManager::playlistSetOrder(const std::shared_ptr& std::string playlist_id = user_data->args.get("playlistId").get(); int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1325,20 +1291,19 @@ void ContentManager::playlistSetOrder(const std::shared_ptr& std::vector members = user_data->args.get("members").get(); ret = media_playlist_get_media_count_from_db(std::stoi(playlist_id), NULL, &cnt); - if(ret != MEDIA_CONTENT_ERROR_NONE) - { + if (ret != MEDIA_CONTENT_ERROR_NONE) { LoggerE("Failed: media_playlist_get_media_count_from_db"); PlatformResult err = convertError(ret); user_data->isSuccess = err; return; } std::size_t members_size = members.size(); - if (cnt < 0 || static_cast(cnt) != members_size ) { + if (cnt < 0 || static_cast(cnt) != members_size) { PlatformResult err = LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, - "The items array does not contain all items from the playlist.", - ("Failed: The items array does not contain all items from the playlist: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::INVALID_VALUES_ERR, + "The items array does not contain all items from the playlist.", + ("Failed: The items array does not contain all items from the playlist: %d (%s)", ret, + get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1354,8 +1319,8 @@ void ContentManager::playlistSetOrder(const std::shared_ptr& ret = media_playlist_update_to_db(playlist); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Removing the contents is failed.", - ("Removing the contents is failed: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Removing the contents is failed.", + ("Removing the contents is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } } @@ -1372,10 +1337,10 @@ void ContentManager::playlistMove(const std::shared_ptr& user std::string playlist_id = user_data->args.get("playlistId").get(); int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); - if(ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { - PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", - ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); + if (ret != MEDIA_CONTENT_ERROR_NONE && playlist == NULL) { + PlatformResult err = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Getting playlist is failed.", + ("Getting playlist is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1385,8 +1350,8 @@ void ContentManager::playlistMove(const std::shared_ptr& user ret = media_playlist_get_play_order(playlist, static_cast(member_id), &old_order); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The content can't find form playlist.", - ("The content can't find form playlist: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "The content can't find form playlist.", + ("The content can't find form playlist: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } @@ -1394,16 +1359,16 @@ void ContentManager::playlistMove(const std::shared_ptr& user ret = media_playlist_set_play_order(playlist, static_cast(member_id), new_order); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The content can't update play_order.", - ("The content can't update play_order: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "The content can't update play_order.", + ("The content can't update play_order: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; return; } ret = media_playlist_update_to_db(playlist); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Updateing play_order is failed.", - ("Updateing play_order is failed: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Updateing play_order is failed.", + ("Updateing play_order is failed: %d (%s)", ret, get_error_message(ret))); user_data->isSuccess = err; } } @@ -1420,8 +1385,8 @@ int ContentManager::getLyrics(const picojson::value& args, picojson::object& res metadata_extractor_h extractor; metadata_extractor_create(&extractor); - std::unique_ptr::type, int(*)(metadata_extractor_h)> - extractor_ptr(extractor, &metadata_extractor_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(metadata_extractor_h)> + extractor_ptr(extractor, &metadata_extractor_destroy); // automatically release the memory ret = metadata_extractor_set_path(extractor, contentURI.c_str()); if (ret != METADATA_EXTRACTOR_ERROR_NONE) { @@ -1432,8 +1397,7 @@ int ContentManager::getLyrics(const picojson::value& args, picojson::object& res picojson::array texts = picojson::array(); char* strSyncTextNum = NULL; - ret = metadata_extractor_get_metadata(extractor, - METADATA_SYNCLYRICS_NUM, &strSyncTextNum); + ret = metadata_extractor_get_metadata(extractor, METADATA_SYNCLYRICS_NUM, &strSyncTextNum); if (ret != METADATA_EXTRACTOR_ERROR_NONE) { LOGGER(ERROR) << "Media extractor error " << ret; return ret; @@ -1462,8 +1426,7 @@ int ContentManager::getLyrics(const picojson::value& args, picojson::object& res ret = METADATA_EXTRACTOR_ERROR_NONE; } else { char* unSyncText = nullptr; - ret = metadata_extractor_get_metadata(extractor, METADATA_UNSYNCLYRICS, - &unSyncText); + ret = metadata_extractor_get_metadata(extractor, METADATA_UNSYNCLYRICS, &unSyncText); if (ret == METADATA_EXTRACTOR_ERROR_NONE) { result["type"] = picojson::value(std::string("UNSYNCHRONIZED")); if (nullptr == unSyncText) { @@ -1478,13 +1441,11 @@ int ContentManager::getLyrics(const picojson::value& args, picojson::object& res return ret; } -media_playlist_h getPlaylistHandle(int id) -{ +media_playlist_h getPlaylistHandle(int id) { LoggerD("Entered"); media_playlist_h playlist_handle = nullptr; int ret_code = media_playlist_get_playlist_from_db(id, &playlist_handle); - if(MEDIA_CONTENT_ERROR_NONE != ret_code || - playlist_handle == nullptr) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code || playlist_handle == nullptr) { LoggerE("could not get playlist handle for id: %d", id); return nullptr; } @@ -1492,14 +1453,13 @@ media_playlist_h getPlaylistHandle(int id) return playlist_handle; } -void destroyMediaPlaylistHandle(media_playlist_h& playlist_handle) -{ +void destroyMediaPlaylistHandle(media_playlist_h& playlist_handle) { LoggerD("Entered"); - if(playlist_handle) { + if (playlist_handle) { int ret_code = media_playlist_destroy(playlist_handle); playlist_handle = nullptr; - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_destroy failed"); } } @@ -1513,13 +1473,13 @@ int ContentManager::getPlaylistName(int id, std::string* result) { char* tmp_playlist_name = nullptr; const int ret_code = media_playlist_get_name(playlist_handle, &tmp_playlist_name); - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_get_name failed"); return TIZEN_ERROR_UNKNOWN; } std::string playlist_name; - if(tmp_playlist_name) { + if (tmp_playlist_name) { playlist_name = tmp_playlist_name; free(tmp_playlist_name); tmp_playlist_name = nullptr; @@ -1529,21 +1489,19 @@ int ContentManager::getPlaylistName(int id, std::string* result) { return MEDIA_CONTENT_ERROR_NONE; } -int updatePlaylistInDB(media_playlist_h playlist_handle) -{ +int updatePlaylistInDB(media_playlist_h playlist_handle) { LoggerD("Entered"); int ret_code = media_playlist_update_to_db(playlist_handle); - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_update_to_db failed"); return ret_code; } return MEDIA_CONTENT_ERROR_NONE; } -int ContentManager::setPlaylistName(int id, const std::string& name) -{ +int ContentManager::setPlaylistName(int id, const std::string& name) { LoggerD("Entered"); - if(name.empty()) { + if (name.empty()) { LoggerE("Cannot set empty playlist name!"); return MEDIA_CONTENT_ERROR_INVALID_PARAMETER; } @@ -1552,10 +1510,10 @@ int ContentManager::setPlaylistName(int id, const std::string& name) PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); const int ret_code = media_playlist_set_name(playlist_handle, name.c_str()); - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_set_name failed"); - //Setting name that is used by other playlist does not return bad error code here. - //MEDIA_CONTENT_ERROR_INVALID_OPERATION is being returned in updatePlaylistInDB + // Setting name that is used by other playlist does not return bad error code here. + // MEDIA_CONTENT_ERROR_INVALID_OPERATION is being returned in updatePlaylistInDB return TIZEN_ERROR_UNKNOWN; } @@ -1563,8 +1521,8 @@ int ContentManager::setPlaylistName(int id, const std::string& name) if (MEDIA_CONTENT_ERROR_NONE != ret) { LoggerE("Error while updating playlist: %d", ret); if (MEDIA_CONTENT_ERROR_DB_FAILED == ret) { - //We could fetch list of playlists and check if other playlist is using this - //name, but that seems to be to much work in synchronous method + // We could fetch list of playlists and check if other playlist is using this + // name, but that seems to be to much work in synchronous method LoggerE("Playlist name: %s is probably already used", name.c_str()); return MEDIA_CONTENT_ERROR_INVALID_PARAMETER; } @@ -1573,8 +1531,7 @@ int ContentManager::setPlaylistName(int id, const std::string& name) return MEDIA_CONTENT_ERROR_NONE; } -int ContentManager::getThumbnailUri(int id, std::string* result) -{ +int ContentManager::getThumbnailUri(int id, std::string* result) { LoggerD("Entered"); media_playlist_h playlist_handle = getPlaylistHandle(id); PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); @@ -1582,13 +1539,13 @@ int ContentManager::getThumbnailUri(int id, std::string* result) char* tmp_playlist_thb_path = nullptr; const int ret_code = media_playlist_get_thumbnail_path(playlist_handle, &tmp_playlist_thb_path); - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_get_name failed"); return TIZEN_ERROR_UNKNOWN; } std::string playlist_thb_path; - if(tmp_playlist_thb_path) { + if (tmp_playlist_thb_path) { playlist_thb_path = tmp_playlist_thb_path; free(tmp_playlist_thb_path); tmp_playlist_thb_path = nullptr; @@ -1602,14 +1559,13 @@ int ContentManager::getThumbnailUri(int id, std::string* result) return MEDIA_CONTENT_ERROR_NONE; } -int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) -{ +int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) { LoggerD("Entered"); - //Allow setting empty URI, unfortunately Core API does not allow to set empty - //path so we need to set one empty space. This is probably issue of Core API. - if(!thb_uri.empty() && " " != thb_uri) { - if(thb_uri.find(uri_absolute_prefix) != 0) { + // Allow setting empty URI, unfortunately Core API does not allow to set empty + // path so we need to set one empty space. This is probably issue of Core API. + if (!thb_uri.empty() && " " != thb_uri) { + if (thb_uri.find(uri_absolute_prefix) != 0) { LoggerE("thumbnail URI is not valid: [%s]", thb_uri.c_str()); return MEDIA_CONTENT_ERROR_INVALID_PARAMETER; } @@ -1619,9 +1575,8 @@ int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); std::string real_path = common::FilesystemProvider::Create().GetRealPath(thb_uri); - const int ret_code = media_playlist_set_thumbnail_path(playlist_handle, - real_path.c_str()); - if(MEDIA_CONTENT_ERROR_NONE != ret_code) { + const int ret_code = media_playlist_set_thumbnail_path(playlist_handle, real_path.c_str()); + if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_set_thumbnail_path failed"); return TIZEN_ERROR_UNKNOWN; } @@ -1634,8 +1589,7 @@ int ContentManager::getNumberOfTracks(int id, int* result) { LoggerD("Entered"); int count = 0; - const int ret_code = media_playlist_get_media_count_from_db(id, nullptr, - &count); + const int ret_code = media_playlist_get_media_count_from_db(id, nullptr, &count); if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_get_media_count_from_db failed"); @@ -1649,12 +1603,13 @@ int ContentManager::getNumberOfTracks(int id, int* result) { common::PlatformResult ContentManager::createThumbnail(const picojson::value& args) { LoggerD("Enter"); - unsigned int* callbackId = new unsigned int(static_cast(args.get("callbackId").get())); + unsigned int* callbackId = + new unsigned int(static_cast(args.get("callbackId").get())); std::string id = args.get("id").get(); media_info_h media = NULL; int ret = media_info_get_media_from_db(id.c_str(), &media); - if(MEDIA_CONTENT_ERROR_NONE != ret && nullptr == media) { + if (MEDIA_CONTENT_ERROR_NONE != ret && nullptr == media) { delete callbackId; return LogAndCreateResult(ErrorCode::ABORT_ERR, "Getting media is failed.", ("Getting media is failed: %d (%s)", ret, get_error_message(ret))); @@ -1662,7 +1617,7 @@ common::PlatformResult ContentManager::createThumbnail(const picojson::value& ar ret = media_info_create_thumbnail(media, CreateThumbnailCallback, (void*)callbackId); media_info_destroy(media); - if(MEDIA_CONTENT_ERROR_NONE != ret) { + if (MEDIA_CONTENT_ERROR_NONE != ret) { delete callbackId; return LogAndCreateResult(ErrorCode::ABORT_ERR, "Creating thumbnail failed.", ("Creating thumbnail failed: %d (%s)", ret, get_error_message(ret))); @@ -1674,28 +1629,28 @@ common::PlatformResult ContentManager::createThumbnail(const picojson::value& ar PlatformResult ContentManager::convertError(int err) { char* error_msg = get_error_message(err); switch (err) { - case MEDIA_CONTENT_ERROR_INVALID_PARAMETER : + case MEDIA_CONTENT_ERROR_INVALID_PARAMETER: return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, error_msg); - case MEDIA_CONTENT_ERROR_OUT_OF_MEMORY : + case MEDIA_CONTENT_ERROR_OUT_OF_MEMORY: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_INVALID_OPERATION : + case MEDIA_CONTENT_ERROR_INVALID_OPERATION: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_FILE_NO_SPACE_ON_DEVICE : + case MEDIA_CONTENT_FILE_NO_SPACE_ON_DEVICE: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_PERMISSION_DENIED : + case MEDIA_CONTENT_ERROR_PERMISSION_DENIED: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_DB_FAILED : + case MEDIA_CONTENT_ERROR_DB_FAILED: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_DB_BUSY : + case MEDIA_CONTENT_ERROR_DB_BUSY: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_NETWORK : + case MEDIA_CONTENT_ERROR_NETWORK: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); - case MEDIA_CONTENT_ERROR_UNSUPPORTED_CONTENT : + case MEDIA_CONTENT_ERROR_UNSUPPORTED_CONTENT: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); default: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error."); } } -} // namespace content -} // namespace extension +} // namespace content +} // namespace extension diff --git a/src/content/content_manager.h b/src/content/content_manager.h index 5c8ed6d..d09adff 100644 --- a/src/content/content_manager.h +++ b/src/content/content_manager.h @@ -18,9 +18,9 @@ #define CONTENT_MANAGER_H_ #include -#include #include #include +#include #include #include @@ -32,8 +32,8 @@ namespace extension { namespace content { -typedef std::unique_ptr::type, - void (*)(media_playlist_h&)> PlaylistUniquePtr; +typedef std::unique_ptr::type, void (*)(media_playlist_h&)> + PlaylistUniquePtr; void ContentToJson(media_info_h info, picojson::object& o); void ContentDirToJson(media_folder_h folder, picojson::object& o); @@ -55,17 +55,15 @@ class ContentManager { common::PlatformResult scanDirectory(media_scan_completed_cb callback, ReplyCallbackData* cbData); common::PlatformResult cancelScanDirectory(const std::string& content_dir_uri); common::PlatformResult addChangeListener(media_content_noti_h* noti_handle, - media_content_db_update_cb callback, - void *user_data); + media_content_db_update_cb callback, void* user_data); common::PlatformResult removeChangeListener(media_content_noti_h noti_handle); - common::PlatformResult setChangeListener(media_content_db_update_cb callback, - void *user_data); + common::PlatformResult setChangeListener(media_content_db_update_cb callback, void* user_data); common::PlatformResult unSetChangeListener(); -//Lyrics - int getLyrics(const picojson::value& args,picojson::object& result); + // Lyrics + int getLyrics(const picojson::value& args, picojson::object& result); -//playlist + // playlist void createPlaylist(std::string name, const std::shared_ptr& user_data); void getPlaylists(const std::shared_ptr& user_data); void removePlaylist(std::string playlistId, const std::shared_ptr& user_data); @@ -81,26 +79,24 @@ class ContentManager { int getNumberOfTracks(int id, int* result); -//playlistSetOrder + // playlistSetOrder static common::PlatformResult convertError(int err); -//thumbnail + // thumbnail int getThumbnailUri(int id, std::string* result); int setThumbnailUri(int id, const std::string& thb_uri); common::PlatformResult createThumbnail(const picojson::value& args); private: - //int setContent(media_info_h media, picojson::value content); + // int setContent(media_info_h media, picojson::value content); ContentManager(); private: bool m_dbConnected; ContentInstance* m_contentInstance; - }; -} // namespace power -} // namespace extension +} // namespace power +} // namespace extension #endif - diff --git a/src/convergence/convergence_app_communication_service.cc b/src/convergence/convergence_app_communication_service.cc index 5d40451..f4ac7d1 100644 --- a/src/convergence/convergence_app_communication_service.cc +++ b/src/convergence/convergence_app_communication_service.cc @@ -17,17 +17,17 @@ // TODO check includes #include "convergence/convergence_app_communication_service.h" -#include #include +#include #include #include -#include "convergence/convergence_instance.h" +#include "common/logger.h" #include "convergence/convergence_channel_info.h" -#include "convergence/convergence_payload.h" #include "convergence/convergence_client_info.h" +#include "convergence/convergence_instance.h" +#include "convergence/convergence_payload.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -38,15 +38,15 @@ using common::TizenSuccess; namespace { static const std::string kChannel = "channel"; static const std::string kClientInfo = "clientInfo"; -} // namespace +} // namespace -ConvergenceAppCommunicationService::ConvergenceAppCommunicationService() - : ConvergenceService() { +ConvergenceAppCommunicationService::ConvergenceAppCommunicationService() : ConvergenceService() { ScopeLogger(); } -ConvergenceAppCommunicationService::ConvergenceAppCommunicationService(conv_device_h device, ConvergenceInstance *convergence_plugin) - : ConvergenceService(device, CONV_SERVICE_APP_TO_APP_COMMUNICATION, convergence_plugin) { +ConvergenceAppCommunicationService::ConvergenceAppCommunicationService( + conv_device_h device, ConvergenceInstance *convergence_plugin) + : ConvergenceService(device, CONV_SERVICE_APP_TO_APP_COMMUNICATION, convergence_plugin) { ScopeLogger(); } @@ -60,13 +60,12 @@ ConvergenceAppCommunicationService::~ConvergenceAppCommunicationService() { callback_param_gc_.clear(); } -common::TizenResult ConvergenceAppCommunicationService::Start( - ConvergenceChannel* channel, - const int cur_listener_id) { +common::TizenResult ConvergenceAppCommunicationService::Start(ConvergenceChannel *channel, + const int cur_listener_id) { ScopeLogger(); LoggerI("Starting service [0x%x] with handle [0x%x]", this, service_handle_); - std::unique_ptr ch_ptr(channel); // auto release memory in case of error + std::unique_ptr ch_ptr(channel); // auto release memory in case of error conv_service_h service_handle = FindServiceHandle(); if (!service_handle) { @@ -74,9 +73,9 @@ common::TizenResult ConvergenceAppCommunicationService::Start( } bool is_started = false; - //regarding to native team returned value should not be checked - //as CONV_ERROR_NONE means service is started, otherwise not started - //check only passed bool variable + // regarding to native team returned value should not be checked + // as CONV_ERROR_NONE means service is started, otherwise not started + // check only passed bool variable conv_service_is_started(service_handle, channel->GetHandle(), &is_started); if (is_started) { @@ -86,26 +85,25 @@ common::TizenResult ConvergenceAppCommunicationService::Start( param[kServiceResultType] = picojson::value("onStart"); // totu - convergence_plugin_->ReplyAsync(kAppCommunicationListenerCallback, - cur_listener_id, true, param); + convergence_plugin_->ReplyAsync(kAppCommunicationListenerCallback, cur_listener_id, true, + param); } else { UpdateListener(cur_listener_id, REMOTE_SERVICE_START); - + const int error = conv_service_start(service_handle, channel->GetHandle(), nullptr); if (CONV_ERROR_NONE != error) { LoggerD("conv_service_start [fail] %d %s", error, get_error_message(error)); return LogAndCreateTizenError(AbortError, "conv_service_start [fail]"); } - + opened_channels.push_back(ch_ptr.release()); } return TizenSuccess(); } -common::TizenResult ConvergenceAppCommunicationService::Stop( - ConvergenceChannel* channel, - const int cur_listener_id) { +common::TizenResult ConvergenceAppCommunicationService::Stop(ConvergenceChannel *channel, + const int cur_listener_id) { ScopeLogger(); conv_service_h service_handle = FindServiceHandle(); @@ -126,7 +124,7 @@ common::TizenResult ConvergenceAppCommunicationService::Stop( return TizenSuccess(); } -common::TizenResult ConvergenceAppCommunicationService::GetClientList(ConvergenceChannel* channel, +common::TizenResult ConvergenceAppCommunicationService::GetClientList(ConvergenceChannel *channel, const int cur_listener_id) { ScopeLogger(); @@ -145,10 +143,9 @@ common::TizenResult ConvergenceAppCommunicationService::GetClientList(Convergenc return TizenSuccess(); } -common::TizenResult ConvergenceAppCommunicationService::Send( - ConvergenceChannel* channel, - ConvergencePayloadArray& payload, - const int cur_listener_id) { +common::TizenResult ConvergenceAppCommunicationService::Send(ConvergenceChannel *channel, + ConvergencePayloadArray &payload, + const int cur_listener_id) { ScopeLogger(); conv_service_h service_handle = FindServiceHandle(); @@ -170,10 +167,10 @@ common::TizenResult ConvergenceAppCommunicationService::Send( // TODO move to Payload class - void ConvergenceAppCommunicationService::ServiceListenerCb(conv_service_h service_handle, - conv_channel_h channel_handle, - conv_error_e error, conv_payload_h result, void* user_data) { + conv_channel_h channel_handle, + conv_error_e error, + conv_payload_h result, void *user_data) { ScopeLogger(); CallbackParam *callbackParam = static_cast(user_data); @@ -187,16 +184,19 @@ void ConvergenceAppCommunicationService::ServiceListenerCb(conv_service_h servic // TODO parse the payload and fill the param LoggerI("YAY! Got the Callback (TODO implement it)"); - if (CONV_ERROR_NONE != error) { // Error occured during connection + if (CONV_ERROR_NONE != error) { // Error occured during connection picojson::object param; - param[kServiceListenerError] = LogAndCreateTizenError(AbortError, "DiscoveryCb return CONV_DISCOVERY_RESULT_ERROR").ToJSON(); + param[kServiceListenerError] = + LogAndCreateTizenError(AbortError, "DiscoveryCb return CONV_DISCOVERY_RESULT_ERROR") + .ToJSON(); callbackParam->plugin_->ReplyAsync(kAppCommunicationListenerCallback, - callbackParam->callback_id_, false, param); + callbackParam->callback_id_, false, param); return; } // Parse the payload - const std::string result_type = ConvergencePayloadArray::ExtractPayloadString(result, kServiceResultType.c_str()); + const std::string result_type = + ConvergencePayloadArray::ExtractPayloadString(result, kServiceResultType.c_str()); LoggerI("Callback type [%s]", result_type.c_str()); picojson::object param; @@ -208,12 +208,12 @@ void ConvergenceAppCommunicationService::ServiceListenerCb(conv_service_h servic if (callbackParam->client_info_) { param[kClientInfo] = callbackParam->client_info_->ToJson(); } - } else if ((kServiceResultTypeOnPublish == result_type) - || (kServiceResultTypeOnStop == result_type)) { + } else if ((kServiceResultTypeOnPublish == result_type) || + (kServiceResultTypeOnStop == result_type)) { // The service doesn't send any callback with thie response } else if (kServiceResultTypeOnMessage == result_type) { - param["senderId"] = picojson::value( - ConvergencePayloadArray::ExtractPayloadString(result, "from")); // Define the string as a constant + param["senderId"] = picojson::value(ConvergencePayloadArray::ExtractPayloadString( + result, "from")); // Define the string as a constant param[kPayload] = ConvergencePayloadArray::ToJson(result); } else if (kServiceResultTypeOnConnect == result_type) { // just filling client_info_ member in CallbackParam @@ -232,11 +232,11 @@ void ConvergenceAppCommunicationService::ServiceListenerCb(conv_service_h servic } } else if (kServiceResultTypeOnClientConnect == result_type) { // TODO the service doesn't send any callback with thie response - return; // TODO + return; // TODO } else if (kServiceResultTypeOnDisconnect == result_type) { - return; // TODO + return; // TODO } else if (kServiceResultTypeOnClientDisconnect == result_type) { - return; // TODO + return; // TODO } else if (kServiceResultTypeOnRead == result_type) { param[kPayload] = ConvergencePayloadArray::ToJson(result); } else { @@ -245,8 +245,8 @@ void ConvergenceAppCommunicationService::ServiceListenerCb(conv_service_h servic return; } - callbackParam->plugin_->ReplyAsync(kAppCommunicationListenerCallback, - callbackParam->callback_id_, true, param); + callbackParam->plugin_->ReplyAsync(kAppCommunicationListenerCallback, callbackParam->callback_id_, + true, param); } void ConvergenceAppCommunicationService::UpdateListener(const int cur_listener_id, @@ -261,7 +261,7 @@ void ConvergenceAppCommunicationService::UpdateListener(const int cur_listener_i return; } - { // dbg + { // dbg LoggerI("...found service handle [%x0x]", service_handle); conv_service_e t = CONV_SERVICE_NONE; @@ -331,13 +331,13 @@ common::TizenResult ConvergenceAppCommunicationService::RemoveListener() { } ConvergenceAppCommunicationServerService::ConvergenceAppCommunicationServerService() - : ConvergenceAppCommunicationService() { + : ConvergenceAppCommunicationService() { ScopeLogger(); } ConvergenceAppCommunicationServerService::ConvergenceAppCommunicationServerService( - conv_device_h device, ConvergenceInstance *convergence_plugin) - : ConvergenceAppCommunicationService(device, convergence_plugin) { + conv_device_h device, ConvergenceInstance *convergence_plugin) + : ConvergenceAppCommunicationService(device, convergence_plugin) { ScopeLogger(); // Creating the handle of local service instance @@ -359,7 +359,8 @@ ConvergenceAppCommunicationServerService::ConvergenceAppCommunicationServerServi * - Version */ - error = conv_service_set_property_string(service_handle_, CONV_SERVICE_ID, "test_app"); // TODO set a proper service ID + error = conv_service_set_property_string(service_handle_, CONV_SERVICE_ID, + "test_app"); // TODO set a proper service ID if (CONV_ERROR_NONE != error) { // TODO: Handle error trace_conv_error(error, __LINE__, "conv_service_set_property Id"); @@ -376,24 +377,22 @@ ConvergenceAppCommunicationServerService::~ConvergenceAppCommunicationServerServ ScopeLogger(); } -common::TizenResult ConvergenceAppCommunicationServerService::Start( - ConvergenceChannel* channel, - const int cur_listener_id) { +common::TizenResult ConvergenceAppCommunicationServerService::Start(ConvergenceChannel *channel, + const int cur_listener_id) { ScopeLogger(); LoggerI("Starting service [0x%x] with handle [0x%x]", this, service_handle_); - std::unique_ptr ch_ptr(channel); // auto release memory in case of error + std::unique_ptr ch_ptr(channel); // auto release memory in case of error conv_service_h service_handle = FindServiceHandle(); if (!service_handle) { return LogAndCreateTizenError(AbortError, "Service with specified type does not exist"); } - bool is_started = false; - //regarding to native team returned value should not be checked - //as CONV_ERROR_NONE means service is started, otherwise not started - //check only passed bool variable + // regarding to native team returned value should not be checked + // as CONV_ERROR_NONE means service is started, otherwise not started + // check only passed bool variable conv_service_is_started(service_handle, channel->GetHandle(), &is_started); if (is_started) { @@ -403,26 +402,25 @@ common::TizenResult ConvergenceAppCommunicationServerService::Start( param[kServiceResultType] = picojson::value("onStart"); // totu - convergence_plugin_->ReplyAsync(kAppCommunicationListenerCallback, - cur_listener_id, true, param); + convergence_plugin_->ReplyAsync(kAppCommunicationListenerCallback, cur_listener_id, true, + param); } else { UpdateListener(cur_listener_id, LOCAL_SERVICE_START); - + const int error = conv_service_start(service_handle, channel->GetHandle(), nullptr); if (CONV_ERROR_NONE != error) { LoggerD("conv_service_start [fail] %d %s", error, get_error_message(error)); return LogAndCreateTizenError(AbortError, "conv_service_start [fail]"); } - + opened_channels.push_back(ch_ptr.release()); } return TizenSuccess(); } -common::TizenResult ConvergenceAppCommunicationServerService::Stop( - ConvergenceChannel* channel, - const int cur_listener_id) { +common::TizenResult ConvergenceAppCommunicationServerService::Stop(ConvergenceChannel *channel, + const int cur_listener_id) { ScopeLogger(); /* By implementation, the local App Communication Service doesn't send @@ -445,13 +443,13 @@ common::TizenResult ConvergenceAppCommunicationServerService::Stop( } ConvergenceAppCommunicationClientService::ConvergenceAppCommunicationClientService() - : ConvergenceAppCommunicationService() { + : ConvergenceAppCommunicationService() { ScopeLogger(); } ConvergenceAppCommunicationClientService::ConvergenceAppCommunicationClientService( - conv_device_h device, ConvergenceInstance *convergence_plugin) - : ConvergenceAppCommunicationService(device, convergence_plugin) { + conv_device_h device, ConvergenceInstance *convergence_plugin) + : ConvergenceAppCommunicationService(device, convergence_plugin) { ScopeLogger(); } @@ -460,7 +458,9 @@ ConvergenceAppCommunicationClientService::~ConvergenceAppCommunicationClientServ } void ConvergenceAppCommunicationClientService::ServiceConnectedCb(conv_service_h service_handle, - conv_error_e error, conv_payload_h result, void* user_data) { + conv_error_e error, + conv_payload_h result, + void *user_data) { ScopeLogger(); CallbackParam *callbackParam = static_cast(user_data); @@ -476,16 +476,12 @@ void ConvergenceAppCommunicationClientService::ServiceConnectedCb(conv_service_h if (CONV_ERROR_NONE == error) { param[kServiceConnectionStatus] = picojson::value(kServiceConnectionStatusConnected); callbackParam->plugin_->ReplyAsync(kAppCommunicationListenerCallback, - callbackParam->callback_id_, - true, - param); + callbackParam->callback_id_, true, param); } else { // Error occured during connection param[kServiceConnectionStatus] = picojson::value(kServiceConnectionStatusNotConnected); callbackParam->plugin_->ReplyAsync(kAppCommunicationListenerCallback, - callbackParam->callback_id_, - false, - param); + callbackParam->callback_id_, false, param); } } @@ -516,8 +512,7 @@ common::TizenResult ConvergenceAppCommunicationClientService::Disconnect() { ScopeLogger(); conv_service_h service = FindServiceHandle(); - if (!service) - return LogAndCreateTizenError(AbortError, "Service is NULL"); + if (!service) return LogAndCreateTizenError(AbortError, "Service is NULL"); int error = conv_service_disconnect(service); if (CONV_ERROR_NONE != error) { @@ -531,8 +526,7 @@ common::TizenResult ConvergenceAppCommunicationClientService::Disconnect() { LoggerE("Error gathering state [%d] : %s", error, get_error_message(error)); return LogAndCreateTizenError(AbortError, "Error gathering state"); } else { - LoggerD("state: %d" , state); - + LoggerD("state: %d", state); } if (CONV_SERVICE_CONNECTION_STATE_NOT_CONNECTED == state) { return TizenSuccess(); @@ -542,6 +536,5 @@ common::TizenResult ConvergenceAppCommunicationClientService::Disconnect() { } } - -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension diff --git a/src/convergence/convergence_app_communication_service.h b/src/convergence/convergence_app_communication_service.h index 10ec5d9..e77113b 100644 --- a/src/convergence/convergence_app_communication_service.h +++ b/src/convergence/convergence_app_communication_service.h @@ -23,9 +23,9 @@ #include #include +#include "common/tizen_result.h" #include "convergence/convergence_service.h" #include "convergence/convergence_utils.h" -#include "common/tizen_result.h" namespace extension { namespace convergence { @@ -36,69 +36,74 @@ class ConvergencePayloadArray; class ConvergenceAppCommunicationService : public ConvergenceService { public: ConvergenceAppCommunicationService(); - ConvergenceAppCommunicationService(conv_device_h device, ConvergenceInstance *convergence_plugin); + ConvergenceAppCommunicationService(conv_device_h device, ConvergenceInstance* convergence_plugin); virtual ~ConvergenceAppCommunicationService(); ConvergenceAppCommunicationService(const ConvergenceAppCommunicationService&) = delete; ConvergenceAppCommunicationService(ConvergenceAppCommunicationService&&) = delete; ConvergenceAppCommunicationService& operator=(const ConvergenceAppCommunicationService&) = delete; ConvergenceAppCommunicationService& operator=(ConvergenceAppCommunicationService&&) = delete; + public: - virtual common::TizenResult Start(ConvergenceChannel* channel, - const int cur_listener_id); - virtual common::TizenResult Stop(ConvergenceChannel* channel, - const int cur_listener_id); - virtual common::TizenResult GetClientList(ConvergenceChannel* channel, - const int cur_listener_id); - virtual common::TizenResult Send(ConvergenceChannel* channel, - ConvergencePayloadArray& payload, + virtual common::TizenResult Start(ConvergenceChannel* channel, const int cur_listener_id); + virtual common::TizenResult Stop(ConvergenceChannel* channel, const int cur_listener_id); + virtual common::TizenResult GetClientList(ConvergenceChannel* channel, const int cur_listener_id); + virtual common::TizenResult Send(ConvergenceChannel* channel, ConvergencePayloadArray& payload, const int cur_listener_id); common::TizenResult SetListener(const int cur_listener_id); common::TizenResult RemoveListener(); + private: - static void ServiceListenerCb(conv_service_h service_handle, - conv_channel_h channel_handle, - conv_error_e error, conv_payload_h result, void* user_data); + static void ServiceListenerCb(conv_service_h service_handle, conv_channel_h channel_handle, + conv_error_e error, conv_payload_h result, void* user_data); protected: void UpdateListener(const int cur_listener_id, ServiceRequestType type = UNKNOWN_REQUEST_TYPE); - std::vector callback_param_gc_; + std::vector callback_param_gc_; }; class ConvergenceAppCommunicationServerService : public ConvergenceAppCommunicationService { public: ConvergenceAppCommunicationServerService(); - ConvergenceAppCommunicationServerService(conv_device_h device, ConvergenceInstance *convergence_plugin); + ConvergenceAppCommunicationServerService(conv_device_h device, + ConvergenceInstance* convergence_plugin); virtual ~ConvergenceAppCommunicationServerService(); - ConvergenceAppCommunicationServerService(const ConvergenceAppCommunicationServerService&) = delete; + ConvergenceAppCommunicationServerService(const ConvergenceAppCommunicationServerService&) = + delete; ConvergenceAppCommunicationServerService(ConvergenceAppCommunicationServerService&&) = delete; - ConvergenceAppCommunicationServerService& operator=(const ConvergenceAppCommunicationServerService&) = delete; - ConvergenceAppCommunicationServerService& operator=(ConvergenceAppCommunicationServerService&&) = delete; + ConvergenceAppCommunicationServerService& operator=( + const ConvergenceAppCommunicationServerService&) = delete; + ConvergenceAppCommunicationServerService& operator=(ConvergenceAppCommunicationServerService&&) = + delete; public: - virtual common::TizenResult Start(ConvergenceChannel* channel, - const int cur_listener_id); - virtual common::TizenResult Stop(ConvergenceChannel* channel, - const int cur_listener_id); + virtual common::TizenResult Start(ConvergenceChannel* channel, const int cur_listener_id); + virtual common::TizenResult Stop(ConvergenceChannel* channel, const int cur_listener_id); }; class ConvergenceAppCommunicationClientService : public ConvergenceAppCommunicationService { public: ConvergenceAppCommunicationClientService(); - ConvergenceAppCommunicationClientService(conv_device_h device, ConvergenceInstance *convergence_plugin); + ConvergenceAppCommunicationClientService(conv_device_h device, + ConvergenceInstance* convergence_plugin); virtual ~ConvergenceAppCommunicationClientService(); - ConvergenceAppCommunicationClientService(const ConvergenceAppCommunicationClientService&) = delete; + ConvergenceAppCommunicationClientService(const ConvergenceAppCommunicationClientService&) = + delete; ConvergenceAppCommunicationClientService(ConvergenceAppCommunicationClientService&&) = delete; - ConvergenceAppCommunicationClientService& operator=(const ConvergenceAppCommunicationClientService&) = delete; - ConvergenceAppCommunicationClientService& operator=(ConvergenceAppCommunicationClientService&&) = delete; + ConvergenceAppCommunicationClientService& operator=( + const ConvergenceAppCommunicationClientService&) = delete; + ConvergenceAppCommunicationClientService& operator=(ConvergenceAppCommunicationClientService&&) = + delete; + public: common::TizenResult Connect(const int cur_listener_id); common::TizenResult Disconnect(); + private: - static void ServiceConnectedCb(conv_service_h service_handle, - conv_error_e error, conv_payload_h result, void* user_data); + static void ServiceConnectedCb(conv_service_h service_handle, conv_error_e error, + conv_payload_h result, void* user_data); }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_APP_COMMUNICATION_SERVICE_H__ +#endif // CONVERGENCE_CONVERGENCE_APP_COMMUNICATION_SERVICE_H__ diff --git a/src/convergence/convergence_channel_info.cc b/src/convergence/convergence_channel_info.cc index a87c290..aac2557 100644 --- a/src/convergence/convergence_channel_info.cc +++ b/src/convergence/convergence_channel_info.cc @@ -17,30 +17,30 @@ // TODO check includes #include "convergence/convergence_channel_info.h" -#include #include +#include +#include "common/logger.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { namespace { // Channel keys -static const std::string kId = "id"; // This id is used in arguments (comes from JS layer) -static const std::string kChannelId = "channel_id"; // This id is used in the App Comm Service engine +static const std::string kId = "id"; // This id is used in arguments (comes from JS layer) +static const std::string kChannelId = + "channel_id"; // This id is used in the App Comm Service engine static const std::string kUri = "uri"; -} // namespace +} // namespace -ConvergenceChannel::ConvergenceChannel() - : channel_handle_(nullptr) { +ConvergenceChannel::ConvergenceChannel() : channel_handle_(nullptr) { ScopeLogger(); } ConvergenceChannel::ConvergenceChannel(const picojson::value &channel_json) - : channel_handle_(nullptr) { + : channel_handle_(nullptr) { ScopeLogger(); FromJson(channel_json); } @@ -67,7 +67,6 @@ std::string ConvergenceChannel::GetId() const { return id_; } - void ConvergenceChannel::FromJson(const picojson::value &channel_json) { ScopeLogger(); if (channel_json.is()) { @@ -108,7 +107,7 @@ picojson::value ConvergenceChannel::ToJson(conv_channel_h channel_handle) { return picojson::value(channel_object); } - { // Extracting channel ID + { // Extracting channel ID char *id = nullptr; const int error = conv_channel_get_string(channel_handle, kChannelId.c_str(), &id); if (CONV_ERROR_NONE != error) { @@ -119,7 +118,7 @@ picojson::value ConvergenceChannel::ToJson(conv_channel_h channel_handle) { } } - { // Extracting channel URI + { // Extracting channel URI char *uri = nullptr; const int error = conv_channel_get_string(channel_handle, kUri.c_str(), &uri); if (CONV_ERROR_NONE != error) { @@ -133,6 +132,5 @@ picojson::value ConvergenceChannel::ToJson(conv_channel_h channel_handle) { return picojson::value(channel_object); } - -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_channel_info.h b/src/convergence/convergence_channel_info.h index f1e87c7..c89ff70 100644 --- a/src/convergence/convergence_channel_info.h +++ b/src/convergence/convergence_channel_info.h @@ -29,10 +29,9 @@ namespace extension { namespace convergence { class ConvergenceChannel { - public: ConvergenceChannel(); - ConvergenceChannel(const picojson::value &channel_json); + ConvergenceChannel(const picojson::value& channel_json); virtual ~ConvergenceChannel(); ConvergenceChannel(const ConvergenceChannel&) = delete; ConvergenceChannel(ConvergenceChannel&&) = delete; @@ -43,7 +42,7 @@ class ConvergenceChannel { conv_channel_h GetHandle() const; std::string GetId() const; std::string GetUri() const; - void FromJson(const picojson::value &channel_json); + void FromJson(const picojson::value& channel_json); public: static picojson::value ToJson(conv_channel_h channel_handle); @@ -54,7 +53,7 @@ class ConvergenceChannel { std::string uri_; }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_CHANNEL_H__ +#endif // CONVERGENCE_CONVERGENCE_CHANNEL_H__ diff --git a/src/convergence/convergence_client_info.cc b/src/convergence/convergence_client_info.cc index b75c2e7..8d501aa 100644 --- a/src/convergence/convergence_client_info.cc +++ b/src/convergence/convergence_client_info.cc @@ -17,13 +17,13 @@ // TODO check includes #include "convergence/convergence_client_info.h" -#include #include +#include #include +#include "common/logger.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -31,19 +31,16 @@ namespace convergence { namespace { // Service keys static const std::string kIsHost = "client_is_host"; -static const std::string kConnectionTime = "client_connect_time"; //-- +static const std::string kConnectionTime = "client_connect_time"; //-- static const std::string kClientId = "client_id"; -} // namespace +} // namespace -ConvergenceClientInfo::ConvergenceClientInfo() - : isHost_(false) - , connectionTime_(0) { +ConvergenceClientInfo::ConvergenceClientInfo() : isHost_(false), connectionTime_(0) { ScopeLogger(); } ConvergenceClientInfo::ConvergenceClientInfo(conv_payload_h payload) - : isHost_(false) - , connectionTime_(0) { + : isHost_(false), connectionTime_(0) { ScopeLogger(); isHost_ = ExtractPayloadString(payload, "client_is_host") == "1"; @@ -81,6 +78,5 @@ picojson::value ConvergenceClientInfo::ToJson() const { return picojson::value(clientInfo); } - -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_client_info.h b/src/convergence/convergence_client_info.h index 665200c..b8f68e9 100644 --- a/src/convergence/convergence_client_info.h +++ b/src/convergence/convergence_client_info.h @@ -42,7 +42,7 @@ class ConvergenceClientInfo { picojson::value ToJson() const; private: - std::string ExtractPayloadString(conv_payload_h payload, const char *key); + std::string ExtractPayloadString(conv_payload_h payload, const char* key); private: bool isHost_; @@ -50,7 +50,7 @@ class ConvergenceClientInfo { long connectionTime_; }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_CLIENT_INFO_H__ +#endif // CONVERGENCE_CONVERGENCE_CLIENT_INFO_H__ diff --git a/src/convergence/convergence_device.cc b/src/convergence/convergence_device.cc index 34d3663..3abc98c 100644 --- a/src/convergence/convergence_device.cc +++ b/src/convergence/convergence_device.cc @@ -17,15 +17,15 @@ // TODO check includes #include "convergence/convergence_device.h" -#include #include +#include +#include "common/logger.h" +#include "convergence/convergence_app_communication_service.h" #include "convergence/convergence_instance.h" -#include "convergence/convergence_service.h" #include "convergence/convergence_remote_app_control_service.h" -#include "convergence/convergence_app_communication_service.h" +#include "convergence/convergence_service.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -33,20 +33,17 @@ namespace convergence { namespace { // Service keys static const std::string kId = "id"; -static const std::string kName = "name"; //-- +static const std::string kName = "name"; //-- static const std::string kDeviceType = "type"; static const std::string kDeviceServices = "services"; -} // namespace +} // namespace -ConvergenceDevice::ConvergenceDevice() - : device_handle_(nullptr) - , convergence_plugin_(NULL) { +ConvergenceDevice::ConvergenceDevice() : device_handle_(nullptr), convergence_plugin_(NULL) { ScopeLogger(); } ConvergenceDevice::ConvergenceDevice(conv_device_h device, ConvergenceInstance *convergence_plugin) - : device_handle_(device) - , convergence_plugin_(convergence_plugin) { + : device_handle_(device), convergence_plugin_(convergence_plugin) { ScopeLogger(); } @@ -83,18 +80,16 @@ ConvergenceService *ConvergenceDevice::SwapService(const int service_type) { ScopeLogger(); LoggerI("Swapping service of type [%d]", service_type); if (services_.count(service_type) <= 0) { - switch(service_type) { + switch (service_type) { case CONV_SERVICE_APP_TO_APP_COMMUNICATION: { services_[service_type] = - new ConvergenceAppCommunicationService(device_handle_, - convergence_plugin_); + new ConvergenceAppCommunicationService(device_handle_, convergence_plugin_); break; } case CONV_SERVICE_REMOTE_APP_CONTROL: { LoggerI("Adding Remote App Control service"); - services_[service_type] = - new ConvergenceRemoteAppControlService(device_handle_, - convergence_plugin_); + services_[service_type] = + new ConvergenceRemoteAppControlService(device_handle_, convergence_plugin_); break; } default: { @@ -110,13 +105,12 @@ ConvergenceService *ConvergenceDevice::RegisterLocalService(const int service_ty ScopeLogger(); LoggerI("Registering the local service of type [%d]", service_type); if (services_.count(service_type) <= 0) { - switch(service_type) { + switch (service_type) { case CONV_SERVICE_APP_TO_APP_COMMUNICATION: { services_[service_type] = - new ConvergenceAppCommunicationServerService(device_handle_, - convergence_plugin_); - LoggerI("Registered for local device [%s] the service [0x%0x] of type [%d]", - id_.c_str(), services_[service_type], CONV_SERVICE_APP_TO_APP_COMMUNICATION); + new ConvergenceAppCommunicationServerService(device_handle_, convergence_plugin_); + LoggerI("Registered for local device [%s] the service [0x%0x] of type [%d]", id_.c_str(), + services_[service_type], CONV_SERVICE_APP_TO_APP_COMMUNICATION); break; } default: { @@ -128,8 +122,7 @@ ConvergenceService *ConvergenceDevice::RegisterLocalService(const int service_ty return services_[service_type]; } -void ConvergenceDevice::ForEachServiceCb(conv_service_h service_handle, - void* user_data) { +void ConvergenceDevice::ForEachServiceCb(conv_service_h service_handle, void *user_data) { ScopeLogger(); if (!service_handle || !user_data) { LoggerE("ERROR! Invalid parameters of D2D API Callback"); @@ -161,8 +154,8 @@ void ConvergenceDevice::Refresh() { name_ = ExtractDevicePropery(CONV_DEVICE_NAME); type_ = ExtractDevicePropery(CONV_DEVICE_TYPE); - LoggerE("Refreshed device id [%s] name [%s] type [%s]", - id_.c_str(), name_.c_str(), type_.c_str()); + LoggerE("Refreshed device id [%s] name [%s] type [%s]", id_.c_str(), name_.c_str(), + type_.c_str()); // Extracting services const int error = conv_device_foreach_service(device_handle_, ForEachServiceCb, this); @@ -198,6 +191,5 @@ ConvergenceService *ConvergenceDevice::GetService(const int service_type) const return services_[service_type]; } - -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_device.h b/src/convergence/convergence_device.h index 505ae38..d187d02 100644 --- a/src/convergence/convergence_device.h +++ b/src/convergence/convergence_device.h @@ -32,33 +32,35 @@ class ConvergenceInstance; class ConvergenceService; class ConvergenceDevice { - public: ConvergenceDevice(); ConvergenceDevice(conv_device_h device_handle, ConvergenceInstance *convergence_plugin); virtual ~ConvergenceDevice(); - ConvergenceDevice(const ConvergenceDevice&) = delete; - ConvergenceDevice(ConvergenceDevice&&) = delete; - ConvergenceDevice& operator=(const ConvergenceDevice&) = delete; - ConvergenceDevice& operator=(ConvergenceDevice&&) = delete; - + ConvergenceDevice(const ConvergenceDevice &) = delete; + ConvergenceDevice(ConvergenceDevice &&) = delete; + ConvergenceDevice &operator=(const ConvergenceDevice &) = delete; + ConvergenceDevice &operator=(ConvergenceDevice &&) = delete; public: void Refresh(); ConvergenceService *GetService(const int service_type) const; - //picojson::object ToJson() const; + // picojson::object ToJson() const; picojson::value ToJson() const; - //std::string get_device() const {return device_handle_; } - int ServiceCount() {return services_.size();}; + // std::string get_device() const {return device_handle_; } + int ServiceCount() { + return services_.size(); + }; public: ConvergenceService *RegisterLocalService(const int service_type); - void SetId(const std::string &id) { id_ = id; } + void SetId(const std::string &id) { + id_ = id; + } private: ConvergenceService *SwapService(const int service_type); std::string ExtractDevicePropery(const char *property); - static void ForEachServiceCb(conv_service_h service_handle, void* user_data); + static void ForEachServiceCb(conv_service_h service_handle, void *user_data); private: conv_device_h device_handle_; @@ -68,10 +70,10 @@ class ConvergenceDevice { private: std::string id_; std::string name_; - std::string type_; // Device profile: mobile, wearable, TV + std::string type_; // Device profile: mobile, wearable, TV }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_DEVICE_H__ +#endif // CONVERGENCE_CONVERGENCE_DEVICE_H__ diff --git a/src/convergence/convergence_extension.cc b/src/convergence/convergence_extension.cc index 6952ef9..c84dbdc 100644 --- a/src/convergence/convergence_extension.cc +++ b/src/convergence/convergence_extension.cc @@ -30,16 +30,13 @@ ConvergenceExtension::ConvergenceExtension() { SetJavaScriptAPI(kSource_convergence_api); const char* entry_points[] = { - "tizen.RemoteAppControlService", - "tizen.AppCommunicationServerService", - "tizen.AppCommunicationClientService", - "tizen.ConvergenceChannelInfo", - nullptr - }; + "tizen.RemoteAppControlService", "tizen.AppCommunicationServerService", + "tizen.AppCommunicationClientService", "tizen.ConvergenceChannelInfo", nullptr}; SetExtraJSEntryPoints(entry_points); } -ConvergenceExtension::~ConvergenceExtension() {} +ConvergenceExtension::~ConvergenceExtension() { +} common::Instance* ConvergenceExtension::CreateInstance() { return new extension::convergence::ConvergenceInstance; diff --git a/src/convergence/convergence_extension.h b/src/convergence/convergence_extension.h index 1a043d2..e9edfc7 100644 --- a/src/convergence/convergence_extension.h +++ b/src/convergence/convergence_extension.h @@ -28,4 +28,4 @@ class ConvergenceExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // CONVERGENCE_CONVERGENCE_EXTENSION_H_ +#endif // CONVERGENCE_CONVERGENCE_EXTENSION_H_ diff --git a/src/convergence/convergence_instance.cc b/src/convergence/convergence_instance.cc index 8634375..2b8ca7b 100644 --- a/src/convergence/convergence_instance.cc +++ b/src/convergence/convergence_instance.cc @@ -20,17 +20,16 @@ #include #include -#include "convergence/convergence_manager.h" -#include "convergence/convergence_remote_app_control_service.h" -#include "convergence/convergence_app_communication_service.h" -#include "convergence/convergence_channel_info.h" -#include "convergence/convergence_payload.h" -#include "convergence/convergence_utils.h" #include "common/logger.h" #include "common/picojson.h" #include "common/task-queue.h" #include "common/tools.h" - +#include "convergence/convergence_app_communication_service.h" +#include "convergence/convergence_channel_info.h" +#include "convergence/convergence_manager.h" +#include "convergence/convergence_payload.h" +#include "convergence/convergence_remote_app_control_service.h" +#include "convergence/convergence_utils.h" namespace extension { namespace convergence { @@ -59,26 +58,26 @@ static const std::string kJSArgumentReply = "reply"; static const std::string kJSArgumentTimeout = "timeout"; static const std::string kJSArgumentService = "service"; static const std::string kJSArgumentAppControl = "appControl"; -} // namespace +} // namespace using namespace common; ConvergenceInstance::ConvergenceInstance() { using namespace std::placeholders; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&ConvergenceInstance::x, this, _1)) +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&ConvergenceInstance::x, this, _1)) REGISTER_SYNC("ConvergenceManager_stopDiscovery", ConvergenceManagerStopDiscovery); REGISTER_SYNC("AppCommunicationService_setListener", AppCommunicationServiceSetListener); REGISTER_SYNC("AppCommunicationService_unsetListener", AppCommunicationServiceUnsetListener); - REGISTER_SYNC("AppCommunicationServerService_constructLocal", AppCommunicationServerServiceConstructLocal); + REGISTER_SYNC("AppCommunicationServerService_constructLocal", + AppCommunicationServerServiceConstructLocal); #undef REGISTER_SYNC - #define REGISTER_ASYNC(c,x) \ - RegisterHandler(c, std::bind(&ConvergenceInstance::x, this, _1, _2)) +#define REGISTER_ASYNC(c, x) RegisterHandler(c, std::bind(&ConvergenceInstance::x, this, _1, _2)) REGISTER_ASYNC("ConvergenceManager_startDiscovery", ConvergenceManagerStartDiscovery); REGISTER_ASYNC("AppCommunicationClientService_connect", AppCommunicationClientServiceConnect); - REGISTER_ASYNC("AppCommunicationClientService_disconnect", AppCommunicationClientServiceDisconnect); + REGISTER_ASYNC("AppCommunicationClientService_disconnect", + AppCommunicationClientServiceDisconnect); REGISTER_ASYNC("AppCommunicationService_start", AppCommunicationServiceStart); REGISTER_ASYNC("AppCommunicationService_stop", AppCommunicationServiceStop); REGISTER_ASYNC("AppCommunicationService_getClientList", AppCommunicationServiceGetClientList); @@ -88,22 +87,23 @@ ConvergenceInstance::ConvergenceInstance() { REGISTER_ASYNC("RemoteAppControlService_start", RemoteAppControlServiceStart); REGISTER_ASYNC("RemoteAppControlService_stop", RemoteAppControlServiceStop); REGISTER_ASYNC("RemoteAppControlService_launch", RemoteAppControlServiceLaunch); - REGISTER_ASYNC("RemoteAppControlService_launchAppControl", RemoteAppControlServiceLaunchAppControl); - #undef REGISTER_ASYNC + REGISTER_ASYNC("RemoteAppControlService_launchAppControl", + RemoteAppControlServiceLaunchAppControl); +#undef REGISTER_ASYNC } ConvergenceInstance::~ConvergenceInstance() { ConvergenceManager::GetInstance(this).ResetInternalData(); } -void ConvergenceInstance::ReplyAsync(ConvergenceCallbacks callback_function_type, - int curListenerId, bool isSuccess, picojson::object& param) { +void ConvergenceInstance::ReplyAsync(ConvergenceCallbacks callback_function_type, int curListenerId, + bool isSuccess, picojson::object& param) { ScopeLogger(); param[kJSListenerStatus] = picojson::value(isSuccess ? kSuccess : kError); param[kJSCurrentListenerId] = picojson::value(static_cast(curListenerId)); - switch(callback_function_type) { + switch (callback_function_type) { case kConvergenceManagerDiscoveryCallback: { param[kJSTargetListenerId] = picojson::value("CONVERGENCE_DISCOVERY_LISTENER"); break; @@ -114,8 +114,7 @@ void ConvergenceInstance::ReplyAsync(ConvergenceCallbacks callback_function_type break; }*/ case kRemoteAppControlListenerCallback: { - param[kJSTargetListenerId] = - picojson::value("REMOTE_APP_CONTROL_SERVICE_LISTENER"); + param[kJSTargetListenerId] = picojson::value("REMOTE_APP_CONTROL_SERVICE_LISTENER"); break; } /*case kAppCommunicationSuccessCallback: { @@ -124,8 +123,7 @@ void ConvergenceInstance::ReplyAsync(ConvergenceCallbacks callback_function_type break; }*/ case kAppCommunicationListenerCallback: { - param[kJSTargetListenerId] = - picojson::value("APP_COMMUNICATION_SERVICE_LISTENER"); + param[kJSTargetListenerId] = picojson::value("APP_COMMUNICATION_SERVICE_LISTENER"); break; } /*case kAppCommunicationClientServiceConnectCallback: { @@ -140,16 +138,14 @@ void ConvergenceInstance::ReplyAsync(ConvergenceCallbacks callback_function_type } picojson::value result = picojson::value(param); - LoggerD("---> %s", result.serialize().c_str()); // TODO remove - + LoggerD("---> %s", result.serialize().c_str()); // TODO remove - TaskQueue::GetInstance().Async([this, result]() { - Instance::PostMessage(this, result.serialize().c_str()); - }); + TaskQueue::GetInstance().Async( + [this, result]() { Instance::PostMessage(this, result.serialize().c_str()); }); } -common::TizenResult ConvergenceInstance::ConvergenceManagerStartDiscovery(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::ConvergenceManagerStartDiscovery( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -162,7 +158,7 @@ common::TizenResult ConvergenceInstance::ConvergenceManagerStartDiscovery(const // Start the discovery procedure TizenResult result = ConvergenceManager::GetInstance(this).StartDiscovery( - static_cast(ConvergenceUtils::GetArg(args, kJSArgumentTimeout).get())); + static_cast(ConvergenceUtils::GetArg(args, kJSArgumentTimeout).get())); this->Post(token, result); }; @@ -171,7 +167,8 @@ common::TizenResult ConvergenceInstance::ConvergenceManagerStartDiscovery(const return common::TizenSuccess(); } -common::TizenResult ConvergenceInstance::ConvergenceManagerStopDiscovery(const picojson::object& args) { +common::TizenResult ConvergenceInstance::ConvergenceManagerStopDiscovery( + const picojson::object& args) { ScopeLogger(); /*CHECK_PRIVILEGE(kPrivilegeInternet) @@ -182,8 +179,8 @@ common::TizenResult ConvergenceInstance::ConvergenceManagerStopDiscovery(const p return ConvergenceManager::GetInstance(this).StopDiscovery(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceConnect(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceConnect( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -197,20 +194,21 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceConnect(const pi TizenResult result = TizenSuccess(); // Finding the service - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { // Running the service connect procedure - result = service->Connect(static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->Connect( + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } - //only in case of failure call callback - //other cases are handled by conv_service_connected_cb() + // only in case of failure call callback + // other cases are handled by conv_service_connected_cb() if (!result) { this->Post(token, result); } @@ -221,8 +219,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceConnect(const pi return TizenSuccess(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceDisconnect(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceDisconnect( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); @@ -233,13 +231,13 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceDisconnect(const TizenResult result = TizenSuccess(); - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { result = service->Disconnect(); } @@ -252,8 +250,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceDisconnect(const return TizenSuccess(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceStart(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceStart( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -268,21 +266,22 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceStart(const pico TizenResult result = TizenSuccess(); // Finding the service - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { // Running the service start procedure - result = service->Start(static_cast(ConvergenceUtils::GetArg(args, kJSArgumentReply).get()), - static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->Start( + static_cast(ConvergenceUtils::GetArg(args, kJSArgumentReply).get()), + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } - //only in case of failure call callback - //other cases are handled by conv_service_listener_cb() + // only in case of failure call callback + // other cases are handled by conv_service_listener_cb() if (!result) { this->Post(token, result); } @@ -293,8 +292,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceStart(const pico return TizenSuccess(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceStop(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceStop( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -309,21 +308,22 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceStop(const picoj TizenResult result = TizenSuccess(); // Finding the service - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { // Running the service stop procedure - result = service->Stop(static_cast(ConvergenceUtils::GetArg(args, kJSArgumentReply).get()), - static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->Stop( + static_cast(ConvergenceUtils::GetArg(args, kJSArgumentReply).get()), + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } - //only in case of failure call callback - //other cases are handled by conv_service_listener_cb() + // only in case of failure call callback + // other cases are handled by conv_service_listener_cb() if (!result) { this->Post(token, result); } @@ -334,8 +334,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceStop(const picoj return TizenSuccess(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunch(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunch( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -351,24 +351,26 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunch(const pic TizenResult result = TizenSuccess(); // Finding the service - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { std::string id = ConvergenceUtils::GetArg(args, kJSArgumentAppId).to_str(); if (id.empty()) { result = LogAndCreateTizenError(InvalidValuesError, "Invalid app id", ("Invalid app id")); } else { - result = service->Launch(id.c_str(), static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->Launch( + id.c_str(), + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } } - //only in case of failure call callback - //other cases are handled by conv_service_listener_cb() + // only in case of failure call callback + // other cases are handled by conv_service_listener_cb() if (!result) { this->Post(token, result); } @@ -379,8 +381,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunch(const pic return TizenSuccess(); } -common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunchAppControl(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunchAppControl( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -398,22 +400,23 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunchAppControl TizenResult result = TizenSuccess(); // Finding the service - ConvergenceRemoteAppControlService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_REMOTE_APP_CONTROL)); + ConvergenceRemoteAppControlService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_REMOTE_APP_CONTROL)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { - result = service->LaunchAppControl(ConvergenceUtils::GetArg(args, kJSArgumentAppControl).get(), - ConvergenceUtils::GetArg(args, kJSArgumentAppId).to_str().c_str(), - ConvergenceUtils::GetArg(args, kJSArgumentReply).get(), - static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->LaunchAppControl( + ConvergenceUtils::GetArg(args, kJSArgumentAppControl).get(), + ConvergenceUtils::GetArg(args, kJSArgumentAppId).to_str().c_str(), + ConvergenceUtils::GetArg(args, kJSArgumentReply).get(), + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } - //only in case of failure call callback - //other cases are handled by conv_service_listener_cb() + // only in case of failure call callback + // other cases are handled by conv_service_listener_cb() if (!result) { this->Post(token, result); } @@ -424,8 +427,8 @@ common::TizenResult ConvergenceInstance::RemoteAppControlServiceLaunchAppControl return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceStart(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceStart( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -441,30 +444,32 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceStart(const pico TizenResult result = TizenSuccess(); // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - result = LogAndCreateTizenError(AbortError, "Service is NULL", - ("Service is NULL")); + result = LogAndCreateTizenError(AbortError, "Service is NULL", ("Service is NULL")); } else { // Running the service start procedure auto channel_arg = ConvergenceUtils::GetArg(args, kJSArgumentChannel); std::vector::iterator channel_it = service->GetChannel(channel_arg); if (service->opened_channels.end() != channel_it) { - result = LogAndCreateTizenError(InvalidStateError, "Service is already started for the channel.", - ("Service is already started for the channel.")); + result = + LogAndCreateTizenError(InvalidStateError, "Service is already started for the channel.", + ("Service is already started for the channel.")); } else { - ConvergenceChannel* channel = new ConvergenceChannel(channel_arg); // memory would be managed in Start method - const int id = static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); + ConvergenceChannel* channel = + new ConvergenceChannel(channel_arg); // memory would be managed in Start method + const int id = + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); result = service->Start(channel, id); } } - //in case of failure call error callback, success callback will be triggered by listener + // in case of failure call error callback, success callback will be triggered by listener if (!result) { this->Post(token, result); } @@ -475,8 +480,8 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceStart(const pico return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceSend(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceSend( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -493,30 +498,31 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceSend(const picoj TizenResult result = TizenSuccess(); // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - result = LogAndCreateTizenError(AbortError, "service is NULL", - ("service is NULL")); + result = LogAndCreateTizenError(AbortError, "service is NULL", ("service is NULL")); } else { // Running the service send procedure auto channel_arg = ConvergenceUtils::GetArg(args, kJSArgumentChannel); std::vector::iterator channel_it = service->GetChannel(channel_arg); if (service->opened_channels.end() == channel_it) { - result = LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", - ("Service is not started for the channel.")); + result = + LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", + ("Service is not started for the channel.")); } else { ConvergencePayloadArray payload(ConvergenceUtils::GetArg(args, kJSArgumentPayload)); - const int id = static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); + const int id = + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); result = service->Send(*channel_it, payload, id); } } - //in case of failure call error callback, success callback will be triggered by listener + // in case of failure call error callback, success callback will be triggered by listener if (!result) { this->Post(token, result); } @@ -527,8 +533,8 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceSend(const picoj return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceStop(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceStop( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -544,23 +550,24 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceStop(const picoj TizenResult result = TizenSuccess(); // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - result = LogAndCreateTizenError(AbortError, "Service is NULL", - ("Service is NULL")); + result = LogAndCreateTizenError(AbortError, "Service is NULL", ("Service is NULL")); } else { // Running the service stop procedure auto channel_arg = ConvergenceUtils::GetArg(args, kJSArgumentChannel); std::vector::iterator channel_it = service->GetChannel(channel_arg); if (service->opened_channels.end() == channel_it) { - result = LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", - ("Service is not started for the channel.")); + result = + LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", + ("Service is not started for the channel.")); } else { - const int id = static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); + const int id = + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); result = service->Stop(*channel_it, id); if (result) { @@ -569,7 +576,7 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceStop(const picoj } } - //in case of failure call error callback, success callback will be triggered by listener + // in case of failure call error callback, success callback will be triggered by listener if (!result) { this->Post(token, result); } @@ -580,8 +587,8 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceStop(const picoj return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceGetClientList(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceGetClientList( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); @@ -597,29 +604,31 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceGetClientList(co TizenResult result = TizenSuccess(); // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { result = LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } else { // Running the service getClientList procedure auto channel_arg = ConvergenceUtils::GetArg(args, kJSArgumentChannel); std::vector::iterator channel_it = service->GetChannel(channel_arg); if (service->opened_channels.end() == channel_it) { - result = LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", - ("Service is not started for the channel.")); + result = + LogAndCreateTizenError(InvalidStateError, "Service is not started for the channel.", + ("Service is not started for the channel.")); } else { - const int id = static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); + const int id = + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get()); result = service->GetClientList(*channel_it, id); } } - //in case of failure call error callback, success callback will be triggered by listener + // in case of failure call error callback, success callback will be triggered by listener if (!result) { this->Post(token, result); } @@ -630,7 +639,8 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceGetClientList(co return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceSetListener(const picojson::object& args) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceSetListener( + const picojson::object& args) { ScopeLogger(); /*CHECK_PRIVILEGE(kPrivilegeInternet) @@ -640,22 +650,23 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceSetListener(cons LoggerI("ARGS: %s", picojson::value(args).serialize().c_str()); // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - return LogAndCreateTizenError(AbortError, "service is NULL", - ("service is NULL")); + return LogAndCreateTizenError(AbortError, "service is NULL", ("service is NULL")); } // Running the service stop procedure - service->SetListener(static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + service->SetListener( + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); return common::TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServiceUnsetListener(const picojson::object& args) { +common::TizenResult ConvergenceInstance::AppCommunicationServiceUnsetListener( + const picojson::object& args) { ScopeLogger(); /*CHECK_PRIVILEGE(kPrivilegeInternet) @@ -663,13 +674,12 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceUnsetListener(co CHECK_PRIVILEGE(kPrivilegeWifiDirect)*/ // Finding the service - ConvergenceAppCommunicationService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationService* service = static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - return LogAndCreateTizenError(AbortError, "service is NULL", - ("service is NULL")); + return LogAndCreateTizenError(AbortError, "service is NULL", ("service is NULL")); } // Running the service stop procedure @@ -678,24 +688,26 @@ common::TizenResult ConvergenceInstance::AppCommunicationServiceUnsetListener(co return common::TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationServerServiceConstructLocal(const picojson::object& args) { +common::TizenResult ConvergenceInstance::AppCommunicationServerServiceConstructLocal( + const picojson::object& args) { ScopeLogger(); // Finding the service - ConvergenceAppCommunicationClientService *service = - static_cast( - ConvergenceManager::GetInstance(this).RegisterLocalService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationClientService* service = + static_cast( + ConvergenceManager::GetInstance(this).RegisterLocalService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { return LogAndCreateTizenError(AbortError, "Can not find the service type = 1", - ("Can not find the service type = 1")); + ("Can not find the service type = 1")); } return common::TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationClientServiceConnect(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationClientServiceConnect( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); // [TK] SecurityError @@ -712,16 +724,17 @@ common::TizenResult ConvergenceInstance::AppCommunicationClientServiceConnect(co TizenResult result = TizenSuccess(); - ConvergenceAppCommunicationClientService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationClientService* service = + static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - result = LogAndCreateTizenError(AbortError, "Service is NULL", - ("service is NULL")); + result = LogAndCreateTizenError(AbortError, "Service is NULL", ("service is NULL")); } else { // Running the service connect procedure - result = service->Connect(static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); + result = service->Connect( + static_cast(ConvergenceUtils::GetArg(args, kJSCurrentListenerId).get())); } this->Post(token, result); @@ -732,26 +745,26 @@ common::TizenResult ConvergenceInstance::AppCommunicationClientServiceConnect(co return TizenSuccess(); } -common::TizenResult ConvergenceInstance::AppCommunicationClientServiceDisconnect(const picojson::object& args, - const common::AsyncToken& token) { +common::TizenResult ConvergenceInstance::AppCommunicationClientServiceDisconnect( + const picojson::object& args, const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeInternet); CHECK_PRIVILEGE(kPrivilegeBluetooth); - //LoggerI("ARGS: %s", picojson::value(args).serialize().c_str()); + // LoggerI("ARGS: %s", picojson::value(args).serialize().c_str()); auto disconnect = [this, args](const common::AsyncToken& token) -> void { ScopeLogger("disconnect"); TizenResult result = TizenSuccess(); - ConvergenceAppCommunicationClientService *service = - static_cast( - ConvergenceManager::GetInstance(this).GetService(ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), - CONV_SERVICE_APP_TO_APP_COMMUNICATION)); + ConvergenceAppCommunicationClientService* service = + static_cast( + ConvergenceManager::GetInstance(this).GetService( + ConvergenceUtils::GetArg(args, kJSArgumentDeviceId).to_str().c_str(), + CONV_SERVICE_APP_TO_APP_COMMUNICATION)); if (!service) { - result = LogAndCreateTizenError(AbortError, "Service is NULL", - ("Service is NULL")); + result = LogAndCreateTizenError(AbortError, "Service is NULL", ("Service is NULL")); } else { // Running the service disconnect procedure result = service->Disconnect(); @@ -765,8 +778,7 @@ common::TizenResult ConvergenceInstance::AppCommunicationClientServiceDisconnect return TizenSuccess(); } - #undef CHECK_EXIST -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension diff --git a/src/convergence/convergence_instance.h b/src/convergence/convergence_instance.h index 9b84922..94758c3 100644 --- a/src/convergence/convergence_instance.h +++ b/src/convergence/convergence_instance.h @@ -18,8 +18,8 @@ #define CONVERGENCE_CONVERGENCE_INSTANCE_H_ #include -#include "common/tizen_instance.h" #include "common/extension.h" +#include "common/tizen_instance.h" #include "common/tizen_result.h" namespace extension { @@ -30,44 +30,55 @@ enum ConvergenceCallbacks { kConvergenceManagerDiscoveryCallback, // Remote App Control - //kRemoteAppControlServiceConnectCallback, + // kRemoteAppControlServiceConnectCallback, kRemoteAppControlListenerCallback, // App Communication - //kAppCommunicationSuccessCallback, + // kAppCommunicationSuccessCallback, kAppCommunicationListenerCallback, - // App Communication Client - //kAppCommunicationClientServiceConnectCallback + // kAppCommunicationClientServiceConnectCallback }; class ConvergenceInstance : public common::TizenInstance { public: ConvergenceInstance(); virtual ~ConvergenceInstance(); + public: - void ReplyAsync(ConvergenceCallbacks cbfunc, - int curListenerId, bool isSuccess, picojson::object& param); + void ReplyAsync(ConvergenceCallbacks cbfunc, int curListenerId, bool isSuccess, + picojson::object& param); private: // Convergence Manager - common::TizenResult ConvergenceManagerStartDiscovery(const picojson::object& args, const common::AsyncToken& token); + common::TizenResult ConvergenceManagerStartDiscovery(const picojson::object& args, + const common::AsyncToken& token); common::TizenResult ConvergenceManagerStopDiscovery(const picojson::object& args); // Remote App Control Service - common::TizenResult RemoteAppControlServiceConnect(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult RemoteAppControlServiceDisconnect(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult RemoteAppControlServiceStart(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult RemoteAppControlServiceStop(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult RemoteAppControlServiceLaunch(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult RemoteAppControlServiceLaunchAppControl(const picojson::object& args, const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceConnect(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceDisconnect(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceStart(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceStop(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceLaunch(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult RemoteAppControlServiceLaunchAppControl(const picojson::object& args, + const common::AsyncToken& token); // App Communication Service - common::TizenResult AppCommunicationServiceStart(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult AppCommunicationServiceStop(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult AppCommunicationServiceGetClientList(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult AppCommunicationServiceSend(const picojson::object& args, const common::AsyncToken& token); + common::TizenResult AppCommunicationServiceStart(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult AppCommunicationServiceStop(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult AppCommunicationServiceGetClientList(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult AppCommunicationServiceSend(const picojson::object& args, + const common::AsyncToken& token); common::TizenResult AppCommunicationServiceSetListener(const picojson::object& args); common::TizenResult AppCommunicationServiceUnsetListener(const picojson::object& args); @@ -75,11 +86,13 @@ class ConvergenceInstance : public common::TizenInstance { common::TizenResult AppCommunicationServerServiceConstructLocal(const picojson::object& args); // App Communication Client Service - common::TizenResult AppCommunicationClientServiceConnect(const picojson::object& args, const common::AsyncToken& token); - common::TizenResult AppCommunicationClientServiceDisconnect(const picojson::object& args, const common::AsyncToken& token); + common::TizenResult AppCommunicationClientServiceConnect(const picojson::object& args, + const common::AsyncToken& token); + common::TizenResult AppCommunicationClientServiceDisconnect(const picojson::object& args, + const common::AsyncToken& token); }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_INSTANCE_H_ +#endif // CONVERGENCE_CONVERGENCE_INSTANCE_H_ diff --git a/src/convergence/convergence_manager.cc b/src/convergence/convergence_manager.cc index 3b14d6c..ea005c5 100644 --- a/src/convergence/convergence_manager.cc +++ b/src/convergence/convergence_manager.cc @@ -16,14 +16,14 @@ #include "convergence/convergence_manager.h" -#include #include +#include -#include "convergence/convergence_instance.h" +#include "common/logger.h" #include "convergence/convergence_device.h" +#include "convergence/convergence_instance.h" #include "convergence/convergence_service.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -31,7 +31,6 @@ namespace convergence { using common::TizenResult; using common::TizenSuccess; - namespace { // Device keys static const std::string kDevice = "device"; @@ -42,21 +41,18 @@ static const std::string kDiscoveryStatusDeviceFound = "device_found"; static const std::string kDiscoveryStatusFinished = "discovery_finished"; static const std::string kDiscoveryStatusError = "discovery_error"; static const std::string kDiscoveryError = "error"; -} // namespace - +} // namespace //////////////////////////////////////////////////////////////////////////////// -ConvergenceManager &ConvergenceManager::GetInstance( - ConvergenceInstance *owner) { +ConvergenceManager &ConvergenceManager::GetInstance(ConvergenceInstance *owner) { static ConvergenceManager instance; instance.convergence_plugin_ = owner; return instance; } ConvergenceManager::ConvergenceManager() - : convergence_plugin_(nullptr) - , convergence_manager_(nullptr) { + : convergence_plugin_(nullptr), convergence_manager_(nullptr) { ScopeLogger(); const int error = conv_create(&convergence_manager_); if (CONV_ERROR_NONE != error) { @@ -70,7 +66,7 @@ ConvergenceManager::~ConvergenceManager() { // Releasing all registered devices for (auto it = registered_devices_.begin(); it != registered_devices_.end(); ++it) { - delete it->second; + delete it->second; } registered_devices_.clear(); @@ -86,7 +82,7 @@ void ConvergenceManager::ResetInternalData() { ScopeLogger(); // Releasing all registered devices for (auto it = registered_devices_.begin(); it != registered_devices_.end(); ++it) { - delete it->second; + delete it->second; } registered_devices_.clear(); @@ -108,7 +104,7 @@ void ConvergenceManager::ResetInternalData() { } ConvergenceDevice *ConvergenceManager::SwapDevice(const char *device_id, - conv_device_h device_handle) { + conv_device_h device_handle) { ScopeLogger(); if (registered_devices_.count(device_id) <= 0) { ConvergenceDevice *d = new ConvergenceDevice(device_handle, convergence_plugin_); @@ -116,7 +112,7 @@ ConvergenceDevice *ConvergenceManager::SwapDevice(const char *device_id, registered_devices_[device_id] = d; LoggerI("...registering the device [%s, %x]", device_id, device_handle); // Assume that there are only two services - } else if(registered_devices_[device_id]->ServiceCount() < 2) { + } else if (registered_devices_[device_id]->ServiceCount() < 2) { registered_devices_.erase(device_id); ConvergenceDevice *d = new ConvergenceDevice(device_handle, convergence_plugin_); d->SetId(device_id); @@ -125,8 +121,8 @@ ConvergenceDevice *ConvergenceManager::SwapDevice(const char *device_id, return registered_devices_[device_id]; } -void ConvergenceManager::DiscoveryCb(conv_device_h device_handle, - conv_discovery_result_e result, void* user_data) { +void ConvergenceManager::DiscoveryCb(conv_device_h device_handle, conv_discovery_result_e result, + void *user_data) { ScopeLogger(); if (!user_data) { @@ -136,79 +132,73 @@ void ConvergenceManager::DiscoveryCb(conv_device_h device_handle, ConvergenceManager *owner = static_cast(user_data); - switch(result) { - case CONV_DISCOVERY_RESULT_SUCCESS: { - LoggerI("...found a device"); + switch (result) { + case CONV_DISCOVERY_RESULT_SUCCESS: { + LoggerI("...found a device"); + + char *id = nullptr; + int error = conv_device_get_property_string(device_handle, CONV_DEVICE_ID, &id); + if (CONV_ERROR_NONE != error) { + trace_conv_error(error, __LINE__, "conv_device_get_property_string ID"); + } + if (!id) { + LoggerE("BAD ERROR: Device ID is NULL"); + return; // TODO report error + } + + conv_device_h clone_device = nullptr; + error = conv_device_clone(device_handle, &clone_device); + if (CONV_ERROR_NONE != error) { + trace_conv_error(error, __LINE__, "conv_device_clone"); + break; + } + ConvergenceDevice *d = owner->SwapDevice(id, clone_device); + free(id); + + if (!d) { + // Handle bad error + LoggerE("BAD ERROR: Cannot swap the device"); + break; + } + + d->Refresh(); + + picojson::object param; + param[kDiscoveryStatus] = picojson::value(kDiscoveryStatusDeviceFound); + param[kDevice] = d->ToJson(); + owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, -1, true, param); - char *id = nullptr; - int error = conv_device_get_property_string(device_handle, CONV_DEVICE_ID, &id); - if (CONV_ERROR_NONE != error) { - trace_conv_error(error, __LINE__, "conv_device_get_property_string ID"); - } - if (!id) { - LoggerE("BAD ERROR: Device ID is NULL"); - return; // TODO report error + break; } + case CONV_DISCOVERY_RESULT_FINISHED: { + LoggerE("...discovery finished"); - conv_device_h clone_device = nullptr; - error = conv_device_clone(device_handle, &clone_device); - if (CONV_ERROR_NONE != error) { - trace_conv_error(error, __LINE__, "conv_device_clone"); + picojson::object param; + param[kDiscoveryStatus] = picojson::value(kDiscoveryStatusFinished); + owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, -1, true, param); break; } - ConvergenceDevice *d = owner->SwapDevice(id, clone_device); - free(id); - - if (!d) { - // Handle bad error - LoggerE("BAD ERROR: Cannot swap the device"); + case CONV_DISCOVERY_RESULT_ERROR: { + LoggerE("Discovery Error"); + picojson::object param; + param[kDiscoveryError] = + LogAndCreateTizenError(AbortError, "DiscoveryCb return CONV_DISCOVERY_RESULT_ERROR") + .ToJSON(); + owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, -1, false, + param); + break; + } + default: { + LoggerE("Unknown discovery result"); break; } - - d->Refresh(); - - picojson::object param; - param[kDiscoveryStatus] = picojson::value(kDiscoveryStatusDeviceFound); - param[kDevice] = d->ToJson(); - owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, - -1, - true, - param); - - break; - } - case CONV_DISCOVERY_RESULT_FINISHED: { - LoggerE("...discovery finished"); - - picojson::object param; - param[kDiscoveryStatus] = picojson::value(kDiscoveryStatusFinished); - owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, - -1, - true, - param); - break; - } - case CONV_DISCOVERY_RESULT_ERROR: { - LoggerE("Discovery Error"); - picojson::object param; - param[kDiscoveryError] = LogAndCreateTizenError(AbortError, "DiscoveryCb return CONV_DISCOVERY_RESULT_ERROR").ToJSON(); - owner->convergence_plugin_->ReplyAsync(kConvergenceManagerDiscoveryCallback, - -1, - false, - param); - break; - } - default: { - LoggerE("Unknown discovery result"); - break; - } } } TizenResult ConvergenceManager::StartDiscovery(long timeout) { ScopeLogger(); - const int error = conv_discovery_start(convergence_manager_, - (const int)timeout, DiscoveryCb, this); + const int error = + conv_discovery_start(convergence_manager_, (const int)timeout, DiscoveryCb, this); if (CONV_ERROR_NONE != error) { return LogAndCreateTizenError(AbortError, "conv_discovery_start [fail]"); } @@ -229,7 +219,7 @@ TizenResult ConvergenceManager::StopDiscovery() { // so this function would return always valid pointers //------------- ConvergenceService *ConvergenceManager::GetService(const char *device_id, - const int service_type) const { + const int service_type) const { ScopeLogger(); LoggerI("Getting the service object for id [%s], type [%d]", device_id, service_type); @@ -248,7 +238,7 @@ ConvergenceService *ConvergenceManager::GetService(const char *device_id, } ConvergenceService *ConvergenceManager::RegisterLocalService(const char *device_id, - const int service_type) { + const int service_type) { ScopeLogger(); LoggerI("Registering local service [%d] for device id [%s]", service_type, device_id); @@ -262,5 +252,5 @@ ConvergenceService *ConvergenceManager::RegisterLocalService(const char *device_ return d->RegisterLocalService(service_type); } -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_manager.h b/src/convergence/convergence_manager.h index 2d8c5d9..d9ffb29 100644 --- a/src/convergence/convergence_manager.h +++ b/src/convergence/convergence_manager.h @@ -27,50 +27,46 @@ namespace extension { namespace convergence { - class ConvergenceDevice; class ConvergenceService; // TODO rename to Discovery Manager // TODO extract service start, stop, read, send to Service Manager class class ConvergenceManager { - public: - static ConvergenceManager &GetInstance(class ConvergenceInstance *owner); + static ConvergenceManager &GetInstance(class ConvergenceInstance *owner); public: ConvergenceManager(); ~ConvergenceManager(); - ConvergenceManager(const ConvergenceManager&) = delete; - ConvergenceManager(ConvergenceManager&&) = delete; - ConvergenceManager& operator=(const ConvergenceManager&) = delete; - ConvergenceManager& operator=(ConvergenceManager&&) = delete; + ConvergenceManager(const ConvergenceManager &) = delete; + ConvergenceManager(ConvergenceManager &&) = delete; + ConvergenceManager &operator=(const ConvergenceManager &) = delete; + ConvergenceManager &operator=(ConvergenceManager &&) = delete; public: common::TizenResult StartDiscovery(long timeout); common::TizenResult StopDiscovery(); public: - ConvergenceService *GetService(const char *device_id, - const int service_type) const; - ConvergenceService *RegisterLocalService(const char *device_id, - const int service_type); + ConvergenceService *GetService(const char *device_id, const int service_type) const; + ConvergenceService *RegisterLocalService(const char *device_id, const int service_type); - void ResetInternalData(); + void ResetInternalData(); private: - static void DiscoveryCb(conv_device_h device_handle, - conv_discovery_result_e result, void* user_data); - ConvergenceDevice *SwapDevice(const char *device_id, - conv_device_h device_handle); + static void DiscoveryCb(conv_device_h device_handle, conv_discovery_result_e result, + void *user_data); + ConvergenceDevice *SwapDevice(const char *device_id, conv_device_h device_handle); private: class ConvergenceInstance *convergence_plugin_; conv_h convergence_manager_; - mutable std::unordered_map registered_devices_; // TODO rename to discovered_devices_ or simply devices_ + mutable std::unordered_map + registered_devices_; // TODO rename to discovered_devices_ or simply devices_ }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_MANAGER_H__ +#endif // CONVERGENCE_CONVERGENCE_MANAGER_H__ diff --git a/src/convergence/convergence_payload.cc b/src/convergence/convergence_payload.cc index b038ed8..22fd23b 100644 --- a/src/convergence/convergence_payload.cc +++ b/src/convergence/convergence_payload.cc @@ -17,12 +17,12 @@ // TODO check includes #include "convergence/convergence_payload.h" -#include #include +#include +#include "common/logger.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -31,15 +31,14 @@ namespace { // Payload data keys and some values static const std::string kKey = "key"; static const std::string kValue = "value"; -} // namespace +} // namespace -ConvergencePayloadArray::ConvergencePayloadArray() - : payload_handle_(nullptr) { +ConvergencePayloadArray::ConvergencePayloadArray() : payload_handle_(nullptr) { ScopeLogger(); } ConvergencePayloadArray::ConvergencePayloadArray(const picojson::value &payload_json) - : payload_handle_(nullptr) { + : payload_handle_(nullptr) { ScopeLogger(); FromJson(payload_json); } @@ -58,7 +57,6 @@ conv_payload_h ConvergencePayloadArray::GetHandle() const { return payload_handle_; } - void ConvergencePayloadArray::FromJson(const picojson::value &payload_json) { ScopeLogger(); if (payload_json.is()) { @@ -94,12 +92,12 @@ void ConvergencePayloadArray::FromJson(const picojson::value &payload_json) { error = conv_payload_set_string(payload_handle_, key.c_str(), value.c_str()); } else if (item.get(kValue).is()) { - const picojson::array& value = item.get(kValue).get(); + const picojson::array &value = item.get(kValue).get(); unsigned int length = value.size(); - unsigned char* bytes = new unsigned char[length]; + unsigned char *bytes = new unsigned char[length]; - for(std::size_t i = 0; i < length; ++i) { + for (std::size_t i = 0; i < length; ++i) { bytes[i] = static_cast(value.at(i).get()); } @@ -118,7 +116,7 @@ void ConvergencePayloadArray::FromJson(const picojson::value &payload_json) { picojson::value ConvergencePayloadArray::ToJson(conv_payload_h payload_handle) { ScopeLogger(); - picojson::array payloads; // Array of payloads to deliver to JS layer + picojson::array payloads; // Array of payloads to deliver to JS layer do { if (!payload_handle) { @@ -136,7 +134,8 @@ picojson::value ConvergencePayloadArray::ToJson(conv_payload_h payload_handle) { } std::string err; - picojson::parse(parsed_payload, payload_json_str, payload_json_str + strlen(payload_json_str), &err); + picojson::parse(parsed_payload, payload_json_str, payload_json_str + strlen(payload_json_str), + &err); free(payload_json_str); if (!err.empty()) { LoggerE("Error parsing payload json: %s", err.c_str()); @@ -160,7 +159,7 @@ picojson::value ConvergencePayloadArray::ToJson(conv_payload_h payload_handle) { payloads.push_back(picojson::value(payload_object)); } - } while(false); + } while (false); return picojson::value(payloads); } @@ -181,5 +180,5 @@ std::string ConvergencePayloadArray::ExtractPayloadString(conv_payload_h payload } return ""; } -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_payload.h b/src/convergence/convergence_payload.h index cb55d6b..f5f3035 100644 --- a/src/convergence/convergence_payload.h +++ b/src/convergence/convergence_payload.h @@ -30,7 +30,7 @@ namespace convergence { namespace { static const std::string kPayload = "payload"; -} // namespace +} // namespace /*enum ConvergencePayloadType { kUnknownPayload = -1, @@ -38,17 +38,16 @@ static const std::string kPayload = "payload"; kRawBytesPayload };*/ - // TODO rename to simply Payload class ConvergencePayloadArray { public: ConvergencePayloadArray(); ConvergencePayloadArray(const picojson::value &payload_json); virtual ~ConvergencePayloadArray(); - ConvergencePayloadArray(const ConvergencePayloadArray&) = delete; - ConvergencePayloadArray(ConvergencePayloadArray&&) = delete; - ConvergencePayloadArray& operator=(const ConvergencePayloadArray&) = delete; - ConvergencePayloadArray& operator=(ConvergencePayloadArray&&) = delete; + ConvergencePayloadArray(const ConvergencePayloadArray &) = delete; + ConvergencePayloadArray(ConvergencePayloadArray &&) = delete; + ConvergencePayloadArray &operator=(const ConvergencePayloadArray &) = delete; + ConvergencePayloadArray &operator=(ConvergencePayloadArray &&) = delete; public: conv_payload_h GetHandle() const; @@ -113,7 +112,7 @@ class ConvergencePayloadRawBytes : public ConvergencePayload { }; */ -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_PAYLOAD_H__ +#endif // CONVERGENCE_CONVERGENCE_PAYLOAD_H__ diff --git a/src/convergence/convergence_remote_app_control_service.cc b/src/convergence/convergence_remote_app_control_service.cc index 70f00c9..895d2df 100644 --- a/src/convergence/convergence_remote_app_control_service.cc +++ b/src/convergence/convergence_remote_app_control_service.cc @@ -17,14 +17,14 @@ // TODO check includes #include "convergence/convergence_remote_app_control_service.h" -#include #include +#include +#include "common/logger.h" +#include "common/scope_exit.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_payload.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" -#include "common/scope_exit.h" namespace extension { namespace convergence { @@ -38,20 +38,20 @@ static const char* kJSCurrentListenerId = "curListenerId"; static const std::string kLaunch = "launch"; static const std::string kLaunchAppControl = "launchAppControl"; -} // namespace +} // namespace using common::TizenResult; using common::TizenSuccess; ConvergenceRemoteAppControlService::ConvergenceRemoteAppControlService() - : ConvergenceService() - , connect_callback_param_(nullptr) { + : ConvergenceService(), connect_callback_param_(nullptr) { ScopeLogger(); } -ConvergenceRemoteAppControlService::ConvergenceRemoteAppControlService(conv_device_h device, ConvergenceInstance *convergence_plugin) - : ConvergenceService(device, CONV_SERVICE_REMOTE_APP_CONTROL, convergence_plugin) - , connect_callback_param_(nullptr) { +ConvergenceRemoteAppControlService::ConvergenceRemoteAppControlService( + conv_device_h device, ConvergenceInstance* convergence_plugin) + : ConvergenceService(device, CONV_SERVICE_REMOTE_APP_CONTROL, convergence_plugin), + connect_callback_param_(nullptr) { ScopeLogger(); } @@ -68,10 +68,12 @@ ConvergenceRemoteAppControlService::~ConvergenceRemoteAppControlService() { } void ConvergenceRemoteAppControlService::ServiceConnectedCb(conv_service_h service_handle, - conv_error_e error, conv_payload_h result, void* user_data) { + conv_error_e error, + conv_payload_h result, + void* user_data) { ScopeLogger(); - CallbackParam *callbackParam = static_cast(user_data); + CallbackParam* callbackParam = static_cast(user_data); if (!callbackParam) { LoggerE("ERROR! NULL user data in Service Connect Callback"); return; @@ -84,16 +86,12 @@ void ConvergenceRemoteAppControlService::ServiceConnectedCb(conv_service_h servi if (CONV_ERROR_NONE == error) { param[kServiceConnectionStatus] = picojson::value(kServiceConnectionStatusConnected); callbackParam->plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - callbackParam->callback_id_, - true, - param); + callbackParam->callback_id_, true, param); } else { // Error occurred during connection param[kServiceConnectionStatus] = picojson::value(kServiceConnectionStatusNotConnected); callbackParam->plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - callbackParam->callback_id_, - false, - param); + callbackParam->callback_id_, false, param); } } @@ -105,7 +103,7 @@ TizenResult ConvergenceRemoteAppControlService::Connect(const int cur_listener_i return LogAndCreateTizenError(AbortError, "Service with specified type does not exist"); } - CallbackParam *param = new CallbackParam(convergence_plugin_, cur_listener_id); + CallbackParam* param = new CallbackParam(convergence_plugin_, cur_listener_id); const int error = conv_service_connect(service, ServiceConnectedCb, param); if (CONV_ERROR_NONE != error) { delete param; @@ -143,8 +141,7 @@ TizenResult ConvergenceRemoteAppControlService::Disconnect() { LoggerE("Error gathering state [%d] : %s", error, get_error_message(error)); return LogAndCreateTizenError(AbortError, "Error gathering state"); } else { - LoggerD("state: %d" , state); - + LoggerD("state: %d", state); } if (CONV_SERVICE_CONNECTION_STATE_NOT_CONNECTED == state) { return TizenSuccess(); @@ -163,22 +160,20 @@ TizenResult ConvergenceRemoteAppControlService::Start(const bool reply, const in } bool is_started = false; - //regarding to native team returned value should not be checked - //as CONV_ERROR_NONE means service is started, otherwise not started - //check only passed bool variable + // regarding to native team returned value should not be checked + // as CONV_ERROR_NONE means service is started, otherwise not started + // check only passed bool variable conv_service_is_started(service, nullptr, &is_started); if (is_started) { - //just call success callback + // just call success callback picojson::object param; param[kServiceResultType] = picojson::value("onStart"); param[kServiceListenerStatus] = picojson::value(kServiceListenerStatusOk); param[kJSCurrentListenerId] = picojson::value(static_cast(cur_listener_id)); - convergence_plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - cur_listener_id, - true, - param); + convergence_plugin_->ReplyAsync(kRemoteAppControlListenerCallback, cur_listener_id, true, + param); } else { if (reply) { UpdateListener(cur_listener_id); @@ -218,30 +213,34 @@ TizenResult ConvergenceRemoteAppControlService::Stop(const bool reply, const int } void ConvergenceRemoteAppControlService::ServiceListenerCb(conv_service_h service_handle, - conv_channel_h channel_handle, - conv_error_e error, conv_payload_h result, void* user_data) { + conv_channel_h channel_handle, + conv_error_e error, + conv_payload_h result, void* user_data) { ScopeLogger(); - CallbackParam *callbackParam = static_cast(user_data); + CallbackParam* callbackParam = static_cast(user_data); if (!callbackParam) { LoggerE("ERROR! NULL user data in Service Listener Callback"); return; } picojson::object param; - const std::string result_type = ConvergencePayloadArray::ExtractPayloadString(result, kServiceResultType.c_str()); + const std::string result_type = + ConvergencePayloadArray::ExtractPayloadString(result, kServiceResultType.c_str()); param[kServiceResultType] = picojson::value(result_type); if (CONV_ERROR_NONE == error) { - //onPublish are triggered by launch() and launchAppControl() methods + // onPublish are triggered by launch() and launchAppControl() methods if (kServiceResultTypeOnPublish == result_type) { param[kRemoteFunc] = picojson::value(callbackParam->remote_method_); - //there is no information which method caused callback execution - //so it is needed to provide such information via callbackParam + // there is no information which method caused callback execution + // so it is needed to provide such information via callbackParam if (kLaunchAppControl == callbackParam->remote_method_) { - const std::string app_control_result = ConvergencePayloadArray::ExtractPayloadString(result, kServiceReplyControlResult.c_str()); + const std::string app_control_result = ConvergencePayloadArray::ExtractPayloadString( + result, kServiceReplyControlResult.c_str()); if ("0" == app_control_result) { - const std::string app_control_reply = ConvergencePayloadArray::ExtractPayloadString(result, kServiceReplyResult.c_str()); + const std::string app_control_reply = + ConvergencePayloadArray::ExtractPayloadString(result, kServiceReplyResult.c_str()); param[kCbResult] = picojson::value("onsuccess"); param[kReply] = picojson::value(app_control_reply); @@ -254,15 +253,11 @@ void ConvergenceRemoteAppControlService::ServiceListenerCb(conv_service_h servic param[kServiceListenerStatus] = picojson::value(kServiceListenerStatusOk); callbackParam->plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - callbackParam->callback_id_, - true, - param); + callbackParam->callback_id_, true, param); } else { param[kServiceListenerStatus] = picojson::value(kServiceListenerStatusOk); callbackParam->plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - callbackParam->callback_id_, - true, - param); + callbackParam->callback_id_, true, param); } } else { // Error occurred during connection @@ -275,13 +270,12 @@ void ConvergenceRemoteAppControlService::ServiceListenerCb(conv_service_h servic param[kServiceListenerStatus] = picojson::value(kServiceListenerStatusError); param[kServiceListenerError] = picojson::value(static_cast(error)); callbackParam->plugin_->ReplyAsync(kRemoteAppControlListenerCallback, - callbackParam->callback_id_, - false, - param); + callbackParam->callback_id_, false, param); } } -void ConvergenceRemoteAppControlService::UpdateListener(const int cur_listener_id, std::string remote_method) { +void ConvergenceRemoteAppControlService::UpdateListener(const int cur_listener_id, + std::string remote_method) { ScopeLogger(); conv_service_h service_handle = FindServiceHandle(); @@ -290,7 +284,7 @@ void ConvergenceRemoteAppControlService::UpdateListener(const int cur_listener_i return; } - CallbackParam *param = new CallbackParam(convergence_plugin_, cur_listener_id); + CallbackParam* param = new CallbackParam(convergence_plugin_, cur_listener_id); param->remote_method_ = remote_method; const int error = conv_service_set_listener_cb(service_handle, ServiceListenerCb, param); @@ -305,7 +299,8 @@ void ConvergenceRemoteAppControlService::UpdateListener(const int cur_listener_i } } -TizenResult ConvergenceRemoteAppControlService::Launch(const char *appId, const int cur_listener_id) { +TizenResult ConvergenceRemoteAppControlService::Launch(const char* appId, + const int cur_listener_id) { ScopeLogger(); conv_payload_h payload = nullptr; @@ -330,7 +325,6 @@ TizenResult ConvergenceRemoteAppControlService::Launch(const char *appId, const return LogAndCreateTizenError(AbortError, "Failed to create payload handle"); } - ret = app_control_create(&app_control); if (APP_CONTROL_ERROR_NONE != ret) { return LogAndCreateTizenError(AbortError, "Failed to create app control handle"); @@ -365,10 +359,9 @@ TizenResult ConvergenceRemoteAppControlService::Launch(const char *appId, const return TizenSuccess(); } -TizenResult ConvergenceRemoteAppControlService::LaunchAppControl(const picojson::object& jsonAppControl, - const char *appId, - bool reply, - const int cur_listener_id) { +TizenResult ConvergenceRemoteAppControlService::LaunchAppControl( + const picojson::object& jsonAppControl, const char* appId, bool reply, + const int cur_listener_id) { ScopeLogger(); conv_payload_h payload = nullptr; @@ -417,12 +410,9 @@ TizenResult ConvergenceRemoteAppControlService::LaunchAppControl(const picojson: const auto it_data = jsonAppControl.find("data"); const auto it_app_control_end = jsonAppControl.end(); - if (it_operation == it_app_control_end || - it_uri == it_app_control_end || - it_mime == it_app_control_end || - it_category == it_app_control_end || - it_data == it_app_control_end || - !it_operation->second.is() || + if (it_operation == it_app_control_end || it_uri == it_app_control_end || + it_mime == it_app_control_end || it_category == it_app_control_end || + it_data == it_app_control_end || !it_operation->second.is() || !it_data->second.is()) { return LogAndCreateTizenError(InvalidValuesError, "Invalid parameter was passed."); } @@ -462,7 +452,8 @@ TizenResult ConvergenceRemoteAppControlService::LaunchAppControl(const picojson: for (auto iter = data.begin(); iter != data.end(); ++iter) { if (iter->is()) { - TizenResult result = ApplicationControlDataToServiceExtraData(iter->get(), app_control); + TizenResult result = + ApplicationControlDataToServiceExtraData(iter->get(), app_control); if (!result) { return result; } @@ -498,18 +489,15 @@ TizenResult ConvergenceRemoteAppControlService::LaunchAppControl(const picojson: } TizenResult ConvergenceRemoteAppControlService::ApplicationControlDataToServiceExtraData( - const picojson::object& app_control_data, - app_control_h app_control) { + const picojson::object& app_control_data, app_control_h app_control) { ScopeLogger(); const auto it_key = app_control_data.find("key"); const auto it_value = app_control_data.find("value"); const auto it_app_control_data_end = app_control_data.end(); - if (it_key == it_app_control_data_end || - it_value == it_app_control_data_end || - !it_key->second.is() || - !it_value->second.is()) { + if (it_key == it_app_control_data_end || it_value == it_app_control_data_end || + !it_key->second.is() || !it_value->second.is()) { return LogAndCreateTizenError(InvalidValuesError, "Invalid parameter was passed."); } @@ -535,5 +523,5 @@ TizenResult ConvergenceRemoteAppControlService::ApplicationControlDataToServiceE return TizenSuccess(); } -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_remote_app_control_service.h b/src/convergence/convergence_remote_app_control_service.h index 240667a..0fb5f3b 100644 --- a/src/convergence/convergence_remote_app_control_service.h +++ b/src/convergence/convergence_remote_app_control_service.h @@ -23,50 +23,47 @@ #include #include +#include "common/tizen_result.h" #include "convergence/convergence_service.h" #include "convergence/convergence_utils.h" -#include "common/tizen_result.h" namespace extension { namespace convergence { class ConvergenceRemoteAppControlService : public ConvergenceService { - public: ConvergenceRemoteAppControlService(); - ConvergenceRemoteAppControlService(conv_device_h device, ConvergenceInstance *convergence_plugin); + ConvergenceRemoteAppControlService(conv_device_h device, ConvergenceInstance* convergence_plugin); virtual ~ConvergenceRemoteAppControlService(); ConvergenceRemoteAppControlService(const ConvergenceRemoteAppControlService&) = delete; ConvergenceRemoteAppControlService(ConvergenceRemoteAppControlService&&) = delete; ConvergenceRemoteAppControlService& operator=(const ConvergenceRemoteAppControlService&) = delete; ConvergenceRemoteAppControlService& operator=(ConvergenceRemoteAppControlService&&) = delete; + public: common::TizenResult Connect(const int cur_listener_id); common::TizenResult Disconnect(); common::TizenResult Start(const bool reply, const int cur_listener_id); common::TizenResult Stop(const bool reply, const int cur_listener_id); - common::TizenResult Launch(const char *appId, const int cur_listener_id); - common::TizenResult LaunchAppControl(const picojson::object& jsonAppControl, - const char *appId, - bool reply, - const int cur_listener_id); + common::TizenResult Launch(const char* appId, const int cur_listener_id); + common::TizenResult LaunchAppControl(const picojson::object& jsonAppControl, const char* appId, + bool reply, const int cur_listener_id); + private: common::TizenResult ApplicationControlDataToServiceExtraData( - const picojson::object& app_control_data, - app_control_h app_control); + const picojson::object& app_control_data, app_control_h app_control); void UpdateListener(const int cur_listener_id, std::string remote_method = ""); - static void ServiceConnectedCb(conv_service_h service_handle, - conv_error_e error, conv_payload_h result, void* user_data); - static void ServiceListenerCb(conv_service_h service_handle, - conv_channel_h channel_handle, - conv_error_e error, conv_payload_h result, void* user_data); + static void ServiceConnectedCb(conv_service_h service_handle, conv_error_e error, + conv_payload_h result, void* user_data); + static void ServiceListenerCb(conv_service_h service_handle, conv_channel_h channel_handle, + conv_error_e error, conv_payload_h result, void* user_data); private: - std::vector callback_param_gc_; + std::vector callback_param_gc_; CallbackParam* connect_callback_param_; }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_REMOTE_APP_CONTROL_SERVICE_H__ +#endif // CONVERGENCE_CONVERGENCE_REMOTE_APP_CONTROL_SERVICE_H__ diff --git a/src/convergence/convergence_service.cc b/src/convergence/convergence_service.cc index 1f2f90f..e8e5030 100644 --- a/src/convergence/convergence_service.cc +++ b/src/convergence/convergence_service.cc @@ -17,12 +17,12 @@ // TODO check includes #include "convergence/convergence_service.h" -#include #include +#include +#include "common/logger.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { @@ -34,23 +34,24 @@ static const std::string kServiceConnectionState = "connectionState"; static const std::string kId = "id"; static const std::string kUri = "uri"; static const std::string kVersion = "version"; -} // namespace +} // namespace ConvergenceService::ConvergenceService() - : convergence_plugin_(nullptr) - , device_(nullptr) - , type_(CONV_SERVICE_NONE) - , service_handle_(nullptr) - , connection_state_(CONV_SERVICE_CONNECTION_STATE_NONE) { + : convergence_plugin_(nullptr), + device_(nullptr), + type_(CONV_SERVICE_NONE), + service_handle_(nullptr), + connection_state_(CONV_SERVICE_CONNECTION_STATE_NONE) { ScopeLogger(); } -ConvergenceService::ConvergenceService(conv_device_h device, conv_service_e type, ConvergenceInstance *convergence_plugin) - : convergence_plugin_(convergence_plugin) - , device_(device) - , type_(type) - , service_handle_(nullptr) - , connection_state_(CONV_SERVICE_CONNECTION_STATE_NONE) { +ConvergenceService::ConvergenceService(conv_device_h device, conv_service_e type, + ConvergenceInstance *convergence_plugin) + : convergence_plugin_(convergence_plugin), + device_(device), + type_(type), + service_handle_(nullptr), + connection_state_(CONV_SERVICE_CONNECTION_STATE_NONE) { ScopeLogger(); } @@ -65,8 +66,7 @@ ConvergenceService::~ConvergenceService() { LoggerD("listener unset"); } - std::for_each(opened_channels.begin(), opened_channels.end(), - [this](ConvergenceChannel* c){ + std::for_each(opened_channels.begin(), opened_channels.end(), [this](ConvergenceChannel *c) { int error = conv_service_stop(service_handle_, c->GetHandle(), nullptr); if (CONV_ERROR_NONE != error) { LoggerW("2 service was not stopped - error %d [%s]", error, get_error_message(error)); @@ -85,13 +85,12 @@ struct ServiceSearchQuery { conv_service_e type; }; -void ConvergenceService::ForEachServiceCb(conv_service_h service_handle, void* user_data) { +void ConvergenceService::ForEachServiceCb(conv_service_h service_handle, void *user_data) { ScopeLogger(); ServiceSearchQuery *query = static_cast(user_data); - if (!query) - return; + if (!query) return; if (query->handle) - return; // Already found a required service handle (no need to analyze something else) + return; // Already found a required service handle (no need to analyze something else) conv_service_e type = CONV_SERVICE_NONE; int error = conv_service_get_type(service_handle, &type); @@ -113,7 +112,6 @@ void ConvergenceService::ForEachServiceCb(conv_service_h service_handle, void* u conv_service_h ConvergenceService::FindServiceHandle() const { ScopeLogger(); if (!service_handle_) { - if (!device_) { LoggerE("ERROR: Device handle is NULL, can not get device services"); return nullptr; @@ -131,7 +129,7 @@ conv_service_h ConvergenceService::FindServiceHandle() const { } std::string ConvergenceService::ExtractServicePropery(conv_service_h service_handle, - const char *property) { + const char *property) { ScopeLogger(); char *value = nullptr; const int error = conv_service_get_property_string(service_handle, property, &value); @@ -168,11 +166,11 @@ void ConvergenceService::Refresh() { id_ = ExtractServicePropery(service_handle, CONV_SERVICE_ID); version_ = ExtractServicePropery(service_handle, CONV_SERVICE_VERSION); - LoggerE("Refreshed service id [%s] version [%s] connection state [%d]", - id_.c_str(), version_.c_str(), connection_state_); + LoggerE("Refreshed service id [%s] version [%s] connection state [%d]", id_.c_str(), + version_.c_str(), connection_state_); - //conv_service_destroy(service_handle); - //LoggerI("DESTROYING SERVICE HANDLE [0x0%x] in ConvergenceService Refresh", service_handle_); + // conv_service_destroy(service_handle); + // LoggerI("DESTROYING SERVICE HANDLE [0x0%x] in ConvergenceService Refresh", service_handle_); } picojson::value ConvergenceService::ToJson() const { @@ -190,13 +188,14 @@ picojson::value ConvergenceService::ToJson() const { return picojson::value(service_json); } -std::vector::iterator ConvergenceService::GetChannel(const picojson::value &channel_json) { +std::vector::iterator ConvergenceService::GetChannel( + const picojson::value &channel_json) { ScopeLogger(); const auto id = channel_json.get(kId).get(); const auto uri = channel_json.get(kUri).get(); for (auto it = opened_channels.begin(); it != opened_channels.end(); ++it) { - if((*it)->GetUri() == uri && (*it)->GetId() == id) { + if ((*it)->GetUri() == uri && (*it)->GetId() == id) { LoggerD("Found channel uri: [%s] id: [%s]", uri.c_str(), id.c_str()); return it; } @@ -205,10 +204,10 @@ std::vector::iterator ConvergenceService::GetChannel(const return opened_channels.end(); } -void ConvergenceService::RemoveChannel(std::vector::iterator it) { +void ConvergenceService::RemoveChannel(std::vector::iterator it) { ScopeLogger(); opened_channels.erase(it); } -} // namespace convergence +} // namespace convergence } // namespace extension diff --git a/src/convergence/convergence_service.h b/src/convergence/convergence_service.h index 9f4b4e4..35b741e 100644 --- a/src/convergence/convergence_service.h +++ b/src/convergence/convergence_service.h @@ -33,49 +33,49 @@ namespace convergence { class ConvergenceInstance; class ConvergenceService { - public: ConvergenceService(); - ConvergenceService(conv_device_h device, conv_service_e type, ConvergenceInstance *convergence_plugin); + ConvergenceService(conv_device_h device, conv_service_e type, + ConvergenceInstance *convergence_plugin); virtual ~ConvergenceService(); - ConvergenceService(const ConvergenceService&) = delete; - ConvergenceService(ConvergenceService&&) = delete; - ConvergenceService& operator=(const ConvergenceService&) = delete; - ConvergenceService& operator=(ConvergenceService&&) = delete; + ConvergenceService(const ConvergenceService &) = delete; + ConvergenceService(ConvergenceService &&) = delete; + ConvergenceService &operator=(const ConvergenceService &) = delete; + ConvergenceService &operator=(ConvergenceService &&) = delete; public: void Refresh(); - std::vector::iterator GetChannel(const picojson::value &channel_json); - void RemoveChannel(std::vector::iterator); + std::vector::iterator GetChannel(const picojson::value &channel_json); + void RemoveChannel(std::vector::iterator); public: - //conv_service_e get_type() const { return type_; } - //conv_device_h get_device() const {return device_; } + // conv_service_e get_type() const { return type_; } + // conv_device_h get_device() const {return device_; } picojson::value ToJson() const; - std::vector opened_channels; + std::vector opened_channels; protected: conv_service_h FindServiceHandle() const; - static void ForEachServiceCb(conv_service_h service_handle, void* user_data); - std::string ExtractServicePropery(conv_service_h service_handle, - const char *property); + static void ForEachServiceCb(conv_service_h service_handle, void *user_data); + std::string ExtractServicePropery(conv_service_h service_handle, const char *property); protected: ConvergenceInstance *convergence_plugin_; - //private: - protected: // TODO switch back to private: - conv_device_h device_; // TODO rename to device_handle_ + // private: + protected: // TODO switch back to private: + conv_device_h device_; // TODO rename to device_handle_ conv_service_e type_; mutable conv_service_h service_handle_; - friend class ConvergenceAppCommunicationServerService; // It is needed to register the local service + friend class ConvergenceAppCommunicationServerService; // It is needed to register the local + // service private: conv_service_connection_state_e connection_state_; std::string id_; std::string version_; }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_SERVICE_H__ +#endif // CONVERGENCE_CONVERGENCE_SERVICE_H__ diff --git a/src/convergence/convergence_utils.cc b/src/convergence/convergence_utils.cc index f14cac2..3af817a 100644 --- a/src/convergence/convergence_utils.cc +++ b/src/convergence/convergence_utils.cc @@ -17,43 +17,43 @@ // TODO check includes #include "convergence/convergence_service.h" -#include #include +#include +#include "common/logger.h" #include "convergence/convergence_instance.h" #include "convergence/convergence_utils.h" -#include "common/logger.h" namespace extension { namespace convergence { -void trace_conv_error(const int error, int line_number, const char *extra_text) { +void trace_conv_error(const int error, int line_number, const char* extra_text) { std::string error_text; switch (error) { - case CONV_ERROR_NONE: - error_text = "CONV_ERROR_NONE"; - break; - case CONV_ERROR_INVALID_PARAMETER: - error_text = "CONV_ERROR_INVALID_PARAMETER"; - break; - case CONV_ERROR_INVALID_OPERATION: - error_text = "CONV_ERROR_INVALID_OPERATION"; - break; - case CONV_ERROR_OUT_OF_MEMORY: - error_text = "CONV_ERROR_OUT_OF_MEMORY"; - break; - case CONV_ERROR_PERMISSION_DENIED: - error_text = "CONV_ERROR_PERMISSION_DENIED"; - break; - case CONV_ERROR_NOT_SUPPORTED: - error_text = "CONV_ERROR_NOT_SUPPORTED"; - break; - case CONV_ERROR_NO_DATA: - error_text = "CONV_ERROR_NO_DATA"; - break; - default: - error_text = "UNSUPPORTED D2D ERROR CODE"; - break; + case CONV_ERROR_NONE: + error_text = "CONV_ERROR_NONE"; + break; + case CONV_ERROR_INVALID_PARAMETER: + error_text = "CONV_ERROR_INVALID_PARAMETER"; + break; + case CONV_ERROR_INVALID_OPERATION: + error_text = "CONV_ERROR_INVALID_OPERATION"; + break; + case CONV_ERROR_OUT_OF_MEMORY: + error_text = "CONV_ERROR_OUT_OF_MEMORY"; + break; + case CONV_ERROR_PERMISSION_DENIED: + error_text = "CONV_ERROR_PERMISSION_DENIED"; + break; + case CONV_ERROR_NOT_SUPPORTED: + error_text = "CONV_ERROR_NOT_SUPPORTED"; + break; + case CONV_ERROR_NO_DATA: + error_text = "CONV_ERROR_NO_DATA"; + break; + default: + error_text = "UNSUPPORTED D2D ERROR CODE"; + break; } if (extra_text) { @@ -63,7 +63,8 @@ void trace_conv_error(const int error, int line_number, const char *extra_text) } } -const picojson::value& ConvergenceUtils::GetArg(const picojson::object& args, const std::string& name) { +const picojson::value& ConvergenceUtils::GetArg(const picojson::object& args, + const std::string& name) { static const picojson::value kNull; auto it = args.find(name); @@ -79,9 +80,9 @@ common::TizenResult ConvergenceUtils::ConvertConvergenceError(int error) { case CONV_ERROR_NONE: return common::TizenSuccess(); case CONV_ERROR_INVALID_OPERATION: - case CONV_ERROR_PERMISSION_DENIED: // Never return - case CONV_ERROR_NOT_SUPPORTED: // Never return - case CONV_ERROR_INVALID_PARAMETER: // Never return + case CONV_ERROR_PERMISSION_DENIED: // Never return + case CONV_ERROR_NOT_SUPPORTED: // Never return + case CONV_ERROR_INVALID_PARAMETER: // Never return return common::InvalidStateError(error); case CONV_ERROR_OUT_OF_MEMORY: case CONV_ERROR_NO_DATA: @@ -97,8 +98,7 @@ common::TizenResult ConvergenceUtils::ConvertConvergenceError(int error) { } return common::TizenSuccess(); - } -} // namespace convergence +} // namespace convergence } // namespace extension \ No newline at end of file diff --git a/src/convergence/convergence_utils.h b/src/convergence/convergence_utils.h index 2d17d8a..6a7441f 100644 --- a/src/convergence/convergence_utils.h +++ b/src/convergence/convergence_utils.h @@ -29,8 +29,8 @@ namespace extension { namespace convergence { -#define CHECK_EXIST(args, name) \ - if (args.end() == args.find(name)) { \ +#define CHECK_EXIST(args, name) \ + if (args.end() == args.find(name)) { \ return common::TypeMismatchError(std::string(name) + " is required argument"); \ } @@ -61,29 +61,25 @@ static const std::string kServiceListenerStatus = "listener_status"; static const std::string kServiceListenerStatusOk = "listener_ok"; static const std::string kServiceListenerStatusError = "listener_error"; static const std::string kServiceListenerError = "error"; -} // namespace +} // namespace -enum ServiceRequestType { - LOCAL_SERVICE_START, - REMOTE_SERVICE_START, - UNKNOWN_REQUEST_TYPE -}; +enum ServiceRequestType { LOCAL_SERVICE_START, REMOTE_SERVICE_START, UNKNOWN_REQUEST_TYPE }; struct CallbackParam { - CallbackParam(ConvergenceInstance *plg, int cbId, ServiceRequestType type = UNKNOWN_REQUEST_TYPE) - : plugin_(plg), callback_id_(cbId), remote_method_(), client_info_(nullptr), type_(type) {} - ~CallbackParam() { - delete client_info_; - } - ConvergenceInstance *plugin_; - int callback_id_; - std::string remote_method_; - ConvergenceClientInfo* client_info_; - ServiceRequestType type_; + CallbackParam(ConvergenceInstance* plg, int cbId, ServiceRequestType type = UNKNOWN_REQUEST_TYPE) + : plugin_(plg), callback_id_(cbId), remote_method_(), client_info_(nullptr), type_(type) { + } + ~CallbackParam() { + delete client_info_; + } + ConvergenceInstance* plugin_; + int callback_id_; + std::string remote_method_; + ConvergenceClientInfo* client_info_; + ServiceRequestType type_; }; - -void trace_conv_error(const int error, int line_number, const char *extra_text); +void trace_conv_error(const int error, int line_number, const char* extra_text); class ConvergenceUtils { public: @@ -91,7 +87,7 @@ class ConvergenceUtils { static common::TizenResult ConvertConvergenceError(int error); }; -} // namespace convergence -} // namespace extension +} // namespace convergence +} // namespace extension -#endif // CONVERGENCE_CONVERGENCE_UTILS_H__ +#endif // CONVERGENCE_CONVERGENCE_UTILS_H__ diff --git a/src/datacontrol/datacontrol_extension.cc b/src/datacontrol/datacontrol_extension.cc old mode 100755 new mode 100644 index b1f4a3e..a18092d --- a/src/datacontrol/datacontrol_extension.cc +++ b/src/datacontrol/datacontrol_extension.cc @@ -30,9 +30,9 @@ DatacontrolExtension::DatacontrolExtension() { SetJavaScriptAPI(kSource_datacontrol_api); } -DatacontrolExtension::~DatacontrolExtension() {} +DatacontrolExtension::~DatacontrolExtension() { +} common::Instance* DatacontrolExtension::CreateInstance() { return new extension::datacontrol::DatacontrolInstance; } - diff --git a/src/datacontrol/datacontrol_instance.cc b/src/datacontrol/datacontrol_instance.cc old mode 100755 new mode 100644 index 60adcee..131b203 --- a/src/datacontrol/datacontrol_instance.cc +++ b/src/datacontrol/datacontrol_instance.cc @@ -18,16 +18,16 @@ #include +#include +#include #include #include #include -#include -#include -#include "common/picojson.h" #include "common/logger.h" -#include "common/tools.h" +#include "common/picojson.h" #include "common/platform_exception.h" +#include "common/tools.h" #include "common/scope_exit.h" @@ -67,38 +67,31 @@ static std::map IdMap; DatacontrolInstance::DatacontrolInstance() { using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&DatacontrolInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) \ + RegisterSyncHandler(c, std::bind(&DatacontrolInstance::x, this, _1, _2)); REGISTER_SYNC("SQLDataControlConsumer_update", SQLDataControlConsumerUpdate); - REGISTER_SYNC("MappedDataControlConsumer_addValue", - MappedDataControlConsumerAddvalue); - REGISTER_SYNC("SQLDataControlConsumer_select", - SQLDataControlConsumerSelect); + REGISTER_SYNC("MappedDataControlConsumer_addValue", MappedDataControlConsumerAddvalue); + REGISTER_SYNC("SQLDataControlConsumer_select", SQLDataControlConsumerSelect); REGISTER_SYNC("SQLDataControlConsumer_remove", SQLDataControlConsumerRemove); - REGISTER_SYNC("MappedDataControlConsumer_removeValue", - MappedDataControlConsumerRemovevalue); - REGISTER_SYNC("MappedDataControlConsumer_updateValue", - MappedDataControlConsumerUpdatevalue); + REGISTER_SYNC("MappedDataControlConsumer_removeValue", MappedDataControlConsumerRemovevalue); + REGISTER_SYNC("MappedDataControlConsumer_updateValue", MappedDataControlConsumerUpdatevalue); REGISTER_SYNC("DataControlManager_getDataControlConsumer", DataControlManagerGetdatacontrolconsumer); REGISTER_SYNC("SQLDataControlConsumer_insert", SQLDataControlConsumerInsert); - REGISTER_SYNC("MappedDataControlConsumer_getValue", - MappedDataControlConsumerGetvalue); - REGISTER_SYNC("DataControlConsumerObject_removeChangeListener", - RemoveChangeListener); - #undef REGISTER_SYNC - #define REGISTER_ASYNC(c, x) \ + REGISTER_SYNC("MappedDataControlConsumer_getValue", MappedDataControlConsumerGetvalue); + REGISTER_SYNC("DataControlConsumerObject_removeChangeListener", RemoveChangeListener); +#undef REGISTER_SYNC +#define REGISTER_ASYNC(c, x) \ RegisterSyncHandler(c, std::bind(&DatacontrolInstance::x, this, _1, _2)); - REGISTER_ASYNC("DataControlConsumerObject_addChangeListener", - AddChangeListener); - #undef REGISTER_ASYNC + REGISTER_ASYNC("DataControlConsumerObject_addChangeListener", AddChangeListener); +#undef REGISTER_ASYNC } DatacontrolInstance::~DatacontrolInstance() { } -static void ReplyAsync(DatacontrolInstance* instance, int callbackId, - bool isSuccess, picojson::object* param) { +static void ReplyAsync(DatacontrolInstance* instance, int callbackId, bool isSuccess, + picojson::object* param) { LoggerD("Enter"); (*param)["callbackId"] = picojson::value(static_cast(callbackId)); (*param)["status"] = picojson::value(isSuccess ? "success" : "error"); @@ -108,8 +101,7 @@ static void ReplyAsync(DatacontrolInstance* instance, int callbackId, common::Instance::PostMessage(instance, result.serialize().c_str()); } -static bool SQLColumnName(result_set_cursor cursor, int columnIndex, - picojson::value& name) { +static bool SQLColumnName(result_set_cursor cursor, int columnIndex, picojson::value& name) { LoggerD("Enter"); char buffer[4096]; int result = data_control_sql_get_column_name(cursor, columnIndex, buffer); @@ -121,12 +113,10 @@ static bool SQLColumnName(result_set_cursor cursor, int columnIndex, return true; } -static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, - picojson::value& val) { +static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, picojson::value& val) { LoggerD("Enter"); data_control_sql_column_type_e type = DATA_CONTROL_SQL_COLUMN_TYPE_UNDEFINED; - int result = - data_control_sql_get_column_item_type(cursor, columnIndex, &type); + int result = data_control_sql_get_column_item_type(cursor, columnIndex, &type); if (result != DATA_CONTROL_ERROR_NONE) { LoggerE("Getting column item type is failed with error : %d", result); return false; @@ -149,11 +139,10 @@ static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, case DATA_CONTROL_SQL_COLUMN_TYPE_TEXT: { int size = data_control_sql_get_column_item_size(cursor, columnIndex); if (DATA_CONTROL_ERROR_NONE > size) { - LoggerE("Getting column item size is failed with error : %s", - ::get_error_message(size)); + LoggerE("Getting column item size is failed with error : %s", ::get_error_message(size)); return false; } - char *buffer = new char[size + 1]; + char* buffer = new char[size + 1]; result = data_control_sql_get_text_data(cursor, columnIndex, buffer); if (result != DATA_CONTROL_ERROR_NONE) { LoggerE("Getting Text value failed : %s", get_error_message(result)); @@ -167,13 +156,11 @@ static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, case DATA_CONTROL_SQL_COLUMN_TYPE_BLOB: { int size = data_control_sql_get_column_item_size(cursor, columnIndex); if (DATA_CONTROL_ERROR_NONE > size) { - LoggerE("Getting column item size is failed with error : %s", - ::get_error_message(size)); + LoggerE("Getting column item size is failed with error : %s", ::get_error_message(size)); return false; } - char *buffer = new char[size + 1]; - result = - data_control_sql_get_blob_data(cursor, columnIndex, buffer, size); + char* buffer = new char[size + 1]; + result = data_control_sql_get_blob_data(cursor, columnIndex, buffer, size); if (result != DATA_CONTROL_ERROR_NONE) { delete[] buffer; break; @@ -192,50 +179,44 @@ static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, } } if (result != DATA_CONTROL_ERROR_NONE) { - LoggerE("Getting column item value is failed with error : %s", - ::get_error_message(result)); + LoggerE("Getting column item value is failed with error : %s", ::get_error_message(result)); return false; } else { return true; } } -static void MAPAddResponseCallback(int requestId, data_control_h handle, - bool providerResult, - const char *error, void *user_data) { +static void MAPAddResponseCallback(int requestId, data_control_h handle, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = InvalidValuesException(error).ToJSON(); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } -static void MAPSetResponseCallback(int requestId, data_control_h handle, - bool providerResult, - const char *error, void *user_data) { +static void MAPSetResponseCallback(int requestId, data_control_h handle, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = NotFoundException(error).ToJSON(); } @@ -245,75 +226,65 @@ static void MAPSetResponseCallback(int requestId, data_control_h handle, IdMap.erase(requestId); } -static void MAPGetResponseCallback(int requestId, data_control_h handle, - char **result_value_list, - int result_value_count, - bool providerResult, - const char *error, void *user_data) { +static void MAPGetResponseCallback(int requestId, data_control_h handle, char** result_value_list, + int result_value_count, bool providerResult, const char* error, + void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = NotFoundException(error).ToJSON(); } else { picojson::array result; - for (int i=0; i < result_value_count; i++) { + for (int i = 0; i < result_value_count; i++) { result.push_back(picojson::value(result_value_list[i])); } obj["result"] = picojson::value(result); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } -static void MAPRemoveReponseCallback(int requestId, data_control_h handle, - bool providerResult, - const char *error, void *user_data) { +static void MAPRemoveReponseCallback(int requestId, data_control_h handle, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = NotFoundException(error).ToJSON(); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } - static void SQLSelectResponseCallback(int requestId, data_control_h handle, - result_set_cursor cursor, - bool providerResult, - const char *error, void *user_data) { + result_set_cursor cursor, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = InvalidValuesException(error).ToJSON(); } else { @@ -324,11 +295,10 @@ static void SQLSelectResponseCallback(int requestId, data_control_h handle, picojson::array columns; picojson::array values; int columnCount = data_control_sql_get_column_count(cursor); - for (int i=0; i < columnCount; i++) { + for (int i = 0; i < columnCount; i++) { picojson::value column; picojson::value value; - if (SQLColumnName(cursor, i, column) && - SQLColumnValue(cursor, i, value)) { + if (SQLColumnName(cursor, i, column) && SQLColumnValue(cursor, i, value)) { columns.push_back(column); values.push_back(value); } @@ -339,113 +309,95 @@ static void SQLSelectResponseCallback(int requestId, data_control_h handle, } obj["result"] = picojson::value(result); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } static void SQLInsertResponseCallback(int requestId, data_control_h handle, - long long inserted_row_id, - bool providerResult, - const char *error, void *user_data) { + long long inserted_row_id, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = InvalidValuesException(error).ToJSON(); } else { obj["result"] = picojson::value(static_cast(inserted_row_id)); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } -static void SQLUpdateResponseCallback(int requestId, data_control_h handle, - bool providerResult, - const char *error, void *user_data) { +static void SQLUpdateResponseCallback(int requestId, data_control_h handle, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = InvalidValuesException(error).ToJSON(); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } -static void SQLDeleteResponseCallback(int requestId, data_control_h handle, - bool providerResult, - const char *error, void *user_data) { +static void SQLDeleteResponseCallback(int requestId, data_control_h handle, bool providerResult, + const char* error, void* user_data) { LoggerD("Enter"); - DatacontrolInformation *info = IdMap[requestId]; + DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); return; } picojson::object obj; - obj["requestId"] = - picojson::value(static_cast(info->userDefinedRequestId)); + obj["requestId"] = picojson::value(static_cast(info->userDefinedRequestId)); if (!providerResult) { obj["result"] = InvalidValuesException(error).ToJSON(); } - ReplyAsync(static_cast(user_data), info->callbackId, - providerResult, &obj); + ReplyAsync(static_cast(user_data), info->callbackId, providerResult, &obj); delete info; IdMap.erase(requestId); } static data_control_sql_response_cb sqlResponseCallback = { - SQLSelectResponseCallback, - SQLInsertResponseCallback, - SQLUpdateResponseCallback, - SQLDeleteResponseCallback -}; + SQLSelectResponseCallback, SQLInsertResponseCallback, SQLUpdateResponseCallback, + SQLDeleteResponseCallback}; static data_control_map_response_cb mapResponseCallback = { - MAPGetResponseCallback, - MAPSetResponseCallback, - MAPAddResponseCallback, - MAPRemoveReponseCallback -}; + MAPGetResponseCallback, MAPSetResponseCallback, MAPAddResponseCallback, + MAPRemoveReponseCallback}; -#define RETURN_IF_FAIL(result, msg) \ - do {\ - if (result != DATA_CONTROL_ERROR_NONE) {\ - LoggerE(msg" : %s", ::get_error_message(result));\ - return result;\ - }\ - } while (0)\ +#define RETURN_IF_FAIL(result, msg) \ + do { \ + if (result != DATA_CONTROL_ERROR_NONE) { \ + LoggerE(msg " : %s", ::get_error_message(result)); \ + return result; \ + } \ + } while (0) int DatacontrolInstance::RunMAPDataControlJob(const std::string& providerId, - const std::string& dataId, - int callbackId, - int userRequestId, - DataControlJob job) { + const std::string& dataId, int callbackId, + int userRequestId, DataControlJob job) { LoggerD("Enter"); int result = DATA_CONTROL_ERROR_NONE; - std::unique_ptr info {new DatacontrolInformation()}; + std::unique_ptr info{new DatacontrolInformation()}; info->callbackId = callbackId; info->userDefinedRequestId = userRequestId; data_control_h handle; @@ -455,20 +407,15 @@ int DatacontrolInstance::RunMAPDataControlJob(const std::string& providerId, }; result = ::data_control_map_create(&handle); - RETURN_IF_FAIL(result, - "Creating map data control handle is failed with error"); + RETURN_IF_FAIL(result, "Creating map data control handle is failed with error"); result = ::data_control_map_set_provider_id(handle, providerId.c_str()); - RETURN_IF_FAIL(result, - "Setting provider id is failed with error"); + RETURN_IF_FAIL(result, "Setting provider id is failed with error"); result = ::data_control_map_set_data_id(handle, dataId.c_str()); - RETURN_IF_FAIL(result, - "Setting data id is failed th error"); + RETURN_IF_FAIL(result, "Setting data id is failed th error"); - result = - ::data_control_map_register_response_cb(handle, &mapResponseCallback, - this); + result = ::data_control_map_register_response_cb(handle, &mapResponseCallback, this); RETURN_IF_FAIL(result, "Setting result Callback failed with error"); result = job(handle, &info->requestId); @@ -481,13 +428,11 @@ int DatacontrolInstance::RunMAPDataControlJob(const std::string& providerId, return result; } int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, - const std::string& dataId, - int callbackId, - int userRequestId, - DataControlJob job) { + const std::string& dataId, int callbackId, + int userRequestId, DataControlJob job) { LoggerD("Enter"); int result = DATA_CONTROL_ERROR_NONE; - std::unique_ptr info {new DatacontrolInformation()}; + std::unique_ptr info{new DatacontrolInformation()}; info->callbackId = callbackId; info->userDefinedRequestId = userRequestId; data_control_h handle; @@ -497,8 +442,7 @@ int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, }; result = ::data_control_sql_create(&handle); - RETURN_IF_FAIL(result, - "Creating sql data control handle is failed with error"); + RETURN_IF_FAIL(result, "Creating sql data control handle is failed with error"); result = ::data_control_sql_set_provider_id(handle, providerId.c_str()); RETURN_IF_FAIL(result, "Setting provider id is failed with error"); @@ -506,9 +450,7 @@ int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, result = ::data_control_sql_set_data_id(handle, dataId.c_str()); RETURN_IF_FAIL(result, "Setting data id is failed th error"); - result = - ::data_control_sql_register_response_cb(handle, &sqlResponseCallback, - this); + result = ::data_control_sql_register_response_cb(handle, &sqlResponseCallback, this); RETURN_IF_FAIL(result, "Setting result Callback failed with error"); result = job(handle, &info->requestId); @@ -521,22 +463,22 @@ int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, return result; } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } -void DatacontrolInstance::DataControlManagerGetdatacontrolconsumer( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::DataControlManagerGetdatacontrolconsumer(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "providerId", out) CHECK_EXIST(args, "dataId", out) } -void DatacontrolInstance::SQLDataControlConsumerInsert( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::SQLDataControlConsumerInsert(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -549,75 +491,71 @@ void DatacontrolInstance::SQLDataControlConsumerInsert( const std::string& dataId = args.get("dataId").get(); int callbackId = static_cast(args.get("callbackId").get()); int reqId = static_cast(args.get("reqId").get()); - picojson::object insertionData = - args.get("insertionData").get(); + picojson::object insertionData = args.get("insertionData").get(); if (!insertionData.count("columns") || !insertionData.count("values")) { - LogAndReportError(TypeMismatchException( - "columns and values is required insertionData argument"), out); + LogAndReportError( + TypeMismatchException("columns and values is required insertionData argument"), out); return; } if (!insertionData["columns"].is() || !insertionData["values"].is()) { - LogAndReportError(TypeMismatchException("columns and values type must be array"), - out); + LogAndReportError(TypeMismatchException("columns and values type must be array"), out); return; } - int result = RunSQLDataControlJob(providerId, dataId, callbackId, reqId, - [&insertionData](data_control_h& handle, - int *requestId) -> int { - picojson::array columns = insertionData["columns"].get(); - picojson::array values = insertionData["values"].get(); + int result = RunSQLDataControlJob( + providerId, dataId, callbackId, reqId, + [&insertionData](data_control_h& handle, int* requestId) -> int { + picojson::array columns = insertionData["columns"].get(); + picojson::array values = insertionData["values"].get(); - picojson::array::size_type columnsLength = columns.size(); - picojson::array::size_type valuesLength = values.size(); + picojson::array::size_type columnsLength = columns.size(); + picojson::array::size_type valuesLength = values.size(); - picojson::array::size_type size = std::min(columnsLength, valuesLength); + picojson::array::size_type size = std::min(columnsLength, valuesLength); - bundle * b = ::bundle_create(); - SCOPE_EXIT { - bundle_free(b); - }; - for (unsigned i=0; i < size; i++) { - picojson::value& column = columns[i]; - picojson::value& value = values[i]; + bundle* b = ::bundle_create(); + SCOPE_EXIT { + bundle_free(b); + }; + for (unsigned i = 0; i < size; i++) { + picojson::value& column = columns[i]; + picojson::value& value = values[i]; - if (!column.is() || !value.is()) { - break; - } + if (!column.is() || !value.is()) { + break; + } - const std::string& columnName = column.get(); - const std::string& valueString = value.get(); + const std::string& columnName = column.get(); + const std::string& valueString = value.get(); - int result = bundle_add_str(b, columnName.c_str(), valueString.c_str()); - if (BUNDLE_ERROR_NONE != result) { - return result; - } - } + int result = bundle_add_str(b, columnName.c_str(), valueString.c_str()); + if (BUNDLE_ERROR_NONE != result) { + return result; + } + } - return ::data_control_sql_insert(handle, b, requestId); - }); + return ::data_control_sql_insert(handle, b, requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else { LogAndReportError(UnknownException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::SQLDataControlConsumerUpdate( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::SQLDataControlConsumerUpdate(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -635,73 +573,67 @@ void DatacontrolInstance::SQLDataControlConsumerUpdate( picojson::object updateData = args.get("updateData").get(); if (!updateData.count("columns") || !updateData.count("values")) { - LogAndReportError(TypeMismatchException( - "columns and values is required updateData argument"), out); + LogAndReportError(TypeMismatchException("columns and values is required updateData argument"), + out); return; } - if (!updateData["columns"].is() || - !updateData["values"].is()) { - LogAndReportError(TypeMismatchException( - "columns and values type must be array"), out); + if (!updateData["columns"].is() || !updateData["values"].is()) { + LogAndReportError(TypeMismatchException("columns and values type must be array"), out); return; } - int result = RunSQLDataControlJob(providerId, dataId, callbackId, reqId, - [&updateData, &where]( - data_control_h& handle, - int *requestId) -> int { - LoggerD("Enter"); - picojson::array columns = updateData["columns"].get(); - picojson::array values = updateData["values"].get(); + int result = RunSQLDataControlJob( + providerId, dataId, callbackId, reqId, + [&updateData, &where](data_control_h& handle, int* requestId) -> int { + LoggerD("Enter"); + picojson::array columns = updateData["columns"].get(); + picojson::array values = updateData["values"].get(); - picojson::array::size_type columnsLength = columns.size(); - picojson::array::size_type valuesLength = values.size(); + picojson::array::size_type columnsLength = columns.size(); + picojson::array::size_type valuesLength = values.size(); - picojson::array::size_type size = std::min(columnsLength, valuesLength); + picojson::array::size_type size = std::min(columnsLength, valuesLength); - bundle * b = ::bundle_create(); - SCOPE_EXIT { - bundle_free(b); - }; - for (unsigned i=0; i < size; i++) { - picojson::value& column = columns[i]; - picojson::value& value = values[i]; + bundle* b = ::bundle_create(); + SCOPE_EXIT { + bundle_free(b); + }; + for (unsigned i = 0; i < size; i++) { + picojson::value& column = columns[i]; + picojson::value& value = values[i]; - if (!column.is() || !value.is()) { - break; - } + if (!column.is() || !value.is()) { + break; + } - std::string& columnName = column.get(); - std::string valueString = value.get(); + std::string& columnName = column.get(); + std::string valueString = value.get(); - bundle_add_str(b, columnName.c_str(), valueString.c_str()); - } + bundle_add_str(b, columnName.c_str(), valueString.c_str()); + } - return ::data_control_sql_update(handle, b, where.c_str(), requestId); - }); + return ::data_control_sql_update(handle, b, where.c_str(), requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::SQLDataControlConsumerRemove( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::SQLDataControlConsumerRemove(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -716,31 +648,29 @@ void DatacontrolInstance::SQLDataControlConsumerRemove( int reqId = static_cast(args.get("reqId").get()); const std::string& where = args.get("where").get(); - int result = RunSQLDataControlJob(providerId, dataId, callbackId, reqId, - [&where](data_control_h& handle, - int *requestId) -> int { - return ::data_control_sql_delete(handle, where.c_str(), requestId); - }); + int result = + RunSQLDataControlJob(providerId, dataId, callbackId, reqId, + [&where](data_control_h& handle, int* requestId) -> int { + return ::data_control_sql_delete(handle, where.c_str(), requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else { LogAndReportError(UnknownException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::SQLDataControlConsumerSelect( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::SQLDataControlConsumerSelect(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -764,8 +694,7 @@ void DatacontrolInstance::SQLDataControlConsumerSelect( page = static_cast(args.get("page").get()); } if (args.contains("maxNumberPerPage")) { - maxNumberPerPage = - static_cast(args.get("maxNumberPerPage").get()); + maxNumberPerPage = static_cast(args.get("maxNumberPerPage").get()); } char* order = nullptr; @@ -773,48 +702,41 @@ void DatacontrolInstance::SQLDataControlConsumerSelect( order = const_cast(args.get("order").get().c_str()); } - int result = RunSQLDataControlJob(providerId, dataId, callbackId, reqId, - [&columns, &where, order, page, maxNumberPerPage]( - data_control_h& handle, - int *requestId) -> int { - LoggerD("Enter"); - std::vector temp; - for (auto& s : columns) temp.push_back(s.get().c_str()); - int columnCount = static_cast(temp.size()); - char** cColumns = const_cast(&*temp.begin()); - - if (page > 0 && maxNumberPerPage > 0) { - return ::data_control_sql_select_with_page(handle, cColumns, - columnCount, where.c_str(), - order, page, - maxNumberPerPage, requestId); - } else { - return ::data_control_sql_select(handle, cColumns, columnCount, - where.c_str(), order, requestId); - } - }); + int result = RunSQLDataControlJob( + providerId, dataId, callbackId, reqId, [&columns, &where, order, page, maxNumberPerPage]( + data_control_h& handle, int* requestId) -> int { + LoggerD("Enter"); + std::vector temp; + for (auto& s : columns) temp.push_back(s.get().c_str()); + int columnCount = static_cast(temp.size()); + char** cColumns = const_cast(&*temp.begin()); + + if (page > 0 && maxNumberPerPage > 0) { + return ::data_control_sql_select_with_page(handle, cColumns, columnCount, where.c_str(), + order, page, maxNumberPerPage, requestId); + } else { + return ::data_control_sql_select(handle, cColumns, columnCount, where.c_str(), order, + requestId); + } + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunSQLDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::MappedDataControlConsumerAddvalue( - const picojson::value& args, - picojson::object& out) { +void DatacontrolInstance::MappedDataControlConsumerAddvalue(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -832,33 +754,29 @@ void DatacontrolInstance::MappedDataControlConsumerAddvalue( const std::string& value = args.get("value").get(); int result = RunMAPDataControlJob(providerId, dataId, callbackId, reqId, - [&key, &value](data_control_h& handle, - int *requestId) -> int { - return ::data_control_map_add(handle, key.c_str(), value.c_str(), - requestId); - }); + [&key, &value](data_control_h& handle, int* requestId) -> int { + return ::data_control_map_add(handle, key.c_str(), + value.c_str(), requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::MappedDataControlConsumerRemovevalue( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::MappedDataControlConsumerRemovevalue(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -876,32 +794,28 @@ void DatacontrolInstance::MappedDataControlConsumerRemovevalue( const std::string& value = args.get("value").get(); int result = RunMAPDataControlJob(providerId, dataId, callbackId, reqId, - [&key, &value](data_control_h& handle, - int *requestId) -> int { - return ::data_control_map_remove(handle, key.c_str(), value.c_str(), - requestId); - }); + [&key, &value](data_control_h& handle, int* requestId) -> int { + return ::data_control_map_remove(handle, key.c_str(), + value.c_str(), requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::MappedDataControlConsumerGetvalue( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::MappedDataControlConsumerGetvalue(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -917,31 +831,27 @@ void DatacontrolInstance::MappedDataControlConsumerGetvalue( const std::string& key = args.get("key").get(); int result = RunMAPDataControlJob(providerId, dataId, callbackId, reqId, - [&key](data_control_h& handle, - int *requestId) -> int { - return ::data_control_map_get(handle, key.c_str(), requestId); - }); + [&key](data_control_h& handle, int* requestId) -> int { + return ::data_control_map_get(handle, key.c_str(), requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -void DatacontrolInstance::MappedDataControlConsumerUpdatevalue( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::MappedDataControlConsumerUpdatevalue(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) @@ -960,64 +870,53 @@ void DatacontrolInstance::MappedDataControlConsumerUpdatevalue( const std::string& oldValue = args.get("oldValue").get(); const std::string& newValue = args.get("newValue").get(); - int result = RunMAPDataControlJob(providerId, dataId, callbackId, reqId, - [&key, &oldValue, &newValue]( - data_control_h& handle, - int *requestId) -> int { - return ::data_control_map_set(handle, key.c_str(), - oldValue.c_str(), newValue.c_str(), - requestId); - }); + int result = RunMAPDataControlJob( + providerId, dataId, callbackId, reqId, + [&key, &oldValue, &newValue](data_control_h& handle, int* requestId) -> int { + return ::data_control_map_set(handle, key.c_str(), oldValue.c_str(), newValue.c_str(), + requestId); + }); if (result == DATA_CONTROL_ERROR_NONE) { ReportSuccess(out); } else { if (result == DATA_CONTROL_ERROR_IO_ERROR) { - LogAndReportError( - IOException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(IOException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else if (result == DATA_CONTROL_ERROR_PERMISSION_DENIED) { - LogAndReportError( - SecurityException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(SecurityException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } else { - LogAndReportError( - UnknownException(get_error_message(result)), out, - ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException(get_error_message(result)), out, + ("RunMAPDataControlJob error: %d (%s)", result, get_error_message(result))); } } } -int DatacontrolInstance::CreateMAPHandle(const std::string& providerId, - const std::string& dataId, - data_control_h *handle) { +int DatacontrolInstance::CreateMAPHandle(const std::string& providerId, const std::string& dataId, + data_control_h* handle) { LoggerD("Enter"); int result = DATA_CONTROL_ERROR_NONE; result = ::data_control_map_create(handle); - RETURN_IF_FAIL(result, - "Creating map data control handle is failed with error"); + RETURN_IF_FAIL(result, "Creating map data control handle is failed with error"); result = ::data_control_map_set_provider_id(*handle, providerId.c_str()); - RETURN_IF_FAIL(result, - "Setting provider id is failed with error"); + RETURN_IF_FAIL(result, "Setting provider id is failed with error"); result = ::data_control_map_set_data_id(*handle, dataId.c_str()); - RETURN_IF_FAIL(result, - "Setting data id is failed the error"); + RETURN_IF_FAIL(result, "Setting data id is failed the error"); return result; } -int DatacontrolInstance::CreateSQLHandle(const std::string& providerId, - const std::string& dataId, - data_control_h *handle) { +int DatacontrolInstance::CreateSQLHandle(const std::string& providerId, const std::string& dataId, + data_control_h* handle) { LoggerD("Enter"); int result = DATA_CONTROL_ERROR_NONE; result = ::data_control_sql_create(handle); - RETURN_IF_FAIL(result, - "Creating sql data control handle is failed with error"); + RETURN_IF_FAIL(result, "Creating sql data control handle is failed with error"); result = ::data_control_sql_set_provider_id(*handle, providerId.c_str()); RETURN_IF_FAIL(result, "Setting provider id is failed with error"); @@ -1028,11 +927,11 @@ int DatacontrolInstance::CreateSQLHandle(const std::string& providerId, return result; } -PlatformResult DatacontrolInstance::ChangeTypeToString(data_control_data_change_type_e type_e, std::string *type) -{ +PlatformResult DatacontrolInstance::ChangeTypeToString(data_control_data_change_type_e type_e, + std::string* type) { LoggerD("Enter"); - switch(type_e) { + switch (type_e) { case DATA_CONTROL_DATA_CHANGE_SQL_UPDATE: *type = "SQL_UPDATE"; break; @@ -1052,27 +951,24 @@ PlatformResult DatacontrolInstance::ChangeTypeToString(data_control_data_change_ *type = "MAP_REMOVE"; break; default: - return LogAndCreateResult(ErrorCode::ABORT_ERR, - "Undefined data change type"); + return LogAndCreateResult(ErrorCode::ABORT_ERR, "Undefined data change type"); break; } return PlatformResult(ErrorCode::NO_ERROR); } -void DatacontrolInstance::callback(data_control_h provider, data_control_data_change_type_e type, bundle *bundle_data, void *user_data) -{ +void DatacontrolInstance::callback(data_control_h provider, data_control_data_change_type_e type, + bundle* bundle_data, void* user_data) { LoggerD("Enter"); auto data = static_cast(user_data); - char *provider_id = nullptr; - char *data_id = nullptr; + char* provider_id = nullptr; + char* data_id = nullptr; int result = DATA_CONTROL_ERROR_NONE; - if (DATA_CONTROL_DATA_CHANGE_SQL_UPDATE == type || - DATA_CONTROL_DATA_CHANGE_SQL_INSERT == type || + if (DATA_CONTROL_DATA_CHANGE_SQL_UPDATE == type || DATA_CONTROL_DATA_CHANGE_SQL_INSERT == type || DATA_CONTROL_DATA_CHANGE_SQL_DELETE == type) { - if (MAP == data->event_type) { LoggerI("Callback registered for different type"); return; @@ -1084,7 +980,6 @@ void DatacontrolInstance::callback(data_control_h provider, data_control_data_ch result = data_control_sql_get_data_id(provider, &data_id); } } else { - if (SQL == data->event_type) { LoggerI("Callback registered for different type"); return; @@ -1102,7 +997,8 @@ void DatacontrolInstance::callback(data_control_h provider, data_control_data_ch if (DATA_CONTROL_ERROR_NONE != result) { obj.insert(std::make_pair("callbackId", picojson::value(std::to_string(data->callbackId)))); - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier LogAndReportError(PlatformResult(ErrorCode::IO_ERR, "Get callback data failed"), &obj); Instance::PostMessage(data->_instance, event.serialize().c_str()); return; @@ -1126,20 +1022,24 @@ void DatacontrolInstance::callback(data_control_h provider, data_control_data_ch obj.insert(std::make_pair("columns", picojson::value(picojson::array()))); obj.insert(std::make_pair("values", picojson::value(picojson::array()))); - bundle_foreach(bundle_data, [](const char *key, const int type, const bundle_keyval_t *kv, void *user_data){ - LoggerD("Enter"); + bundle_foreach( + bundle_data, + [](const char* key, const int type, const bundle_keyval_t* kv, void* user_data) { + LoggerD("Enter"); - picojson::object &row_data = *(static_cast(user_data)); + picojson::object& row_data = *(static_cast(user_data)); - void *basic_val = NULL; - size_t basic_size = 0; + void* basic_val = NULL; + size_t basic_size = 0; - LoggerD("Key:%s, Type:%d\n", key, type); - bundle_keyval_get_basic_val(const_cast(kv), &basic_val, &basic_size); + LoggerD("Key:%s, Type:%d\n", key, type); + bundle_keyval_get_basic_val(const_cast(kv), &basic_val, &basic_size); - row_data["columns"].get().push_back(picojson::value(std::string(key))); - row_data["values"].get().push_back(picojson::value(std::string(static_cast(basic_val)))); - }, &obj); + row_data["columns"].get().push_back(picojson::value(std::string(key))); + row_data["values"].get().push_back( + picojson::value(std::string(static_cast(basic_val)))); + }, + &obj); obj.insert(std::make_pair("listenerId", picojson::value("DataControlManagerChangeCallback"))); @@ -1148,14 +1048,16 @@ void DatacontrolInstance::callback(data_control_h provider, data_control_data_ch // result_callback method is used only for pass information to errorCallback if any error // occur while adding listener -void DatacontrolInstance::result_callback(data_control_h provider, data_control_error_e result, int callback_id, void *user_data) { +void DatacontrolInstance::result_callback(data_control_h provider, data_control_error_e result, + int callback_id, void* user_data) { LoggerD("Enter"); if (DATA_CONTROL_ERROR_NONE != result) { auto data = static_cast(user_data); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); obj.insert(std::make_pair("callbackId", picojson::value(std::to_string(data->callbackId)))); - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier LogAndReportError(IOException("AddChangeListener failed"), obj); Instance::PostMessage(data->_instance, event.serialize().c_str()); if (0 != callback_id) { @@ -1164,7 +1066,6 @@ void DatacontrolInstance::result_callback(data_control_h provider, data_control_ } } - void DatacontrolInstance::AddChangeListener(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); @@ -1198,27 +1099,28 @@ void DatacontrolInstance::AddChangeListener(const picojson::value& args, picojso } }; - std::unique_ptr::type, decltype(deleter)> handle_ptr( - handle, deleter); + std::unique_ptr::type, decltype(deleter)> handle_ptr(handle, + deleter); std::shared_ptr user_data(new ReplyCallbackData()); user_data->_instance = this; user_data->callbackId = callbackId; user_data->event_type = type; - if (DATA_CONTROL_ERROR_NONE != result) { - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier result_callback(handle, DATA_CONTROL_ERROR_IO_ERROR, 0, user_data.get()); return; } - int watch_id = 0; - result = ::data_control_add_data_change_cb(handle, callback, user_data.get(), result_callback, user_data.get(), &watch_id); + result = ::data_control_add_data_change_cb(handle, callback, user_data.get(), result_callback, + user_data.get(), &watch_id); if (DATA_CONTROL_ERROR_NONE != result) { - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier result_callback(handle, DATA_CONTROL_ERROR_IO_ERROR, 0, user_data.get()); return; } @@ -1232,8 +1134,7 @@ void DatacontrolInstance::AddChangeListener(const picojson::value& args, picojso ReportSuccess(return_value, out); } -void DatacontrolInstance::RemoveChangeListener( - const picojson::value& args, picojson::object& out) { +void DatacontrolInstance::RemoveChangeListener(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatasharing, &out); @@ -1261,29 +1162,29 @@ void DatacontrolInstance::RemoveChangeListener( } if (DATA_CONTROL_ERROR_NONE != result) { - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier LogAndReportError(IOException("RemoveChangeListener failed"), out, - ("RemoveChangeListener failed: %d (%s)", result, - get_error_message(result))); + ("RemoveChangeListener failed: %d (%s)", result, get_error_message(result))); return; } - auto deleter = [&del](data_control_h handle){ + auto deleter = [&del](data_control_h handle) { if (handle && DATA_CONTROL_ERROR_NONE != del(handle)) { LoggerE("Destroy handle failed"); } }; - std::unique_ptr::type, decltype(deleter)> handle_ptr( - handle, deleter); + std::unique_ptr::type, decltype(deleter)> handle_ptr(handle, + deleter); result = ::data_control_remove_data_change_cb(handle, watch_id); if (DATA_CONTROL_ERROR_NONE != result) { - // According to native documentation only IOError can be returned to webapi, other errors are handled earlier + // According to native documentation only IOError can be returned to webapi, other errors are + // handled earlier LogAndReportError(IOException("RemoveChangeListener failed"), out, - ("RemoveChangeListener failed: %d (%s)", result, - get_error_message(result))); + ("RemoveChangeListener failed: %d (%s)", result, get_error_message(result))); return; } diff --git a/src/datacontrol/datacontrol_instance.h b/src/datacontrol/datacontrol_instance.h old mode 100755 new mode 100644 index 5b1c341..3478e97 --- a/src/datacontrol/datacontrol_instance.h +++ b/src/datacontrol/datacontrol_instance.h @@ -18,9 +18,9 @@ #define DATACONTROL_DATACONTROL_INSTANCE_H_ #include -#include #include #include +#include #include "common/extension.h" @@ -43,59 +43,41 @@ class DatacontrolInstance : public common::ParsedInstance { DatacontrolInstance(); virtual ~DatacontrolInstance(); - typedef std::function< int (data_control_h& handle, int *requestId) > - DataControlJob; - int RunMAPDataControlJob(const std::string& providerId, - const std::string& dataId, - int callbackId, int userRequestId, - DataControlJob job); - int RunSQLDataControlJob(const std::string& providerId, - const std::string& dataId, - int callbackId, int userRequestId, - DataControlJob job); - - int CreateMAPHandle(const std::string& providerId, - const std::string& dataId, - data_control_h *handle); - - int CreateSQLHandle(const std::string& providerId, - const std::string& dataId, - data_control_h *handle); - - void EraseMap(int watch_id) {reply_map.erase(watch_id);}; - - static void callback(data_control_h provider, - data_control_data_change_type_e type, - bundle *bundle_data, void *user_data); - static void result_callback(data_control_h provider, - data_control_error_e result, - int callback_id, void *user_data); + typedef std::function DataControlJob; + int RunMAPDataControlJob(const std::string& providerId, const std::string& dataId, int callbackId, + int userRequestId, DataControlJob job); + int RunSQLDataControlJob(const std::string& providerId, const std::string& dataId, int callbackId, + int userRequestId, DataControlJob job); + + int CreateMAPHandle(const std::string& providerId, const std::string& dataId, + data_control_h* handle); + + int CreateSQLHandle(const std::string& providerId, const std::string& dataId, + data_control_h* handle); + + void EraseMap(int watch_id) { + reply_map.erase(watch_id); + }; + + static void callback(data_control_h provider, data_control_data_change_type_e type, + bundle* bundle_data, void* user_data); + static void result_callback(data_control_h provider, data_control_error_e result, int callback_id, + void* user_data); static common::PlatformResult ChangeTypeToString(data_control_data_change_type_e type_e, - std::string *type); + std::string* type); private: - void DataControlManagerGetdatacontrolconsumer(const picojson::value& args, - picojson::object& out); - void SQLDataControlConsumerInsert(const picojson::value& args, - picojson::object& out); - void SQLDataControlConsumerUpdate(const picojson::value& args, - picojson::object& out); - void SQLDataControlConsumerRemove(const picojson::value& args, - picojson::object& out); - void SQLDataControlConsumerSelect(const picojson::value& args, - picojson::object& out); - void MappedDataControlConsumerAddvalue(const picojson::value& args, - picojson::object& out); - void MappedDataControlConsumerRemovevalue(const picojson::value& args, - picojson::object& out); - void MappedDataControlConsumerGetvalue(const picojson::value& args, - picojson::object& out); - void MappedDataControlConsumerUpdatevalue(const picojson::value& args, - picojson::object& out); - void AddChangeListener(const picojson::value& args, - picojson::object& out); - void RemoveChangeListener(const picojson::value& args, - picojson::object& out); + void DataControlManagerGetdatacontrolconsumer(const picojson::value& args, picojson::object& out); + void SQLDataControlConsumerInsert(const picojson::value& args, picojson::object& out); + void SQLDataControlConsumerUpdate(const picojson::value& args, picojson::object& out); + void SQLDataControlConsumerRemove(const picojson::value& args, picojson::object& out); + void SQLDataControlConsumerSelect(const picojson::value& args, picojson::object& out); + void MappedDataControlConsumerAddvalue(const picojson::value& args, picojson::object& out); + void MappedDataControlConsumerRemovevalue(const picojson::value& args, picojson::object& out); + void MappedDataControlConsumerGetvalue(const picojson::value& args, picojson::object& out); + void MappedDataControlConsumerUpdatevalue(const picojson::value& args, picojson::object& out); + void AddChangeListener(const picojson::value& args, picojson::object& out); + void RemoveChangeListener(const picojson::value& args, picojson::object& out); ReplyCallbackDataMap reply_map; }; diff --git a/src/download/download_extension.cc b/src/download/download_extension.cc old mode 100755 new mode 100644 index 1968ca1..ed83954 --- a/src/download/download_extension.cc +++ b/src/download/download_extension.cc @@ -29,14 +29,12 @@ DownloadExtension::DownloadExtension() { SetExtensionName("tizen.download"); SetJavaScriptAPI(kSource_download_api); - const char* entry_points[] = { - "tizen.DownloadRequest", - NULL - }; + const char* entry_points[] = {"tizen.DownloadRequest", NULL}; SetExtraJSEntryPoints(entry_points); } -DownloadExtension::~DownloadExtension() {} +DownloadExtension::~DownloadExtension() { +} common::Instance* DownloadExtension::CreateInstance() { return new extension::download::DownloadInstance; diff --git a/src/download/download_instance.cc b/src/download/download_instance.cc old mode 100755 new mode 100644 index 68179a1..1217373 --- a/src/download/download_instance.cc +++ b/src/download/download_instance.cc @@ -20,12 +20,12 @@ #include -#include "common/tools.h" -#include "common/picojson.h" -#include "common/logger.h" -#include "common/typeutil.h" #include "common/filesystem/filesystem_provider.h" +#include "common/logger.h" +#include "common/picojson.h" #include "common/scope_exit.h" +#include "common/tools.h" +#include "common/typeutil.h" namespace extension { namespace download { @@ -43,18 +43,16 @@ DownloadInstance::DownloadInstance() { LoggerD("Entered"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&DownloadInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&DownloadInstance::x, this, _1, _2)); REGISTER_SYNC("DownloadManager_pause", DownloadManagerPause); - REGISTER_SYNC - ("DownloadManager_getDownloadRequest", DownloadManagerGetdownloadrequest); + REGISTER_SYNC("DownloadManager_getDownloadRequest", DownloadManagerGetdownloadrequest); REGISTER_SYNC("DownloadManager_setListener", DownloadManagerSetlistener); REGISTER_SYNC("DownloadManager_getMIMEType", DownloadManagerGetmimetype); REGISTER_SYNC("DownloadManager_start", DownloadManagerStart); REGISTER_SYNC("DownloadManager_cancel", DownloadManagerCancel); REGISTER_SYNC("DownloadManager_resume", DownloadManagerResume); REGISTER_SYNC("DownloadManager_getState", DownloadManagerGetstate); - #undef REGISTER_SYNC +#undef REGISTER_SYNC std::lock_guard lock(instances_mutex_); instances_.push_back(this); @@ -64,26 +62,26 @@ DownloadInstance::~DownloadInstance() { LoggerD("Entered"); int ret; for (DownloadCallbackMap::iterator it = download_callbacks.begin(); - it != download_callbacks.end(); ++it) { + it != download_callbacks.end(); ++it) { DownloadInfoPtr diPtr = it->second->instance->diMap[it->second->callbackId]; SLoggerD("~DownloadInstance() for callbackID %d Called", it->second->callbackId); if (diPtr) { ret = download_unset_state_changed_cb(diPtr->download_id); if (ret != DOWNLOAD_ERROR_NONE) - LoggerE("download_unset_state_changed_cb() is failed. (%s)", get_error_message (ret)); + LoggerE("download_unset_state_changed_cb() is failed. (%s)", get_error_message(ret)); ret = download_unset_progress_cb(diPtr->download_id); if (ret != DOWNLOAD_ERROR_NONE) - LoggerE("download_unset_progress_cb() is failed. (%s)", get_error_message (ret)); + LoggerE("download_unset_progress_cb() is failed. (%s)", get_error_message(ret)); ret = download_cancel(diPtr->download_id); if (ret != DOWNLOAD_ERROR_NONE) - LoggerE("download_cancel() is failed. (%s)", get_error_message (ret)); + LoggerE("download_cancel() is failed. (%s)", get_error_message(ret)); ret = download_destroy(diPtr->download_id); if (ret != DOWNLOAD_ERROR_NONE) - LoggerE("download_destroy() is failed. (%s)", get_error_message (ret)); + LoggerE("download_destroy() is failed. (%s)", get_error_message(ret)); } else { LoggerD("diPtr is nullptr"); } @@ -198,22 +196,22 @@ common::PlatformResult DownloadInstance::convertError(int err) { } } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(common::PlatformResult(common::ErrorCode::TYPE_MISMATCH_ERR, name" is required argument"), &out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(common::PlatformResult(common::ErrorCode::TYPE_MISMATCH_ERR, \ + name " is required argument"), \ + &out); \ + return; \ + } -void DownloadInstance::OnStateChanged(int download_id, - download_state_e state, void* user_data) { +void DownloadInstance::OnStateChanged(int download_id, download_state_e state, void* user_data) { LoggerD("Entered"); CallbackPtr downCbPtr = static_cast(user_data); downCbPtr->state = state; downCbPtr->downloadId = download_id; - SLoggerD("State for callbackId %d changed to %d", - downCbPtr->callbackId, static_cast(state)); + SLoggerD("State for callbackId %d changed to %d", downCbPtr->callbackId, static_cast(state)); switch (state) { case DOWNLOAD_STATE_NONE: @@ -255,14 +253,12 @@ gboolean DownloadInstance::OnProgressChanged(void* user_data) { picojson::value::object out; out["status"] = picojson::value("progress"); - out["callbackId"] = - picojson::value(static_cast(downCbPtr->callbackId)); - out["receivedSize"] = - picojson::value(static_cast(downCbPtr->received)); + out["callbackId"] = picojson::value(static_cast(downCbPtr->callbackId)); + out["receivedSize"] = picojson::value(static_cast(downCbPtr->received)); out["totalSize"] = picojson::value(static_cast(diPtr->file_size)); - LoggerD("OnProgressChanged for callbackId %d Called: Received: %ld", - downCbPtr->callbackId, downCbPtr->received); + LoggerD("OnProgressChanged for callbackId %d Called: Received: %ld", downCbPtr->callbackId, + downCbPtr->received); picojson::value v = picojson::value(out); Instance::PostMessage(downCbPtr->instance, v.serialize().c_str()); @@ -316,8 +312,8 @@ gboolean DownloadInstance::OnFinished(void* user_data) { int ret = download_get_downloaded_file_path(downCbPtr->downloadId, &fullPath); if (ret != DOWNLOAD_ERROR_NONE) { - LogAndReportError(convertError(ret), &out, - ("download_get_downloaded_file_path error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(convertError(ret), &out, ("download_get_downloaded_file_path error: %d (%s)", + ret, get_error_message(ret))); } else { ret = download_unset_state_changed_cb(diPtr->download_id); if (ret != DOWNLOAD_ERROR_NONE) { @@ -366,8 +362,7 @@ gboolean DownloadInstance::OnPaused(void* user_data) { picojson::value::object out; out["status"] = picojson::value("paused"); - out["callbackId"] = - picojson::value(static_cast(callback_id)); + out["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(downCbPtr->instance, picojson::value(out).serialize().c_str()); return FALSE; @@ -407,8 +402,7 @@ gboolean DownloadInstance::OnCanceled(void* user_data) { picojson::value::object out; out["status"] = picojson::value("canceled"); - out["callbackId"] = - picojson::value(static_cast(callback_id)); + out["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(downCbPtr->instance, picojson::value(out).serialize().c_str()); downCbPtr->instance->download_callbacks.erase(callback_id); @@ -459,8 +453,7 @@ gboolean DownloadInstance::OnFailed(void* user_data) { LoggerE("%s", get_error_message(ret)); } - out["callbackId"] = - picojson::value(static_cast(downCbPtr->callbackId)); + out["callbackId"] = picojson::value(static_cast(downCbPtr->callbackId)); Instance::PostMessage(downCbPtr->instance, picojson::value(out).serialize().c_str()); downCbPtr->instance->download_callbacks.erase(callback_id); @@ -469,8 +462,8 @@ gboolean DownloadInstance::OnFailed(void* user_data) { return FALSE; } -void DownloadInstance::progress_changed_cb - (int download_id, long long unsigned received, void* user_data) { +void DownloadInstance::progress_changed_cb(int download_id, long long unsigned received, + void* user_data) { LoggerD("Entered"); CallbackPtr downCbPtr = static_cast(user_data); downCbPtr->received = received; @@ -479,8 +472,7 @@ void DownloadInstance::progress_changed_cb g_idle_add(OnProgressChanged, downCbPtr); } -void DownloadInstance::DownloadManagerStart - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerStart(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeDownload, &out); CHECK_EXIST(args, "callbackId", out) @@ -495,7 +487,8 @@ void DownloadInstance::DownloadManagerStart diPtr->url = args.get("url").is() ? args.get("url").get() : ""; if (!args.get("destination").is()) { - if (args.get("destination").is() && args.get("destination").get() != "") { + if (args.get("destination").is() && + args.get("destination").get() != "") { diPtr->destination = args.get("destination").get(); diPtr->destination = common::FilesystemProvider::Create().GetRealPath(diPtr->destination); } @@ -508,18 +501,17 @@ void DownloadInstance::DownloadManagerStart } if (!args.get("networkType").is()) { - networkType = args.get("networkType").is() ? - args.get("networkType").get() : "ALL"; + networkType = args.get("networkType").is() + ? args.get("networkType").get() + : "ALL"; } bool network_support = false; bool cell_support = false; bool wifi_support = false; - system_info_get_platform_bool("http://tizen.org/feature/network.telephony", - &cell_support); - system_info_get_platform_bool("http://tizen.org/feature/network.wifi", - &wifi_support); + system_info_get_platform_bool("http://tizen.org/feature/network.telephony", &cell_support); + system_info_get_platform_bool("http://tizen.org/feature/network.wifi", &wifi_support); connection_h connection = nullptr; connection_create(&connection); @@ -538,8 +530,8 @@ void DownloadInstance::DownloadManagerStart if (CONNECTION_TYPE_DISCONNECTED == connection_type) { LogAndReportError( - common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "Connection problem occured"), - &out, ("Connection type is disconnected")); + common::PlatformResult(common::ErrorCode::UNKNOWN_ERR, "Connection problem occured"), &out, + ("Connection type is disconnected")); return; } @@ -563,8 +555,7 @@ void DownloadInstance::DownloadManagerStart LogAndReportError( common::PlatformResult(common::ErrorCode::INVALID_VALUES_ERR, "The input parameter contains an invalid network type."), - &out, - ("The input parameter contains an invalid network type: %s", networkType.c_str())); + &out, ("The input parameter contains an invalid network type: %s", networkType.c_str())); return; } @@ -572,22 +563,18 @@ void DownloadInstance::DownloadManagerStart * There is no relevant feature for networkType == "ALL". */ if (!network_support && ("ALL" != networkType)) { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, - "The networkType of the given DownloadRequest " - "is not supported on this device."), - &out, - ("Requested network type (%s) is not supported.", networkType.c_str())); + LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, + "The networkType of the given DownloadRequest " + "is not supported on this device."), + &out, ("Requested network type (%s) is not supported.", networkType.c_str())); return; } if (!network_available) { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NETWORK_ERR, - "The networkType of the given DownloadRequest " - "is currently not available on this device."), - &out, - ("Requested network type (%s) is not available.", networkType.c_str())); + LogAndReportError(common::PlatformResult(common::ErrorCode::NETWORK_ERR, + "The networkType of the given DownloadRequest " + "is currently not available on this device."), + &out, ("Requested network type (%s) is not available.", networkType.c_str())); return; } @@ -605,16 +592,16 @@ void DownloadInstance::DownloadManagerStart return; } - ret = download_set_state_changed_cb (diPtr->download_id, OnStateChanged, - static_cast(downCbPtr)); + ret = download_set_state_changed_cb(diPtr->download_id, OnStateChanged, + static_cast(downCbPtr)); if (ret != DOWNLOAD_ERROR_NONE) { - LogAndReportError(convertError(ret), &out, - ("download_set_state_changed_cb error: %d (%s)", ret, get_error_message(ret))); + LogAndReportError(convertError(ret), &out, ("download_set_state_changed_cb error: %d (%s)", ret, + get_error_message(ret))); return; } - ret = download_set_progress_cb (diPtr->download_id, progress_changed_cb, - static_cast(downCbPtr)); + ret = download_set_progress_cb(diPtr->download_id, progress_changed_cb, + static_cast(downCbPtr)); if (ret != DOWNLOAD_ERROR_NONE) { LogAndReportError(convertError(ret), &out, ("download_set_progress_cb error: %d (%s)", ret, get_error_message(ret))); @@ -650,10 +637,9 @@ void DownloadInstance::DownloadManagerStart if (args.get("httpHeader").is()) { picojson::object obj = args.get("httpHeader").get(); - for (picojson::object::const_iterator it = obj.begin(); - it != obj.end(); ++it) { - download_add_http_header_field - (diPtr->download_id, it->first.c_str(), it->second.to_str().c_str()); + for (picojson::object::const_iterator it = obj.begin(); it != obj.end(); ++it) { + download_add_http_header_field(diPtr->download_id, it->first.c_str(), + it->second.to_str().c_str()); } } @@ -669,8 +655,7 @@ void DownloadInstance::DownloadManagerStart } } -void DownloadInstance::DownloadManagerCancel - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerCancel(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -678,10 +663,10 @@ void DownloadInstance::DownloadManagerCancel int callbackId = static_cast(args.get("downloadId").get()); if (!GetDownloadID(callbackId, downloadId)) { - LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, - "The identifier does not match any download operation in progress"), - &out, - ("The identifier %d does not match any download operation in progress", downloadId)); + LogAndReportError( + common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, + "The identifier does not match any download operation in progress"), + &out, ("The identifier %d does not match any download operation in progress", downloadId)); return; } @@ -695,8 +680,7 @@ void DownloadInstance::DownloadManagerCancel } } -void DownloadInstance::DownloadManagerPause - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerPause(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -704,10 +688,10 @@ void DownloadInstance::DownloadManagerPause int callbackId = static_cast(args.get("downloadId").get()); if (!GetDownloadID(callbackId, downloadId)) { - LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, - "The identifier does not match any download operation in progress"), - &out, - ("The identifier %d does not match any download operation in progress", downloadId)); + LogAndReportError( + common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, + "The identifier does not match any download operation in progress"), + &out, ("The identifier %d does not match any download operation in progress", downloadId)); return; } @@ -721,8 +705,7 @@ void DownloadInstance::DownloadManagerPause } } -void DownloadInstance::DownloadManagerResume - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerResume(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -730,10 +713,10 @@ void DownloadInstance::DownloadManagerResume int callbackId = static_cast(args.get("downloadId").get()); if (!GetDownloadID(callbackId, downloadId)) { - LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, - "The identifier does not match any download operation in progress"), - &out, - ("The identifier %d does not match any download operation in progress", downloadId)); + LogAndReportError( + common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, + "The identifier does not match any download operation in progress"), + &out, ("The identifier %d does not match any download operation in progress", downloadId)); return; } @@ -747,8 +730,7 @@ void DownloadInstance::DownloadManagerResume } } -void DownloadInstance::DownloadManagerGetstate - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerGetstate(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -758,10 +740,10 @@ void DownloadInstance::DownloadManagerGetstate int callbackId = static_cast(args.get("downloadId").get()); if (!GetDownloadID(callbackId, downloadId)) { - LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, - "The identifier does not match any download operation in progress"), - &out, - ("The identifier %d does not match any download operation in progress", downloadId)); + LogAndReportError( + common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, + "The identifier does not match any download operation in progress"), + &out, ("The identifier %d does not match any download operation in progress", downloadId)); return; } @@ -769,29 +751,29 @@ void DownloadInstance::DownloadManagerGetstate if (ret == DOWNLOAD_ERROR_NONE) { switch (state) { - case DOWNLOAD_STATE_NONE: - break; - case DOWNLOAD_STATE_QUEUED: - stateValue = "QUEUED"; - break; - case DOWNLOAD_STATE_DOWNLOADING: - stateValue = "DOWNLOADING"; - break; - case DOWNLOAD_STATE_PAUSED: - stateValue = "PAUSED"; - break; - case DOWNLOAD_STATE_COMPLETED: - stateValue = "COMPLETED"; - break; - case DOWNLOAD_STATE_FAILED: - stateValue = "FAILED"; - break; - case DOWNLOAD_STATE_CANCELED: - stateValue = "CANCELED"; - break; - default: - LoggerD("Unexpected download state: %d", state); - break; + case DOWNLOAD_STATE_NONE: + break; + case DOWNLOAD_STATE_QUEUED: + stateValue = "QUEUED"; + break; + case DOWNLOAD_STATE_DOWNLOADING: + stateValue = "DOWNLOADING"; + break; + case DOWNLOAD_STATE_PAUSED: + stateValue = "PAUSED"; + break; + case DOWNLOAD_STATE_COMPLETED: + stateValue = "COMPLETED"; + break; + case DOWNLOAD_STATE_FAILED: + stateValue = "FAILED"; + break; + case DOWNLOAD_STATE_CANCELED: + stateValue = "CANCELED"; + break; + default: + LoggerD("Unexpected download state: %d", state); + break; } ReportSuccess(picojson::value(stateValue), out); @@ -801,8 +783,8 @@ void DownloadInstance::DownloadManagerGetstate } } -void DownloadInstance::DownloadManagerGetmimetype - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerGetmimetype(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "downloadId", out) @@ -812,10 +794,10 @@ void DownloadInstance::DownloadManagerGetmimetype int callbackId = static_cast(args.get("downloadId").get()); if (!GetDownloadID(callbackId, downloadId)) { - LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, - "The identifier does not match any download operation in progress"), - &out, - ("The identifier %d does not match any download operation in progress", downloadId)); + LogAndReportError( + common::PlatformResult(common::ErrorCode::NOT_FOUND_ERR, + "The identifier does not match any download operation in progress"), + &out, ("The identifier %d does not match any download operation in progress", downloadId)); return; } @@ -830,8 +812,7 @@ void DownloadInstance::DownloadManagerGetmimetype free(mimetype); } -bool DownloadInstance::GetDownloadID - (const int callback_id, int& download_id) { +bool DownloadInstance::GetDownloadID(const int callback_id, int& download_id) { LoggerD("Entered"); if (diMap.find(callback_id) != diMap.end()) { download_id = diMap.find(callback_id)->second->download_id; @@ -841,19 +822,18 @@ bool DownloadInstance::GetDownloadID return true; } -void DownloadInstance::DownloadManagerGetdownloadrequest - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerGetdownloadrequest(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); // Nothing to do } -void DownloadInstance::DownloadManagerSetlistener - (const picojson::value& args, picojson::object& out) { +void DownloadInstance::DownloadManagerSetlistener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); // Nothing to do } - #undef CHECK_EXIST } // namespace download diff --git a/src/download/download_instance.h b/src/download/download_instance.h old mode 100755 new mode 100644 index 6af32da..a951c9e --- a/src/download/download_instance.h +++ b/src/download/download_instance.h @@ -17,24 +17,24 @@ #ifndef DOWNLOAD_DOWNLOAD_INSTANCE_H_ #define DOWNLOAD_DOWNLOAD_INSTANCE_H_ -#include #include +#include #include +#include #include +#include #include -#include #include #include -#include #include "common/extension.h" template - inline std::string to_string(const T& t) { - std::stringstream ss; - ss << t; - return ss.str(); - } +inline std::string to_string(const T& t) { + std::stringstream ss; + ss << t; + return ss.str(); +} namespace extension { namespace download { @@ -45,30 +45,20 @@ class DownloadInstance : public common::ParsedInstance { virtual ~DownloadInstance(); private: - void DownloadManagerStart - (const picojson::value& args, picojson::object& out); - void DownloadManagerCancel - (const picojson::value& args, picojson::object& out); - void DownloadManagerPause - (const picojson::value& args, picojson::object& out); - void DownloadManagerResume - (const picojson::value& args, picojson::object& out); - void DownloadManagerGetstate - (const picojson::value& args, picojson::object& out); - void DownloadManagerGetdownloadrequest - (const picojson::value& args, picojson::object& out); - void DownloadManagerGetmimetype - (const picojson::value& args, picojson::object& out); - void DownloadManagerSetlistener - (const picojson::value& args, picojson::object& out); + void DownloadManagerStart(const picojson::value& args, picojson::object& out); + void DownloadManagerCancel(const picojson::value& args, picojson::object& out); + void DownloadManagerPause(const picojson::value& args, picojson::object& out); + void DownloadManagerResume(const picojson::value& args, picojson::object& out); + void DownloadManagerGetstate(const picojson::value& args, picojson::object& out); + void DownloadManagerGetdownloadrequest(const picojson::value& args, picojson::object& out); + void DownloadManagerGetmimetype(const picojson::value& args, picojson::object& out); + void DownloadManagerSetlistener(const picojson::value& args, picojson::object& out); bool GetDownloadID(const int callback_id, int& download_id); static common::PlatformResult convertError(int err); - static void OnStateChanged - (int download_id, download_state_e state, void* user_data); - static void progress_changed_cb - (int download_id, long long unsigned received, void* user_data); + static void OnStateChanged(int download_id, download_state_e state, void* user_data); + static void progress_changed_cb(int download_id, long long unsigned received, void* user_data); static void OnStart(int download_id, void* user_data); static gboolean OnProgressChanged(void* user_data); diff --git a/src/exif/exif_extension.cc b/src/exif/exif_extension.cc old mode 100755 new mode 100644 index b6bfdc6..3c261cd --- a/src/exif/exif_extension.cc +++ b/src/exif/exif_extension.cc @@ -17,7 +17,9 @@ #include "exif/exif_extension.h" #include "exif/exif_instance.h" -common::Extension* CreateExtension() { return new ExifExtension; } +common::Extension* CreateExtension() { + return new ExifExtension; +} // This will be generated from exif_api.js. extern const char kSource_exif_api[]; @@ -30,6 +32,9 @@ ExifExtension::ExifExtension() { SetExtraJSEntryPoints(entry_points); } -ExifExtension::~ExifExtension() {} +ExifExtension::~ExifExtension() { +} -common::Instance* ExifExtension::CreateInstance() { return new extension::exif::ExifInstance; } +common::Instance* ExifExtension::CreateInstance() { + return new extension::exif::ExifInstance; +} diff --git a/src/exif/exif_gps_location.cc b/src/exif/exif_gps_location.cc old mode 100755 new mode 100644 index 806d7b1..2426cb0 --- a/src/exif/exif_gps_location.cc +++ b/src/exif/exif_gps_location.cc @@ -16,9 +16,9 @@ #include "exif/exif_gps_location.h" -#include -#include #include +#include +#include #include "common/assert.h" #include "common/logger.h" @@ -30,12 +30,9 @@ GCSPosition::GCSPosition() { LoggerD("Enter"); } -GCSPosition::GCSPosition(Rational _degrees, Rational _minutes, - Rational _seconds) : - degrees(_degrees), - minutes(_minutes), - seconds(_seconds) { - LoggerD("Enter"); +GCSPosition::GCSPosition(Rational _degrees, Rational _minutes, Rational _seconds) + : degrees(_degrees), minutes(_minutes), seconds(_seconds) { + LoggerD("Enter"); } bool GCSPosition::isValid() const { @@ -44,8 +41,7 @@ bool GCSPosition::isValid() const { return false; } - if ((degrees.toDouble() > 180.0f) || - (minutes.toDouble() > 60.0f) || + if ((degrees.toDouble() > 180.0f) || (minutes.toDouble() > 60.0f) || (seconds.toDouble() > 60.0f)) { return false; } @@ -58,7 +54,7 @@ double GCSPosition::toDouble() const { const double degrees_value = degrees.toDouble(); const double minutes_value = minutes.toDouble(); const double seconds_value = seconds.toDouble(); - return (degrees_value + (minutes_value/60.0) + (seconds_value/3600.0)); + return (degrees_value + (minutes_value / 60.0) + (seconds_value / 3600.0)); } Rationals GCSPosition::toRationalsVector() const { @@ -111,8 +107,7 @@ GCSPosition GCSPosition::createFromDouble(double value) { Assert(d_degrees <= 180.0); - LoggerD("d_degrees:%f d_minutes:%f d_seconds:%f", - d_degrees, d_minutes, d_seconds); + LoggerD("d_degrees:%f d_minutes:%f d_seconds:%f", d_degrees, d_minutes, d_seconds); GCSPosition pos; pos.degrees = Rational(static_cast(d_degrees), 1); @@ -122,9 +117,8 @@ GCSPosition GCSPosition::createFromDouble(double value) { return pos; } -ExifGPSLocation::ExifGPSLocation() : - m_longitude_ref(GPS_LOCATION_WEST), - m_latitude_ref(GPS_LOCATION_NORTH) { +ExifGPSLocation::ExifGPSLocation() + : m_longitude_ref(GPS_LOCATION_WEST), m_latitude_ref(GPS_LOCATION_NORTH) { for (int i = 0; i < EXIF_GPS_LOCATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; ++i) { LoggerD("Enter"); m_is_set[i] = false; @@ -222,7 +216,7 @@ void ExifGPSLocation::unsetAll() { LoggerD("Enter"); m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE] = false; m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] = false; - m_longitude = GCSPosition(); + m_longitude = GCSPosition(); m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE] = false; m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF] = false; @@ -232,12 +226,11 @@ void ExifGPSLocation::unsetAll() { bool ExifGPSLocation::isComplete() const { LoggerD("Enter"); return m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE] && - m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] && - m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE] && - m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF]; + m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] && + m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE] && + m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF]; } - bool ExifGPSLocation::isValid() const { LoggerD("Enter"); return isComplete() && m_latitude.isValid() && m_longitude.isValid(); @@ -245,16 +238,14 @@ bool ExifGPSLocation::isValid() const { double ExifGPSLocation::getLongitudeValue() const { LoggerD("Enter"); - const double longitude_dir = - (m_longitude_ref == GPS_LOCATION_WEST) ? -1.0f : 1.0f; + const double longitude_dir = (m_longitude_ref == GPS_LOCATION_WEST) ? -1.0f : 1.0f; const double longitude = m_longitude.toDouble() * longitude_dir; return longitude; } double ExifGPSLocation::getLatitudeValue() const { LoggerD("Enter"); - const double latitude_dir = - (m_latitude_ref == GPS_LOCATION_SOUTH) ? -1.0f : 1.0f; + const double latitude_dir = (m_latitude_ref == GPS_LOCATION_SOUTH) ? -1.0f : 1.0f; const double latitude = m_latitude.toDouble() * latitude_dir; return latitude; } diff --git a/src/exif/exif_gps_location.h b/src/exif/exif_gps_location.h old mode 100755 new mode 100644 index 2bafcb5..777bf36 --- a/src/exif/exif_gps_location.h +++ b/src/exif/exif_gps_location.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef EXIF_EXIF_GPS_LOCATION_H_ #define EXIF_EXIF_GPS_LOCATION_H_ @@ -26,15 +26,9 @@ namespace extension { namespace exif { -enum GPSLocationDirectionLongitude { - GPS_LOCATION_WEST, - GPS_LOCATION_EAST -}; +enum GPSLocationDirectionLongitude { GPS_LOCATION_WEST, GPS_LOCATION_EAST }; -enum GPSLocationDirectionLatitude { - GPS_LOCATION_NORTH, - GPS_LOCATION_SOUTH -}; +enum GPSLocationDirectionLatitude { GPS_LOCATION_NORTH, GPS_LOCATION_SOUTH }; enum ExifGPSLocationAttributes { EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE = 0, diff --git a/src/exif/exif_information.cc b/src/exif/exif_information.cc old mode 100755 new mode 100644 index e1541a1..08f7ed9 --- a/src/exif/exif_information.cc +++ b/src/exif/exif_information.cc @@ -16,8 +16,8 @@ #include "exif/exif_information.h" -#include #include +#include #include "common/assert.h" #include "common/converter.h" @@ -46,7 +46,7 @@ const std::string EXIF_UNDEFINED_TYPE_UNDEFINED = namespace { constexpr unsigned int str2int(const char* str, int h = 0) { - return !str[h] ? 5381 : (str2int(str, h+1)*33) ^ str[h]; + return !str[h] ? 5381 : (str2int(str, h + 1) * 33) ^ str[h]; } IsoSpeedRatingsVector jsonArray2vector(const picojson::value& a) { @@ -60,8 +60,7 @@ IsoSpeedRatingsVector jsonArray2vector(const picojson::value& a) { picojson::array v = a.get(); for (picojson::array::iterator it = v.begin(); it != v.end(); ++it) { - if ((*it).is()) - result.push_back(static_cast((*it).get())); + if ((*it).is()) result.push_back(static_cast((*it).get())); } return result; @@ -70,21 +69,19 @@ IsoSpeedRatingsVector jsonArray2vector(const picojson::value& a) { ExifInformation::ExifInformation() { LoggerD("Enter"); - for (int attr = 0; - attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { + for (int attr = 0; attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { unset(static_cast(attr)); } } ExifInformation::ExifInformation(const picojson::value& args) { LoggerD("Enter"); - for (int attr = 0; - attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { + for (int attr = 0; attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { unset(static_cast(attr)); } for (AttributeMap::const_iterator it = ExifInformationAttributeMap.begin(); - it != ExifInformationAttributeMap.end(); ++it) { + it != ExifInformationAttributeMap.end(); ++it) { std::string attributeName = it->second; picojson::value v = args.get(attributeName); if (!common::IsNull(v)) { @@ -95,7 +92,7 @@ ExifInformation::ExifInformation(const picojson::value& args) { ExifInformation::~ExifInformation() { LoggerD("Enter"); - } +} const std::string& ExifInformation::getUri() { LoggerD("Entered"); @@ -206,8 +203,7 @@ const std::vector& ExifInformation::getIsoSpeedRatings() { return m_iso_speed_ratings; } -void ExifInformation::setIsoSpeedRatings( -const std::vector& iso_speed_ratings) { +void ExifInformation::setIsoSpeedRatings(const std::vector& iso_speed_ratings) { LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_ISO_SPEED_RATINGS] = true; m_iso_speed_ratings = iso_speed_ratings; @@ -221,8 +217,7 @@ const Rational& ExifInformation::getExposureTime() { void ExifInformation::setExposureTime(const Rational& exposure_time) { LoggerD("Entered"); if (!exposure_time.isValid() || 0 == exposure_time.nominator) { - LoggerW("Trying to set invalid exposure time: [%s]", - exposure_time.toString().c_str()); + LoggerW("Trying to set invalid exposure time: [%s]", exposure_time.toString().c_str()); return; } @@ -232,7 +227,8 @@ void ExifInformation::setExposureTime(const Rational& exposure_time) { const std::string& ExifInformation::getExposureProgramString() { LoggerD("Entered"); - return ExifUtil::exposureProgramToString(m_exposure_program);; + return ExifUtil::exposureProgramToString(m_exposure_program); + ; } ExposureProgram ExifInformation::getExposureProgram() { @@ -270,8 +266,7 @@ const Rational& ExifInformation::getFocalLength() const { void ExifInformation::setFocalLength(Rational focal_length) { LoggerD("Entered"); if (!focal_length.isValid()) { - LoggerW("Trying to set invalid focal length: %s", - focal_length.toString().c_str()); + LoggerW("Trying to set invalid focal length: %s", focal_length.toString().c_str()); return; } @@ -325,8 +320,7 @@ const Rational& ExifInformation::getGpsAltitude() const { void ExifInformation::setGpsAltitude(Rational gps_altitude) { LoggerD("Entered"); if (!gps_altitude.isValid()) { - LoggerW("Trying to set invalid gps altitude: %s", - gps_altitude.toString().c_str()); + LoggerW("Trying to set invalid gps altitude: %s", gps_altitude.toString().c_str()); return; } @@ -378,14 +372,12 @@ const std::string& ExifInformation::getGpsProcessingMethodType() const { } void ExifInformation::setGpsProcessingMethod(const std::string& type, - const std::string& processing_method) { - LoggerD("Entered"); - if (type != EXIF_UNDEFINED_TYPE_ASCII && - type != EXIF_UNDEFINED_TYPE_JIS && - type != EXIF_UNDEFINED_TYPE_UNICODE && - type != EXIF_UNDEFINED_TYPE_UNDEFINED) { - LoggerW("Trying to set invalid GPSProcessingMethod type: [%s] len:%d", - type.c_str(), type.length()); + const std::string& processing_method) { + LoggerD("Entered"); + if (type != EXIF_UNDEFINED_TYPE_ASCII && type != EXIF_UNDEFINED_TYPE_JIS && + type != EXIF_UNDEFINED_TYPE_UNICODE && type != EXIF_UNDEFINED_TYPE_UNDEFINED) { + LoggerW("Trying to set invalid GPSProcessingMethod type: [%s] len:%d", type.c_str(), + type.length()); return; } @@ -421,15 +413,11 @@ const std::string& ExifInformation::getUserCommentType() { return m_user_comment_type; } -void ExifInformation::setUserComment(const std::string& type, - const std::string& user_comment) { +void ExifInformation::setUserComment(const std::string& type, const std::string& user_comment) { LoggerD("Entered"); - if (type != EXIF_UNDEFINED_TYPE_ASCII && - type != EXIF_UNDEFINED_TYPE_JIS && - type != EXIF_UNDEFINED_TYPE_UNICODE && - type != EXIF_UNDEFINED_TYPE_UNDEFINED) { - LoggerW("Trying to set invalid user comment type: [%s] len:%d", - type.c_str(), type.length()); + if (type != EXIF_UNDEFINED_TYPE_ASCII && type != EXIF_UNDEFINED_TYPE_JIS && + type != EXIF_UNDEFINED_TYPE_UNICODE && type != EXIF_UNDEFINED_TYPE_UNDEFINED) { + LoggerW("Trying to set invalid user comment type: [%s] len:%d", type.c_str(), type.length()); return; } @@ -544,7 +532,7 @@ void ExifInformation::set(std::string attributeName, const picojson::value& v) { } case str2int(EI_ORIGINAL_TIME): { setOriginalTime(static_cast(v.get())); - break; + break; } case str2int(EI_ORIENTATION): { setOrientation(v.get()); @@ -559,8 +547,7 @@ void ExifInformation::set(std::string attributeName, const picojson::value& v) { break; } case str2int(EI_EXPOSURE_TIME): { - setExposureTime( - Rational::createFromExposureTimeString(v.get())); + setExposureTime(Rational::createFromExposureTimeString(v.get())); break; } case str2int(EI_EXPOSURE_PROGRAM): { @@ -580,8 +567,8 @@ void ExifInformation::set(std::string attributeName, const picojson::value& v) { break; } case str2int(EI_GPS_LOCATION): { - setGPSLocation(ExifGPSLocation(v.get("longitude").get(), - v.get("latitude").get())); + setGPSLocation( + ExifGPSLocation(v.get("longitude").get(), v.get("latitude").get())); break; } case str2int(EI_GPS_ALTITUDE): { @@ -643,8 +630,7 @@ void ExifInformation::removeNulledAttributesFromExifData(ExifData* exif_data) { } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_ORIGINAL_TIME)) { LoggerD("Removing original time"); - ExifTagSaver::removeExifEntryWithTag( - EXIF_TAG_DATE_TIME_ORIGINAL, exif_data); + ExifTagSaver::removeExifEntryWithTag(EXIF_TAG_DATE_TIME_ORIGINAL, exif_data); } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_EXPOSURE_TIME)) { LoggerD("Removing exposure time"); @@ -664,23 +650,21 @@ void ExifInformation::removeNulledAttributesFromExifData(ExifData* exif_data) { } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_TIME)) { LoggerD("Removing gps altitude"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_TIME_STAMP), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_TIME_STAMP), exif_data); } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_ALTITUDE)) { LoggerD("Removing gps altitude"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_ALTITUDE), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_ALTITUDE), exif_data); } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_ALTITUDE_REF)) { LoggerD("Removing gps altitude ref"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_ALTITUDE_REF), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_ALTITUDE_REF), + exif_data); } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_PROCESSING_METHOD)) { LoggerD("Removing gps processing method"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_PROCESSING_METHOD), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_PROCESSING_METHOD), + exif_data); } if (!isSet(EXIF_INFORMATION_ATTRIBUTE_USER_COMMENT)) { LoggerD("Removing user comment"); @@ -688,23 +672,21 @@ void ExifInformation::removeNulledAttributesFromExifData(ExifData* exif_data) { } if (!m_gps_location.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE)) { LoggerD("Removing latitude"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_LATITUDE), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_LATITUDE), exif_data); } if (!m_gps_location.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF)) { LoggerD("Removing latitude ref"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_LATITUDE_REF), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_LATITUDE_REF), + exif_data); } if (!m_gps_location.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE)) { LoggerD("Removing longitude"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_LONGITUDE), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_LONGITUDE), exif_data); } if (!m_gps_location.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF)) { LoggerD("Removing longitude ref"); - ExifTagSaver::removeExifEntryWithTag( - static_cast(EXIF_TAG_GPS_LONGITUDE_REF), exif_data); + ExifTagSaver::removeExifEntryWithTag(static_cast(EXIF_TAG_GPS_LONGITUDE_REF), + exif_data); } } @@ -717,41 +699,36 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) if (isSet(EXIF_INFORMATION_ATTRIBUTE_WIDTH)) { LoggerD("Saving width: %d", getWidth()); - ret = ExifTagSaver::saveToExif(getWidth(), - EXIF_TAG_IMAGE_WIDTH, exif_data); + ret = ExifTagSaver::saveToExif(getWidth(), EXIF_TAG_IMAGE_WIDTH, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_HEIGHT)) { LoggerD("Saving height: %d", getHeight()); - ret = ExifTagSaver::saveToExif(getHeight(), - EXIF_TAG_IMAGE_LENGTH, exif_data); + ret = ExifTagSaver::saveToExif(getHeight(), EXIF_TAG_IMAGE_LENGTH, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_DEVICE_MAKER)) { LoggerD("Saving device maker: %s", getDeviceMaker().c_str()); - ret = ExifTagSaver::saveToExif(getDeviceMaker(), - EXIF_TAG_MAKE, exif_data); + ret = ExifTagSaver::saveToExif(getDeviceMaker(), EXIF_TAG_MAKE, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_ORIENTATION)) { LoggerD("Saving orientation: %d", static_cast(getOrientation())); - ret = ExifTagSaver::saveToExif(static_cast(getOrientation()), - EXIF_TAG_ORIENTATION, exif_data); + ret = ExifTagSaver::saveToExif(static_cast(getOrientation()), EXIF_TAG_ORIENTATION, + exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_EXPOSURE_PROGRAM)) { - LoggerD("Saving exposure program: %d", - static_cast(getExposureProgram())); - ret = ExifTagSaver::saveToExif(getExposureProgram(), - EXIF_TAG_EXPOSURE_PROGRAM, exif_data); + LoggerD("Saving exposure program: %d", static_cast(getExposureProgram())); + ret = ExifTagSaver::saveToExif(getExposureProgram(), EXIF_TAG_EXPOSURE_PROGRAM, exif_data); if (!ret) { return ret; } @@ -759,38 +736,33 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) if (isSet(EXIF_INFORMATION_ATTRIBUTE_ISO_SPEED_RATINGS)) { std::vector iso_ratings = getIsoSpeedRatings(); LoggerD("Saving iso speed ratings count:%d", iso_ratings.size()); - ret = ExifTagSaver::saveToExif(iso_ratings, EXIF_FORMAT_SHORT, - EXIF_TAG_ISO_SPEED_RATINGS, exif_data); + ret = ExifTagSaver::saveToExif(iso_ratings, EXIF_FORMAT_SHORT, EXIF_TAG_ISO_SPEED_RATINGS, + exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_WHITE_BALANCE)) { - LoggerD("Saving white balance: %d", - static_cast(getWhiteBalanceMode())); - ret = ExifTagSaver::saveToExif(getWhiteBalanceMode(), - EXIF_TAG_WHITE_BALANCE, exif_data); + LoggerD("Saving white balance: %d", static_cast(getWhiteBalanceMode())); + ret = ExifTagSaver::saveToExif(getWhiteBalanceMode(), EXIF_TAG_WHITE_BALANCE, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_DEVICE_MODEL)) { LoggerD("Saving device model: %s", getDeviceModel().c_str()); - ret = ExifTagSaver::saveToExif(getDeviceModel(), - EXIF_TAG_MODEL, exif_data); + ret = ExifTagSaver::saveToExif(getDeviceModel(), EXIF_TAG_MODEL, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_ORIGINAL_TIME)) { const time_t o_time = getOriginalTime(); - const std::string o_time_str = - ExifUtil::timeTToExifDateTimeOriginal(o_time); - LoggerD("Saving original time time_t:%d, format:%s", - static_cast(o_time), o_time_str.c_str()); + const std::string o_time_str = ExifUtil::timeTToExifDateTimeOriginal(o_time); + LoggerD("Saving original time time_t:%d, format:%s", static_cast(o_time), + o_time_str.c_str()); - ret = ExifTagSaver::saveToExif(o_time_str, - EXIF_TAG_DATE_TIME_ORIGINAL, exif_data); + ret = ExifTagSaver::saveToExif(o_time_str, EXIF_TAG_DATE_TIME_ORIGINAL, exif_data); if (!ret) { return ret; } @@ -798,12 +770,10 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) if (isSet(EXIF_INFORMATION_ATTRIBUTE_EXPOSURE_TIME)) { Rational exposure_time = getExposureTime(); if (exposure_time.isValid()) { - LoggerD("Saving exposure time: %s (%s)", - exposure_time.toString().c_str(), - exposure_time.toExposureTimeString().c_str()); + LoggerD("Saving exposure time: %s (%s)", exposure_time.toString().c_str(), + exposure_time.toExposureTimeString().c_str()); - ret = ExifTagSaver::saveToExif(exposure_time, - EXIF_TAG_EXPOSURE_TIME, exif_data); + ret = ExifTagSaver::saveToExif(exposure_time, EXIF_TAG_EXPOSURE_TIME, exif_data); if (!ret) { return ret; } @@ -811,28 +781,23 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) } if (isSet(EXIF_INFORMATION_ATTRIBUTE_FNUMBER)) { auto f_number = getFNumber(); - LoggerD("Saving f-number: %f (%s)", f_number.toDouble(), - f_number.toString().c_str()); - ret = ExifTagSaver::saveToExif(f_number, - EXIF_TAG_FNUMBER, exif_data); + LoggerD("Saving f-number: %f (%s)", f_number.toDouble(), f_number.toString().c_str()); + ret = ExifTagSaver::saveToExif(f_number, EXIF_TAG_FNUMBER, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_FLASH)) { LoggerD("Saving flash: %s", getFlash() ? "ON" : "OFF"); - ret = ExifTagSaver::saveToExif(getFlash(), - EXIF_TAG_FLASH, exif_data); + ret = ExifTagSaver::saveToExif(getFlash(), EXIF_TAG_FLASH, exif_data); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_FOCAL_LENGTH)) { auto f_length = getFocalLength(); - LoggerD("Saving focal length:%f (%s)", f_length.toDouble(), - f_length.toString().c_str()); - ret = ExifTagSaver::saveToExif(f_length, - EXIF_TAG_FOCAL_LENGTH, exif_data); + LoggerD("Saving focal length:%f (%s)", f_length.toDouble(), f_length.toString().c_str()); + ret = ExifTagSaver::saveToExif(f_length, EXIF_TAG_FOCAL_LENGTH, exif_data); if (!ret) { return ret; } @@ -846,9 +811,9 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) } if (isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_ALTITUDE)) { LoggerD("Saving gps altitude:%f (%s)", m_gps_altitude.toDouble(), - m_gps_altitude.toString().c_str()); - ret = ExifTagSaver::saveToExif(m_gps_altitude, - static_cast(EXIF_TAG_GPS_ALTITUDE), exif_data); + m_gps_altitude.toString().c_str()); + ret = ExifTagSaver::saveToExif(m_gps_altitude, static_cast(EXIF_TAG_GPS_ALTITUDE), + exif_data); if (!ret) { return ret; } @@ -857,12 +822,9 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) // Exif spec: // 0 = Sea level // 1 = Sea level reference (negative value) - LoggerD("Saving gps altitude ref:%d (%s)", - static_cast(m_gps_altitude_ref), - (static_cast(m_gps_altitude_ref) > 0) ? "below sea" : "above sea"); - std::vector value = { - static_cast(m_gps_altitude_ref) - }; + LoggerD("Saving gps altitude ref:%d (%s)", static_cast(m_gps_altitude_ref), + (static_cast(m_gps_altitude_ref) > 0) ? "below sea" : "above sea"); + std::vector value = {static_cast(m_gps_altitude_ref)}; ret = ExifTagSaver::saveToExif(value, EXIF_FORMAT_BYTE, static_cast(EXIF_TAG_GPS_ALTITUDE_REF), exif_data); if (!ret) { @@ -870,16 +832,14 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_PROCESSING_METHOD)) { - LoggerD("Saving gps processing method: [%s] type:%s", - getGpsProcessingMethod().c_str(), getGpsProcessingMethodType().c_str()); + LoggerD("Saving gps processing method: [%s] type:%s", getGpsProcessingMethod().c_str(), + getGpsProcessingMethodType().c_str()); - const std::string& joined = getGpsProcessingMethodType() + - getGpsProcessingMethod(); + const std::string& joined = getGpsProcessingMethodType() + getGpsProcessingMethod(); LoggerD("joined: [%s]", joined.c_str()); - ret = ExifTagSaver::saveToExif(joined, - static_cast(EXIF_TAG_GPS_PROCESSING_METHOD), exif_data, - EXIF_FORMAT_UNDEFINED, false); + ret = ExifTagSaver::saveToExif(joined, static_cast(EXIF_TAG_GPS_PROCESSING_METHOD), + exif_data, EXIF_FORMAT_UNDEFINED, false); if (!ret) { return ret; } @@ -887,34 +847,32 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) if (isSet(EXIF_INFORMATION_ATTRIBUTE_GPS_TIME)) { const time_t gps_time = getGpsTime(); const Rationals gps_time_vec = ExifUtil::timeTToExifGpsTimeStamp(gps_time); - const std::string& gps_date_str = - ExifUtil::timeTToExifGpsDateStamp(gps_time); + const std::string& gps_date_str = ExifUtil::timeTToExifGpsDateStamp(gps_time); LoggerD("Saving gps time stamp time_t: %d", static_cast(gps_time)); - ret = ExifTagSaver::saveToExif(gps_time_vec, - static_cast(EXIF_TAG_GPS_TIME_STAMP), exif_data); + ret = ExifTagSaver::saveToExif(gps_time_vec, static_cast(EXIF_TAG_GPS_TIME_STAMP), + exif_data); if (!ret) { return ret; } LoggerD("Saving gps date stamp: %s", gps_date_str.c_str()); - ret = ExifTagSaver::saveToExif(gps_date_str, - static_cast(EXIF_TAG_GPS_DATE_STAMP), exif_data, - EXIF_FORMAT_ASCII, false); + ret = ExifTagSaver::saveToExif(gps_date_str, static_cast(EXIF_TAG_GPS_DATE_STAMP), + exif_data, EXIF_FORMAT_ASCII, false); if (!ret) { return ret; } } if (isSet(EXIF_INFORMATION_ATTRIBUTE_USER_COMMENT)) { LoggerD("Saving user comment: %s (type:%s)", getUserComment().c_str(), - getUserCommentType().c_str()); + getUserCommentType().c_str()); const std::string& joined = getUserCommentType() + getUserComment(); LoggerD("joined: [%s]", joined.c_str()); - ret = ExifTagSaver::saveToExif(joined, - EXIF_TAG_USER_COMMENT, exif_data, EXIF_FORMAT_UNDEFINED, false); + ret = ExifTagSaver::saveToExif(joined, EXIF_TAG_USER_COMMENT, exif_data, EXIF_FORMAT_UNDEFINED, + false); if (!ret) { return ret; } @@ -925,21 +883,18 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) PlatformResult ExifInformation::saveToFile(const std::string& file_path) { LoggerD("Entered"); - LoggerD("Using JpegFile to read: [%s] and Exif if present", - file_path.c_str()); + LoggerD("Using JpegFile to read: [%s] and Exif if present", file_path.c_str()); JpegFilePtr jpg_file; PlatformResult result = JpegFile::loadFile(file_path, &jpg_file); - if (!result) - return result; + if (!result) return result; ExifData* exif_data = jpg_file->getExifData(); bool exif_data_is_new = false; // Exif is not present in file - create new ExifData if (!exif_data) { - LoggerD("Exif is not present in file: [%s] creating new", - file_path.c_str()); + LoggerD("Exif is not present in file: [%s] creating new", file_path.c_str()); exif_data = exif_data_new(); if (!exif_data) { diff --git a/src/exif/exif_information.h b/src/exif/exif_information.h old mode 100755 new mode 100644 index 809ac44..01fadad --- a/src/exif/exif_information.h +++ b/src/exif/exif_information.h @@ -62,7 +62,7 @@ extern const std::string EXIF_UNDEFINED_TYPE_JIS; extern const std::string EXIF_UNDEFINED_TYPE_UNICODE; extern const std::string EXIF_UNDEFINED_TYPE_UNDEFINED; -enum ExifInformationAttribute{ +enum ExifInformationAttribute { EXIF_INFORMATION_ATTRIBUTE_URI, EXIF_INFORMATION_ATTRIBUTE_WIDTH, EXIF_INFORMATION_ATTRIBUTE_HEIGHT, @@ -86,32 +86,27 @@ enum ExifInformationAttribute{ EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES }; -enum GpsAltitudeRef { - GPS_ALTITUDE_REF_ABOVE_SEA = 0, - GPS_ALTITUDE_REF_BELOW_SEA = 1 -}; - -const AttributeMap ExifInformationAttributeMap = { - {"uri", "uri"}, - {"width", "width"}, - {"height", "height"}, - {"deviceMaker", "deviceMaker"}, - {"deviceModel", "deviceModel"}, - {"originalTime", "originalTime"}, - {"orientation", "orientation"}, - {"fNumber", "fNumber"}, - {"isoSpeedRatings", "isoSpeedRatings"}, - {"exposureTime", "exposureTime"}, - {"exposureProgram", "exposureProgram"}, - {"flash", "flash"}, - {"focalLength", "focalLength"}, - {"whiteBalance", "whiteBalance"}, - {"gpsLocation", "gpsLocation"}, - {"gpsAltitude", "gpsAltitude"}, - {"gpsProcessingMethod", "gpsProcessingMethod"}, - {"gpsTime", "gpsTime"}, - {"userComment", "userComment"} -}; +enum GpsAltitudeRef { GPS_ALTITUDE_REF_ABOVE_SEA = 0, GPS_ALTITUDE_REF_BELOW_SEA = 1 }; + +const AttributeMap ExifInformationAttributeMap = {{"uri", "uri"}, + {"width", "width"}, + {"height", "height"}, + {"deviceMaker", "deviceMaker"}, + {"deviceModel", "deviceModel"}, + {"originalTime", "originalTime"}, + {"orientation", "orientation"}, + {"fNumber", "fNumber"}, + {"isoSpeedRatings", "isoSpeedRatings"}, + {"exposureTime", "exposureTime"}, + {"exposureProgram", "exposureProgram"}, + {"flash", "flash"}, + {"focalLength", "focalLength"}, + {"whiteBalance", "whiteBalance"}, + {"gpsLocation", "gpsLocation"}, + {"gpsAltitude", "gpsAltitude"}, + {"gpsProcessingMethod", "gpsProcessingMethod"}, + {"gpsTime", "gpsTime"}, + {"userComment", "userComment"}}; class ExifInformation { public: @@ -194,8 +189,7 @@ class ExifInformation { const std::string& getGpsProcessingMethod() const; const std::string& getGpsProcessingMethodType() const; - void setGpsProcessingMethod(const std::string& type, - const std::string& processing_method); + void setGpsProcessingMethod(const std::string& type, const std::string& processing_method); void setGpsTime(time_t time); time_t getGpsTime(); diff --git a/src/exif/exif_instance.cc b/src/exif/exif_instance.cc old mode 100755 new mode 100644 index 6f0101a..ced9129 --- a/src/exif/exif_instance.cc +++ b/src/exif/exif_instance.cc @@ -20,8 +20,8 @@ #include #include -#include #include +#include #include "common/logger.h" #include "common/platform_result.h" @@ -50,7 +50,8 @@ ExifInstance::ExifInstance() { #undef REGISTER_ASYNC } -ExifInstance::~ExifInstance() {} +ExifInstance::~ExifInstance() { +} void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson::object& out) { LoggerD("enter"); @@ -58,31 +59,31 @@ void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson: const std::string& uri = args.get("uri").get(); const double callback_id = args.get("callbackId").get(); - auto get = [=](const std::shared_ptr& response)->void { - JsonValue result = JsonValue(JsonObject()); - PlatformResult status(ErrorCode::NO_ERROR); + auto get = [=](const std::shared_ptr& response) -> void { + JsonValue result = JsonValue(JsonObject()); + PlatformResult status(ErrorCode::NO_ERROR); - const std::string &file_path = ExifUtil::convertUriToPath(uri); + const std::string& file_path = ExifUtil::convertUriToPath(uri); - PlatformResult fileAvailability(common::tools::CheckFileAvailability(file_path)); - if (!fileAvailability) { - LogAndReportError(fileAvailability, &response->get()); - return; - } + PlatformResult fileAvailability(common::tools::CheckFileAvailability(file_path)); + if (!fileAvailability) { + LogAndReportError(fileAvailability, &response->get()); + return; + } - LoggerD("file_path = %s", file_path.c_str()); + LoggerD("file_path = %s", file_path.c_str()); - status = GetExifInfo::LoadFromURI(uri, &result); - if (status) - ReportSuccess(result, response->get()); - else - LogAndReportError(status, &response->get()); + status = GetExifInfo::LoadFromURI(uri, &result); + if (status) + ReportSuccess(result, response->get()); + else + LogAndReportError(status, &response->get()); }; - auto get_response = [callback_id, this](const std::shared_ptr& response)->void { - picojson::object& obj = response->get(); - obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); - Instance::PostMessage(this, response->serialize().c_str()); + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { + picojson::object& obj = response->get(); + obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); + Instance::PostMessage(this, response->serialize().c_str()); }; auto data = std::shared_ptr(new JsonValue(JsonObject())); @@ -92,30 +93,29 @@ void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson: LoggerD("exit"); } -void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, - picojson::object& out) { +void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - JsonValue result = JsonValue(JsonObject()); - PlatformResult status(ErrorCode::NO_ERROR); - - ExifInformationPtr exifInfo(new ExifInformation(args)); - const std::string& uri = exifInfo->getUri(); - const std::string& path = ExifUtil::convertUriToPath(uri); - status = exifInfo->saveToFile(path); - - if (status) - ReportSuccess(result, response->get()); - else - LogAndReportError(status, &response->get()); + JsonValue result = JsonValue(JsonObject()); + PlatformResult status(ErrorCode::NO_ERROR); + + ExifInformationPtr exifInfo(new ExifInformation(args)); + const std::string& uri = exifInfo->getUri(); + const std::string& path = ExifUtil::convertUriToPath(uri); + status = exifInfo->saveToFile(path); + + if (status) + ReportSuccess(result, response->get()); + else + LogAndReportError(status, &response->get()); }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - picojson::object& obj = response->get(); - obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); - Instance::PostMessage(this, response->serialize().c_str()); + picojson::object& obj = response->get(); + obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); + Instance::PostMessage(this, response->serialize().c_str()); }; auto data = std::shared_ptr(new JsonValue(JsonObject())); @@ -123,76 +123,74 @@ void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, common::TaskQueue::GetInstance().Queue(get, get_response, data); } -void ExifInstance::ExifManagerGetThumbnail(const picojson::value& args, - picojson::object& out) { +void ExifInstance::ExifManagerGetThumbnail(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); const std::string& uri = args.get("uri").get(); const double callback_id = args.get("callbackId").get(); - auto get = [=](const std::shared_ptr &response) -> void { - PlatformResult status(ErrorCode::NO_ERROR); - - const std::string &file_path = ExifUtil::convertUriToPath(uri); - JsonValue result = JsonValue(JsonObject()); - JsonObject &result_obj = result.get(); - - PlatformResult fileAvailability(common::tools::CheckFileAvailability(file_path)); - if (!fileAvailability) { - LogAndReportError(fileAvailability, &response->get()); - return; - } - - LoggerD("file_path = %s", file_path.c_str()); - - std::string ext = file_path.substr(file_path.find_last_of(".") + 1); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - - if ("jpg" == ext) { - ext = "jpeg"; - } - - if ("jpeg" != ext && "png" != ext && "gif" != ext) { - status = PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "getThumbnail support only jpeg/jpg/png/gif"); - LogAndReportError(status, &response->get(), - ("extension: %s is not valid (jpeg/jpg/png/gif is supported)", ext.c_str())); - return; - } - - LoggerD("Get thumbnail from Exif in file: [%s]", file_path.c_str()); - ExifData *exif_data = exif_data_new_from_file(file_path.c_str()); - if (!exif_data) { - status = PlatformResult(ErrorCode::UNKNOWN_ERR, - "Error reading from file"); - LogAndReportError(status, &response->get(), - ("Error reading from file [%s]", file_path.c_str())); - return; - } - - if (!exif_data->data || !exif_data->size) { - exif_data_unref(exif_data); - status = PlatformResult(ErrorCode::UNKNOWN_ERR, - "File doesn't contain thumbnail"); - LogAndReportError(status, &response->get(), - ("File [%s] doesn't contain thumbnail", file_path.c_str())); - return; - } - - gchar *ch_uri = g_base64_encode(exif_data->data, exif_data->size); + auto get = [=](const std::shared_ptr& response) -> void { + PlatformResult status(ErrorCode::NO_ERROR); + + const std::string& file_path = ExifUtil::convertUriToPath(uri); + JsonValue result = JsonValue(JsonObject()); + JsonObject& result_obj = result.get(); + + PlatformResult fileAvailability(common::tools::CheckFileAvailability(file_path)); + if (!fileAvailability) { + LogAndReportError(fileAvailability, &response->get()); + return; + } + + LoggerD("file_path = %s", file_path.c_str()); + + std::string ext = file_path.substr(file_path.find_last_of(".") + 1); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + + if ("jpg" == ext) { + ext = "jpeg"; + } + + if ("jpeg" != ext && "png" != ext && "gif" != ext) { + status = PlatformResult(ErrorCode::INVALID_VALUES_ERR, + "getThumbnail support only jpeg/jpg/png/gif"); + LogAndReportError( + status, &response->get(), + ("extension: %s is not valid (jpeg/jpg/png/gif is supported)", ext.c_str())); + return; + } + + LoggerD("Get thumbnail from Exif in file: [%s]", file_path.c_str()); + ExifData* exif_data = exif_data_new_from_file(file_path.c_str()); + if (!exif_data) { + status = PlatformResult(ErrorCode::UNKNOWN_ERR, "Error reading from file"); + LogAndReportError(status, &response->get(), + ("Error reading from file [%s]", file_path.c_str())); + return; + } + + if (!exif_data->data || !exif_data->size) { exif_data_unref(exif_data); - std::string base64 = "data:image/" + ext + ";base64," + ch_uri; + status = PlatformResult(ErrorCode::UNKNOWN_ERR, "File doesn't contain thumbnail"); + LogAndReportError(status, &response->get(), + ("File [%s] doesn't contain thumbnail", file_path.c_str())); + return; + } - std::pair pair; - pair = std::make_pair("src", picojson::value(base64)); - result_obj.insert(pair); + gchar* ch_uri = g_base64_encode(exif_data->data, exif_data->size); + exif_data_unref(exif_data); + std::string base64 = "data:image/" + ext + ";base64," + ch_uri; - ReportSuccess(result, response->get()); + std::pair pair; + pair = std::make_pair("src", picojson::value(base64)); + result_obj.insert(pair); + + ReportSuccess(result, response->get()); }; - auto get_response = [callback_id, this](const std::shared_ptr& response)->void { - picojson::object& obj = response->get(); - obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); - Instance::PostMessage(this, response->serialize().c_str()); + auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { + picojson::object& obj = response->get(); + obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); + Instance::PostMessage(this, response->serialize().c_str()); }; auto data = std::shared_ptr(new JsonValue(JsonObject())); diff --git a/src/exif/exif_tag_saver.cc b/src/exif/exif_tag_saver.cc old mode 100755 new mode 100644 index dc49cba..11bab29 --- a/src/exif/exif_tag_saver.cc +++ b/src/exif/exif_tag_saver.cc @@ -16,19 +16,18 @@ #include "exif/exif_tag_saver.h" #include -#include #include +#include -#include "common/platform_result.h" #include "common/logger.h" +#include "common/platform_result.h" #include "exif/exif_util.h" namespace extension { namespace exif { -void ExifTagSaver::removeExifEntryWithTag(const ExifTag tag, - ExifData* exif_data) { +void ExifTagSaver::removeExifEntryWithTag(const ExifTag tag, ExifData* exif_data) { LoggerD("Entered tag:%d (0x%x)", tag, tag); ExifEntry* exif_entry = exif_data_get_entry(exif_data, tag); if (!exif_entry) { @@ -39,8 +38,7 @@ void ExifTagSaver::removeExifEntryWithTag(const ExifTag tag, exif_content_remove_entry(exif_entry->parent, exif_entry); } -common::PlatformResult ExifTagSaver::saveToExif(long int value, ExifTag tag, - ExifData* exif_data) { +common::PlatformResult ExifTagSaver::saveToExif(long int value, ExifTag tag, ExifData* exif_data) { LoggerD("Entered"); ExifEntry* entry = prepareEntry(exif_data, tag); @@ -72,7 +70,7 @@ common::PlatformResult ExifTagSaver::saveToExif(long int value, ExifTag tag, } default: { return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Wrong format", - ("Error: wrong format: %d \n", entry->format)); + ("Error: wrong format: %d \n", entry->format)); } } return common::PlatformResult(common::ErrorCode::NO_ERROR); @@ -150,7 +148,7 @@ common::PlatformResult ExifTagSaver::saveToExif(const Rational& value, ExifTag t } common::PlatformResult ExifTagSaver::saveToExif(const Rationals& value, ExifTag tag, - ExifData* exif_data) { + ExifData* exif_data) { LoggerD("Entered"); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { @@ -186,8 +184,8 @@ common::PlatformResult ExifTagSaver::saveToExif(const Rationals& value, ExifTag } common::PlatformResult ExifTagSaver::saveToExif(std::vector& value, - ExifFormat store_as, - ExifTag tag, ExifData* exif_data) { + ExifFormat store_as, ExifTag tag, + ExifData* exif_data) { LoggerD("Entered"); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { @@ -205,7 +203,7 @@ common::PlatformResult ExifTagSaver::saveToExif(std::vector& valu break; default: return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "ExifFormat is not supported!", - ("output ExifFormat: %d is not supported!", store_as)); + ("output ExifFormat: %d is not supported!", store_as)); } entry->format = store_as; @@ -226,7 +224,6 @@ common::PlatformResult ExifTagSaver::saveToExif(std::vector& valu } entry->components = num_elements; - switch (store_as) { case EXIF_FORMAT_BYTE: { for (std::size_t i = 0; i < num_elements; ++i) { @@ -236,29 +233,26 @@ common::PlatformResult ExifTagSaver::saveToExif(std::vector& valu } case EXIF_FORMAT_SHORT: { for (std::size_t i = 0; i < num_elements; ++i) { - exif_set_short(entry->data + i * size_per_member, order, - static_cast(value[i])); + exif_set_short(entry->data + i * size_per_member, order, static_cast(value[i])); } break; } case EXIF_FORMAT_SSHORT: { for (std::size_t i = 0; i < num_elements; ++i) { exif_set_sshort(entry->data + i * size_per_member, order, - static_cast(value[i])); + static_cast(value[i])); } break; } case EXIF_FORMAT_LONG: { for (std::size_t i = 0; i < num_elements; ++i) { - exif_set_long(entry->data + i * size_per_member, order, - static_cast(value[i])); + exif_set_long(entry->data + i * size_per_member, order, static_cast(value[i])); } break; } case EXIF_FORMAT_SLONG: { for (std::size_t i = 0; i < num_elements; ++i) { - exif_set_slong(entry->data + i * size_per_member, order, - static_cast(value[i])); + exif_set_slong(entry->data + i * size_per_member, order, static_cast(value[i])); } break; } @@ -284,19 +278,18 @@ common::PlatformResult ExifTagSaver::saveGpsLocationToExif(const ExifGPSLocation if (gps_info.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE)) { auto latitude = gps_info.getLatitude(); LoggerD("Saving latitude: %s", latitude.toDebugString().c_str()); - ret = saveToExif(latitude.toRationalsVector(), - static_cast(EXIF_TAG_GPS_LATITUDE), exif_data); + ret = saveToExif(latitude.toRationalsVector(), static_cast(EXIF_TAG_GPS_LATITUDE), + exif_data); if (!ret) { return ret; } } if (gps_info.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF)) { - std::string lat_ref = - (gps_info.getLatitudeRef() == GPS_LOCATION_NORTH) ? "N" : "S"; + std::string lat_ref = (gps_info.getLatitudeRef() == GPS_LOCATION_NORTH) ? "N" : "S"; LoggerD("Saving latitude ref: %s", lat_ref.c_str()); - ret = saveToExif(lat_ref, static_cast(EXIF_TAG_GPS_LATITUDE_REF), - exif_data, EXIF_FORMAT_ASCII, false); + ret = saveToExif(lat_ref, static_cast(EXIF_TAG_GPS_LATITUDE_REF), exif_data, + EXIF_FORMAT_ASCII, false); if (!ret) { return ret; } @@ -305,19 +298,18 @@ common::PlatformResult ExifTagSaver::saveGpsLocationToExif(const ExifGPSLocation if (gps_info.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE)) { auto longitude = gps_info.getLongitude(); LoggerD("Saving longitude: %s", longitude.toDebugString().c_str()); - ret = saveToExif(longitude.toRationalsVector(), - static_cast(EXIF_TAG_GPS_LONGITUDE), exif_data); + ret = saveToExif(longitude.toRationalsVector(), static_cast(EXIF_TAG_GPS_LONGITUDE), + exif_data); if (!ret) { return ret; } } if (gps_info.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF)) { - std::string long_ref = - (gps_info.getLongitudeRef() == GPS_LOCATION_WEST) ? "W" : "E"; + std::string long_ref = (gps_info.getLongitudeRef() == GPS_LOCATION_WEST) ? "W" : "E"; LoggerD("Saving longitude ref: %s", long_ref.c_str()); - ret = saveToExif(long_ref, static_cast(EXIF_TAG_GPS_LONGITUDE_REF), - exif_data, EXIF_FORMAT_ASCII, false); + ret = saveToExif(long_ref, static_cast(EXIF_TAG_GPS_LONGITUDE_REF), exif_data, + EXIF_FORMAT_ASCII, false); if (!ret) { return ret; } @@ -357,8 +349,8 @@ ExifEntry* ExifTagSaver::prepareEntry(ExifData* exif_data, ExifTag tag) { return exif_entry; } -ExifEntry* ExifTagSaver::createNewTag(ExifData* exif_data, ExifIfd ifd, - ExifFormat format, ExifTag tag) { +ExifEntry* ExifTagSaver::createNewTag(ExifData* exif_data, ExifIfd ifd, ExifFormat format, + ExifTag tag) { LoggerD("Creating new tag: %d", tag); ExifEntry* new_entry = exif_entry_new(); @@ -415,7 +407,7 @@ common::PlatformResult ExifTagSaver::deduceIfdSection(ExifTag tag, ExifIfd* exif // Tags in other sections default: return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Unsupported tag", - ("Unsupported tag: %d", tag)); + ("Unsupported tag: %d", tag)); } return common::PlatformResult(common::ErrorCode::NO_ERROR); @@ -475,7 +467,7 @@ common::PlatformResult ExifTagSaver::deduceDataFormat(ExifTag tag, ExifFormat* e // Unsupported tags: default: return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Unsupported tag", - ("Unsupported tag: %d", tag)); + ("Unsupported tag: %d", tag)); } return common::PlatformResult(common::ErrorCode::NO_ERROR); diff --git a/src/exif/exif_tag_saver.h b/src/exif/exif_tag_saver.h old mode 100755 new mode 100644 index ba13eb2..013a17d --- a/src/exif/exif_tag_saver.h +++ b/src/exif/exif_tag_saver.h @@ -34,23 +34,22 @@ class ExifTagSaver { static common::PlatformResult saveToExif(long int value, ExifTag tag, ExifData* exif_data); static common::PlatformResult saveToExif(const std::string& value, ExifTag tag, - ExifData* exif_data, ExifFormat format = EXIF_FORMAT_ASCII, - bool add_zero_character = true); - static common::PlatformResult saveToExif(const Rational& value, ExifTag tag, - ExifData* exif_data); + ExifData* exif_data, + ExifFormat format = EXIF_FORMAT_ASCII, + bool add_zero_character = true); + static common::PlatformResult saveToExif(const Rational& value, ExifTag tag, ExifData* exif_data); static common::PlatformResult saveToExif(const Rationals& value, ExifTag tag, - ExifData* exif_data); + ExifData* exif_data); static common::PlatformResult saveToExif(std::vector& value, ExifFormat store_as, - ExifTag tag, ExifData* exif_data); + ExifTag tag, ExifData* exif_data); static common::PlatformResult saveGpsLocationToExif(const ExifGPSLocation& gps_info, - ExifData* exif_data); + ExifData* exif_data); private: static ExifEntry* prepareEntry(ExifData* exif_data, ExifTag tag); static common::PlatformResult deduceIfdSection(ExifTag tag, ExifIfd* exif_ifd); static common::PlatformResult deduceDataFormat(ExifTag tag, ExifFormat* exif_format); - static ExifEntry* createNewTag(ExifData* exif_data, ExifIfd ifd, - ExifFormat format, ExifTag tag); + static ExifEntry* createNewTag(ExifData* exif_data, ExifIfd ifd, ExifFormat format, ExifTag tag); }; } // namespace exif diff --git a/src/exif/exif_util.cc b/src/exif/exif_util.cc old mode 100755 new mode 100644 index 3669b37..9f9bc90 --- a/src/exif/exif_util.cc +++ b/src/exif/exif_util.cc @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "exif/exif_util.h" #include #include -#include "common/platform_result.h" #include "common/logger.h" +#include "common/platform_result.h" namespace extension { namespace exif { @@ -130,8 +130,7 @@ const std::string& ExifUtil::orientationToString(ImageOrientation orientation) { } } -WhiteBalanceMode ExifUtil::stringToWhiteBalance( - const std::string& white_balance) { +WhiteBalanceMode ExifUtil::stringToWhiteBalance(const std::string& white_balance) { LoggerD("Entered"); if (WHITE_BALANCE_MODE_AUTO == white_balance) { return WhiteBalanceMode::EXIF_WHITE_BALANCE_MODE_AUTO; @@ -154,8 +153,7 @@ const std::string& ExifUtil::whiteBalanceToString(WhiteBalanceMode value) { } } -ExposureProgram ExifUtil::stringToExposureProgram( - const std::string& exposure_program) { +ExposureProgram ExifUtil::stringToExposureProgram(const std::string& exposure_program) { LoggerD("Entered"); if (EXPOSURE_PROGRAM_NOT_DEFINED == exposure_program) { return EXIF_EXPOSURE_PROGRAM_NOT_DEFINED; @@ -246,8 +244,7 @@ std::string ExifUtil::ltrim(const std::string& s) { time_t ExifUtil::exifDateTimeOriginalToTimeT(const char* string) { int year, month, day, hour, min, sec; - if (sscanf(string, "%5d:%5d:%5d %5d:%5d:%5d", - &year, &month, &day, &hour, &min, &sec) >= 6) { + if (sscanf(string, "%5d:%5d:%5d %5d:%5d:%5d", &year, &month, &day, &hour, &min, &sec) >= 6) { return convertToTimeT(year, month, day, hour, min, sec); } @@ -303,7 +300,7 @@ std::string ExifUtil::timeTToExifGpsDateStamp(time_t time) { return ss.str(); } -size_t ExifUtil::getSizeOfExifFormatType(ExifFormat format) { +size_t ExifUtil::getSizeOfExifFormatType(ExifFormat format) { std::size_t size_per_member = 0; switch (format) { case EXIF_FORMAT_BYTE: @@ -368,16 +365,12 @@ void ExifUtil::printExifEntryInfo(ExifEntry* entry, ExifData* exif_data) { } LoggerD("Entry{name:%s type:%s size:%d components:%d value:%s RAW DATA:[%s]}", - exif_tag_get_name(entry->tag), - exif_format_get_name(entry->format), - static_cast(entry->size), - static_cast(entry->components), - exif_entry_get_value(entry, buf, sizeof(buf)), - ss.str().c_str()); + exif_tag_get_name(entry->tag), exif_format_get_name(entry->format), + static_cast(entry->size), static_cast(entry->components), + exif_entry_get_value(entry, buf, sizeof(buf)), ss.str().c_str()); } -void ExifUtil::extractFromTimeT(const time_t time, - int& out_year, int& out_month, int& out_day, +void ExifUtil::extractFromTimeT(const time_t time, int& out_year, int& out_month, int& out_day, int& out_hour, int& out_min, int& out_sec) { struct tm utc; gmtime_r(&time, &utc); @@ -390,9 +383,8 @@ void ExifUtil::extractFromTimeT(const time_t time, out_sec = utc.tm_sec; } -time_t ExifUtil::convertToTimeT(int year, int month, int day, - int hour, int min, int sec) { - struct tm timeinfo = { 0 }; +time_t ExifUtil::convertToTimeT(int year, int month, int day, int hour, int min, int sec) { + struct tm timeinfo = {0}; time_t tmp_time = 0; tzset(); localtime_r(&tmp_time, &timeinfo); diff --git a/src/exif/exif_util.h b/src/exif/exif_util.h old mode 100755 new mode 100644 index 3b35f62..1dab85a --- a/src/exif/exif_util.h +++ b/src/exif/exif_util.h @@ -75,7 +75,6 @@ enum ExposureProgram { * denominator. */ struct ExifTypeInfo { - /** * Number of bytes used by each exif type */ @@ -109,12 +108,10 @@ class ExifUtil { static ImageOrientation stringToOrientation(const std::string& orientation); static const std::string& orientationToString(ImageOrientation value); - static WhiteBalanceMode stringToWhiteBalance( - const std::string& white_balance); + static WhiteBalanceMode stringToWhiteBalance(const std::string& white_balance); static const std::string& whiteBalanceToString(WhiteBalanceMode value); - static ExposureProgram stringToExposureProgram( - const std::string& exposure_program); + static ExposureProgram stringToExposureProgram(const std::string& exposure_program); static const std::string& exposureProgramToString(ExposureProgram value); static std::string convertUriToPath(const std::string& str); @@ -126,14 +123,12 @@ class ExifUtil { static std::string timeTToExifGpsDateStamp(time_t time); static std::size_t getSizeOfExifFormatType(ExifFormat format); - static void printExifEntryInfo(ExifEntry* entry, ExifData* exif_data); + static void printExifEntryInfo(ExifEntry* entry, ExifData* exif_data); - static void extractFromTimeT(const time_t time, - int& out_year, int& out_month, int& out_day, - int& out_hour, int& out_min, int& out_sec); + static void extractFromTimeT(const time_t time, int& out_year, int& out_month, int& out_day, + int& out_hour, int& out_min, int& out_sec); - static time_t convertToTimeT(int year, int month, int day, - int hour, int min, int sec); + static time_t convertToTimeT(int year, int month, int day, int hour, int min, int sec); }; } // namespace exif diff --git a/src/exif/get_exif_info.cc b/src/exif/get_exif_info.cc old mode 100755 new mode 100644 index 07758f6..0c2efe0 --- a/src/exif/get_exif_info.cc +++ b/src/exif/get_exif_info.cc @@ -21,8 +21,8 @@ #include #include -#include "common/platform_result.h" #include "common/logger.h" +#include "common/platform_result.h" #include "exif/exif_util.h" @@ -37,11 +37,9 @@ struct ExifDataHolder { JsonObject* result_obj_ptr; }; -Rational GetRationalFromEntry(ExifEntry *entry, ExifData* exif_data) { +Rational GetRationalFromEntry(ExifEntry* entry, ExifData* exif_data) { LoggerD("Entered"); - if (EXIF_FORMAT_RATIONAL == entry->format - && entry->components >= 1 - && entry->data) { + if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= 1 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); return Rational(exif_get_rational(entry->data, order)); } else { @@ -49,13 +47,10 @@ Rational GetRationalFromEntry(ExifEntry *entry, ExifData* exif_data) { } } -bool GetRationalsFromEntry(ExifEntry* entry, ExifData* exif_data, - unsigned long required_count, +bool GetRationalsFromEntry(ExifEntry* entry, ExifData* exif_data, unsigned long required_count, Rationals& out_rationals) { LoggerD("Entered"); - if (EXIF_FORMAT_RATIONAL == entry->format && - entry->components >= required_count && - entry->data) { + if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= required_count && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); unsigned char* ptr = entry->data; @@ -70,19 +65,15 @@ bool GetRationalsFromEntry(ExifEntry* entry, ExifData* exif_data, } } -bool GetGCSPositionFromEntry(ExifEntry* entry, ExifData* exif_data, - GCSPosition& out_pos) { +bool GetGCSPositionFromEntry(ExifEntry* entry, ExifData* exif_data, GCSPosition& out_pos) { // RATIONAL - 3 LoggerD("Entered"); - if (EXIF_FORMAT_RATIONAL == entry->format && - entry->components >= 3 && - entry->data) { + if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= 3 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); out_pos.degrees = Rational(exif_get_rational(entry->data, order)); - out_pos.minutes = Rational(exif_get_rational( - entry->data + ExifTypeInfo::RationalSize, order)); - out_pos.seconds = Rational(exif_get_rational( - entry->data + 2*ExifTypeInfo::RationalSize, order)); + out_pos.minutes = Rational(exif_get_rational(entry->data + ExifTypeInfo::RationalSize, order)); + out_pos.seconds = + Rational(exif_get_rational(entry->data + 2 * ExifTypeInfo::RationalSize, order)); return true; } else { return false; @@ -108,9 +99,8 @@ bool DecomposeExifUndefined(ExifEntry* entry, std::string& type, std::string& va return true; } -PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, - ExifData* exif_data, - JsonObject* result_obj) { +PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, ExifData* exif_data, + JsonObject* result_obj) { LoggerD("Entered"); char buf[2000]; exif_entry_get_value(entry, buf, sizeof(buf)); @@ -154,13 +144,12 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, case EXIF_TAG_DATE_TIME_ORIGINAL: { // ASCII - 20 exif_entry_get_value(entry, buf, sizeof(buf)); - const time_t time = ExifUtil::exifDateTimeOriginalToTimeT( - reinterpret_cast(entry->data)); + const time_t time = + ExifUtil::exifDateTimeOriginalToTimeT(reinterpret_cast(entry->data)); LoggerD("Setting ExifInformation time original to: [%s] time_t:%d", buf, - static_cast(time)); + static_cast(time)); // convert time_t (number of seconds) to string - pair = std::make_pair("originalTimeSeconds", - JsonValue(static_cast(time))); + pair = std::make_pair("originalTimeSeconds", JsonValue(static_cast(time))); result_obj->insert(pair); break; } @@ -170,51 +159,45 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, const ExifByteOrder order = exif_data_get_byte_order(exif_data); const ExifShort orient(exif_get_short(entry->data, order)); - const std::string& orientation = ExifUtil::orientationToString( - static_cast(orient)); + const std::string& orientation = + ExifUtil::orientationToString(static_cast(orient)); pair = std::make_pair("orientation", JsonValue(orientation)); result_obj->insert(pair); if (orient < EXIF_ORIENTATION_NORMAL || orient >= EXIF_ORIENTATION_NOT_VALID) { - LoggerW("Couldn't set ExifInformation - orientation is not valid: %d (%s)", - orient, buf); + LoggerW("Couldn't set ExifInformation - orientation is not valid: %d (%s)", orient, buf); } else { LoggerD("Setting ExifInformation orientation to: %d [%s]", orient, buf); } break; } - case EXIF_TAG_FNUMBER: - { + case EXIF_TAG_FNUMBER: { // RATIONAL - 1 Rational fnumber = GetRationalFromEntry(entry, exif_data); if (fnumber.isValid()) { LoggerD("Setting ExifInformation fnumber to: %f (%s)", fnumber.toDouble(), - fnumber.toString().c_str()); + fnumber.toString().c_str()); pair = std::make_pair("fNumber", JsonValue(fnumber.toDouble())); result_obj->insert(pair); } else { LoggerW("Couldn't set ExifInformation - fnumber is not valid: %s", - fnumber.toString().c_str()); + fnumber.toString().c_str()); } break; } case EXIF_TAG_ISO_SPEED_RATINGS: { // SHORT - Any - if (EXIF_FORMAT_SHORT == entry->format && - entry->components > 0 && - entry->data) { + if (EXIF_FORMAT_SHORT == entry->format && entry->components > 0 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); unsigned char* read_ptr = entry->data; - const std::size_t size_per_member = - ExifUtil::getSizeOfExifFormatType(entry->format); + const std::size_t size_per_member = ExifUtil::getSizeOfExifFormatType(entry->format); JsonArray array = JsonArray(); for (unsigned long i = 0; i < entry->components; ++i) { ExifShort iso_rating = exif_get_short(read_ptr, order); array.push_back(JsonValue(std::to_string(iso_rating))); - LoggerD("Appending ExifInformation speed ratings with: %d", - static_cast(iso_rating)); + LoggerD("Appending ExifInformation speed ratings with: %d", static_cast(iso_rating)); read_ptr += size_per_member; } @@ -222,31 +205,28 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, result_obj->insert(pair); } else { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "iso speed ratings: format or components count is invalid!"); + "iso speed ratings: format or components count is invalid!"); } break; } case EXIF_TAG_EXPOSURE_TIME: { // RATIONAL - 1 - if (EXIF_FORMAT_RATIONAL == entry->format && - entry->components > 0 && - entry->data) { + if (EXIF_FORMAT_RATIONAL == entry->format && entry->components > 0 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); const Rational exp_time(exif_get_rational(entry->data, order)); if (exp_time.isValid()) { - LoggerD("Setting ExifInformation exposure time to: %s (%s)", - exp_time.toString().c_str(), - exp_time.toExposureTimeString().c_str()); + LoggerD("Setting ExifInformation exposure time to: %s (%s)", exp_time.toString().c_str(), + exp_time.toExposureTimeString().c_str()); pair = std::make_pair("exposureTime", JsonValue(exp_time.toDouble())); result_obj->insert(pair); } else { LoggerD("Couldn't set ExifInformation - exposure time is not valid: %s", - exp_time.toString().c_str()); + exp_time.toString().c_str()); } } else { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "exposure time: format or components count is invalid!"); + "exposure time: format or components count is invalid!"); } break; } @@ -259,8 +239,7 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, if (exp_program >= EXIF_EXPOSURE_PROGRAM_NOT_VALID) { LoggerW("ExposureProgram: %d (%s) is not valid!", exp_program, buf); } else { - LoggerD("Setting ExifInformation exposure program to: %d [%s]", - exp_program, buf); + LoggerD("Setting ExifInformation exposure program to: %d [%s]", exp_program, buf); std::string exp_program_string = ExifUtil::exposureProgramToString(static_cast(exp_program)); pair = std::make_pair("exposureProgram", JsonValue(exp_program_string)); @@ -284,13 +263,13 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, // RATIONAL - 1 Rational flength = GetRationalFromEntry(entry, exif_data); if (flength.isValid()) { - LoggerD("Setting ExifInformation focal length to: %f (%s)", - flength.toDouble(), flength.toString().c_str()); + LoggerD("Setting ExifInformation focal length to: %f (%s)", flength.toDouble(), + flength.toString().c_str()); pair = std::make_pair("focalLength", JsonValue(flength.toDouble())); result_obj->insert(pair); } else { LoggerW("Couldn't set ExifInformation - focal length is not valid: %s", - flength.toString().c_str()); + flength.toString().c_str()); } break; } @@ -298,8 +277,7 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, // SHORT - 1 exif_entry_get_value(entry, buf, sizeof(buf)); LoggerD("Setting ExifInformation white balance to: [%s]", buf); - pair = std::make_pair("whiteBalanceValue", - JsonValue(static_cast(entry->data[0]))); + pair = std::make_pair("whiteBalanceValue", JsonValue(static_cast(entry->data[0]))); result_obj->insert(pair); break; } @@ -314,10 +292,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, pair = std::make_pair("gpsLongitudeSeconds", JsonValue(longitude.seconds.toDouble())); result_obj->insert(pair); LoggerD("Setting ExifInformation gps longitude to: %s; %s; %s valid:%d", - longitude.degrees.toString().c_str(), - longitude.minutes.toString().c_str(), - longitude.seconds.toString().c_str(), - longitude.isValid()); + longitude.degrees.toString().c_str(), longitude.minutes.toString().c_str(), + longitude.seconds.toString().c_str(), longitude.isValid()); } else { LoggerW("Couldn't set longitude pos - data is not valid."); } @@ -331,11 +307,11 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, } const char ref = static_cast(entry->data[0]); - if ('E' == ref || 'e' == ref) { // East + if ('E' == ref || 'e' == ref) { // East pair = std::make_pair("gpsLongitudeRef", JsonValue("EAST")); result_obj->insert(pair); LoggerD("Setting ExifInformation gps longitude REF to: EAST"); - } else if ('W' == ref || 'w' == ref) { // West + } else if ('W' == ref || 'w' == ref) { // West pair = std::make_pair("gpsLongitudeRef", JsonValue("WEST")); result_obj->insert(pair); LoggerD("Setting ExifInformation gps longitude REF to: WEST"); @@ -347,8 +323,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, case EXIF_TAG_GPS_LATITUDE: { // RATIONAL - 3 exif_entry_get_value(entry, buf, sizeof(buf)); - LoggerD("Setting ExifInformation latitude to: [%s], tag->%s", - buf, exif_tag_get_name(entry->tag) ); + LoggerD("Setting ExifInformation latitude to: [%s], tag->%s", buf, + exif_tag_get_name(entry->tag)); GCSPosition latitude; if (GetGCSPositionFromEntry(entry, exif_data, latitude)) { @@ -360,10 +336,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, result_obj->insert(pair); LoggerD("Setting ExifInformation gps latitude to: %s; %s; %s valid:%d", - latitude.degrees.toString().c_str(), - latitude.minutes.toString().c_str(), - latitude.seconds.toString().c_str(), - latitude.isValid()); + latitude.degrees.toString().c_str(), latitude.minutes.toString().c_str(), + latitude.seconds.toString().c_str(), latitude.isValid()); } else { LoggerW("Couldn't set latitude pos - data is not valid!"); } @@ -377,11 +351,11 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, } const char ref = static_cast(entry->data[0]); - if ('N' == ref || 'n' == ref) { // North + if ('N' == ref || 'n' == ref) { // North pair = std::make_pair("gpsLatitudeRef", JsonValue("NORTH")); result_obj->insert(pair); LoggerD("Setting ExifInformation gps latitude REF to: NORTH"); - } else if ('S' == ref || 's' == ref) { // South + } else if ('S' == ref || 's' == ref) { // South pair = std::make_pair("gpsLatitudeRef", JsonValue("SOUTH")); result_obj->insert(pair); LoggerD("Setting ExifInformation gps latitude REF to: SOUTH"); @@ -394,13 +368,13 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, // RATIONAL - 1 Rational gps_altitude = GetRationalFromEntry(entry, exif_data); if (gps_altitude.isValid()) { - LoggerD("Setting ExifInformation gps altitude to: %f (%s)", - gps_altitude.toDouble(), gps_altitude.toString().c_str()); + LoggerD("Setting ExifInformation gps altitude to: %f (%s)", gps_altitude.toDouble(), + gps_altitude.toString().c_str()); pair = std::make_pair("gpsAltitude", JsonValue(gps_altitude.toDouble())); result_obj->insert(pair); } else { LoggerW("Couldn't set ExifInformation - gps altitude is not valid: %s", - gps_altitude.toString().c_str()); + gps_altitude.toString().c_str()); } break; } @@ -410,8 +384,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, pair = std::make_pair("gpsAltitudeRef", JsonValue(static_cast(altitude_ref))); result_obj->insert(pair); LoggerD("Setting ExifInformation gps altitude ref to: %d (%s)", - static_cast(altitude_ref), - (altitude_ref > 0) ? "below sea level" : "above sea level"); + static_cast(altitude_ref), + (altitude_ref > 0) ? "below sea level" : "above sea level"); break; } @@ -419,8 +393,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, // UNDEFINED - Any std::string type, value; if (DecomposeExifUndefined(entry, type, value)) { - LoggerD("Extracted GPSProcessingMethod: [%s], len:%d, type:%s", - value.c_str(), value.length(), type.c_str()); + LoggerD("Extracted GPSProcessingMethod: [%s], len:%d, type:%s", value.c_str(), + value.length(), type.c_str()); pair = std::make_pair("gpsProcessingMethod", JsonValue(value)); result_obj->insert(pair); } else { @@ -454,8 +428,8 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, // UNDEFINED - Any std::string type, value; if (DecomposeExifUndefined(entry, type, value)) { - LoggerD("Extracted UserComment: [%s], len:%d, type:%s", - value.c_str(), value.length(), type.c_str()); + LoggerD("Extracted UserComment: [%s], len:%d, type:%s", value.c_str(), value.length(), + type.c_str()); pair = std::make_pair("userComment", JsonValue(value)); result_obj->insert(pair); @@ -469,7 +443,7 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, return PlatformResult(ErrorCode::NO_ERROR); } -void GetExifInfo::ContentForeachFunctionProxy(ExifEntry *entry, void *user_data) { +void GetExifInfo::ContentForeachFunctionProxy(ExifEntry* entry, void* user_data) { LoggerD("Entered"); ExifDataHolder* holder = static_cast(user_data); if (!holder) { @@ -490,19 +464,17 @@ void GetExifInfo::ContentForeachFunctionProxy(ExifEntry *entry, void *user_data) } } -void GetExifInfo::DataForeachFunction(ExifContent *content, void *user_data) { +void GetExifInfo::DataForeachFunction(ExifContent* content, void* user_data) { exif_content_foreach_entry(content, ContentForeachFunctionProxy, user_data); } -PlatformResult GetExifInfo::LoadFromURI(const std::string& uri, - JsonValue* result) { +PlatformResult GetExifInfo::LoadFromURI(const std::string& uri, JsonValue* result) { LoggerD("Entered"); const std::string& file_path = ExifUtil::convertUriToPath(uri); ExifData* ed = exif_data_new_from_file(file_path.c_str()); if (!ed) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error reading exif from file", - ("Error reading exif from file %s", file_path.c_str())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error reading exif from file", + ("Error reading exif from file %s", file_path.c_str())); } LoggerD("loadFromURI_into_json exif_data_foreach_content START"); @@ -512,8 +484,7 @@ PlatformResult GetExifInfo::LoadFromURI(const std::string& uri, ExifDataHolder holder; holder.exif_data = ed; holder.result_obj_ptr = &result_obj; - exif_data_foreach_content(ed, DataForeachFunction, - static_cast(&holder)); + exif_data_foreach_content(ed, DataForeachFunction, static_cast(&holder)); LoggerD("loadFromURI_into_json exif_data_foreach_content END"); diff --git a/src/exif/get_exif_info.h b/src/exif/get_exif_info.h old mode 100755 new mode 100644 index c14273a..3774f43 --- a/src/exif/get_exif_info.h +++ b/src/exif/get_exif_info.h @@ -38,15 +38,14 @@ extern const std::size_t EXIF_UNDEFINED_TYPE_LENGTH; class GetExifInfo { public: - static common::PlatformResult ProcessEntry(ExifEntry* entry, - ExifData* exif_data, + static common::PlatformResult ProcessEntry(ExifEntry* entry, ExifData* exif_data, JsonObject* result_obj); - static common::PlatformResult LoadFromURI(const std::string& uri, - JsonValue* result); + static common::PlatformResult LoadFromURI(const std::string& uri, JsonValue* result); private: - GetExifInfo() { } // private ctor - class can not be created + GetExifInfo() { + } // private ctor - class can not be created static void ContentForeachFunctionProxy(ExifEntry* entry, void* user_data); static void DataForeachFunction(ExifContent* content, void* user_data); diff --git a/src/exif/jpeg_file.cc b/src/exif/jpeg_file.cc old mode 100755 new mode 100644 index 65bc4f5..b46ed6e --- a/src/exif/jpeg_file.cc +++ b/src/exif/jpeg_file.cc @@ -42,8 +42,7 @@ const unsigned int MAX_JPEG_SECTION_DATA_SIZE = 65535; * JPEG's section data length includes 2 bytes for length therefore we need to * substract 2 from MAX_JPEG_SECTION_DATA_SIZE */ -const unsigned int MAX_AVAILABLE_JPEG_SECTION_DATA_SIZE = - MAX_JPEG_SECTION_DATA_SIZE - 2; +const unsigned int MAX_AVAILABLE_JPEG_SECTION_DATA_SIZE = MAX_JPEG_SECTION_DATA_SIZE - 2; bool isJpegMarker(const int value) { return value >= JPEG_MARKER_LOWEST_ID && value <= JPEG_MARKER_HIGHEST_ID; @@ -67,30 +66,31 @@ void writeUShortBE(unsigned short value, unsigned char* buffer) { } struct CArrayDeleter { - void operator()(void* buffer) { free(buffer); } + void operator()(void* buffer) { + free(buffer); + } }; -JpegFile::JpegFile() : - m_in_data(NULL), - m_in_data_size(0), - m_image_data(NULL), - m_image_size(0), - m_padding_data(NULL), - m_padding_data_size(0), - m_in_file(NULL), - m_out_file(NULL) { +JpegFile::JpegFile() + : m_in_data(NULL), + m_in_data_size(0), + m_image_data(NULL), + m_image_size(0), + m_padding_data(NULL), + m_padding_data_size(0), + m_in_file(NULL), + m_out_file(NULL) { } JpegFile::~JpegFile() { - delete [] m_in_data; + delete[] m_in_data; m_in_data = NULL; m_in_data_size = 0; m_padding_data = NULL; m_padding_data_size = 0; - for (SectionsVec::iterator it = m_sections.begin(); - it != m_sections.end(); ++it) { + for (SectionsVec::iterator it = m_sections.begin(); it != m_sections.end(); ++it) { JpegFileSectionPtr cur = *it; if (cur->exif_data) { @@ -122,7 +122,7 @@ PlatformResult JpegFile::loadFile(const std::string& path, JpegFilePtr* jpg_ptr) JpegFile* new_jpg = new (std::nothrow) JpegFile(); if (!new_jpg) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed", - ("Couldn't allocate Jpegfile!")); + ("Couldn't allocate Jpegfile!")); } jpg_ptr->reset(new_jpg); @@ -151,7 +151,7 @@ PlatformResult JpegFile::load(const std::string& path) { long ftell_val = ftell(m_in_file); if (0 > ftell_val) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", - ("Input file [%s] access error! [%d]", path.c_str(), errno)); + ("Input file [%s] access error! [%d]", path.c_str(), errno)); } const std::size_t in_file_size = static_cast(ftell_val); @@ -172,8 +172,9 @@ PlatformResult JpegFile::load(const std::string& path) { const std::size_t read_bytes = fread(m_in_data, 1, m_in_data_size, m_in_file); if (read_bytes != m_in_data_size) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not read JPEG file", - ("Couldn't read all: %d bytes. Read only: %d bytes!", m_in_data_size, read_bytes)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not read JPEG file", + ("Couldn't read all: %d bytes. Read only: %d bytes!", m_in_data_size, read_bytes)); } if (fclose(m_in_file) == EOF) { @@ -184,8 +185,7 @@ PlatformResult JpegFile::load(const std::string& path) { return generateListOfSections(); } -std::string JpegFile::getPartOfFile(const std::size_t offset, - const std::size_t num_bytes_before, +std::string JpegFile::getPartOfFile(const std::size_t offset, const std::size_t num_bytes_before, const std::size_t num_bytes_after) { LoggerD("Entered"); auto start = offset - num_bytes_before; @@ -206,7 +206,6 @@ std::string JpegFile::getPartOfFile(const std::size_t offset, return ss.str(); } - common::PlatformResult JpegFile::generateListOfSections() { LoggerD("Entered"); @@ -230,8 +229,7 @@ common::PlatformResult JpegFile::generateListOfSections() { m_padding_data = NULL; m_padding_data_size = 0; - for (size_t offset = 0, iterration = 0; - offset < m_in_data_size; ++iterration) { + for (size_t offset = 0, iterration = 0; offset < m_in_data_size; ++iterration) { LoggerD("offset:%d | Starting iteration: %d", offset, iterration); const std::size_t search_len = 10; std::size_t search_offset = 0; @@ -245,7 +243,8 @@ common::PlatformResult JpegFile::generateListOfSections() { if (search_len == search_offset) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", - ("offset:%d | Couldn't find marker! RAW DATA:{%s}", offset, getPartOfFile(offset, 0, 10).c_str())); + ("offset:%d | Couldn't find marker! RAW DATA:{%s}", offset, + getPartOfFile(offset, 0, 10).c_str())); } const std::size_t section_offset = offset + search_offset - 1; @@ -257,13 +256,12 @@ common::PlatformResult JpegFile::generateListOfSections() { if (!isJpegMarker(section_begin[1])) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", ("offset:%d | Is not valid marker: 0x%x RAW DATA:{%s}", offset, - section_begin[1], getPartOfFile(section_offset, 0, 4).c_str())); + section_begin[1], getPartOfFile(section_offset, 0, 4).c_str())); } const JpegMarker cur_marker = castToJpegMarker(section_begin[1]); - LoggerD("offset:%d | Found valid marker: 0x%x RAW DATA:{%s}", offset, - cur_marker, - getPartOfFile(section_offset, 0, 4).c_str()); + LoggerD("offset:%d | Found valid marker: 0x%x RAW DATA:{%s}", offset, cur_marker, + getPartOfFile(section_offset, 0, 4).c_str()); offset += 2; // Read 0xffxx marker tag - 2 bytes @@ -272,7 +270,7 @@ common::PlatformResult JpegFile::generateListOfSections() { JpegFileSection* sec = new (std::nothrow) JpegFileSection(); if (!sec) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed", - ("Couldn't allocate JpegFileSection")); + ("Couldn't allocate JpegFileSection")); } section = JpegFileSectionPtr(sec); @@ -280,14 +278,13 @@ common::PlatformResult JpegFile::generateListOfSections() { section->type = cur_marker; m_sections.push_back(section); - if (cur_marker == JPEG_MARKER_SOI || - cur_marker == JPEG_MARKER_EOI) { - LoggerD("offset:%d | Found: %s marker, moving to next marker at:%d", - section_offset, ((cur_marker == JPEG_MARKER_SOI) ? "SOI" : "EOI"), - offset); + if (cur_marker == JPEG_MARKER_SOI || cur_marker == JPEG_MARKER_EOI) { + LoggerD("offset:%d | Found: %s marker, moving to next marker at:%d", section_offset, + ((cur_marker == JPEG_MARKER_SOI) ? "SOI" : "EOI"), offset); if (cur_marker == JPEG_MARKER_EOI && m_padding_data != NULL) { - LoggerW("Padding data have been found" + LoggerW( + "Padding data have been found" " - do not try to parse end of file"); break; } @@ -309,39 +306,36 @@ common::PlatformResult JpegFile::generateListOfSections() { // size 2 bytes const long section_data_len = total_section_len - 2; - LoggerD("offset:%d tag:0x%x | Read total_section_len:%d (data len:%d)", - section_offset, cur_marker, total_section_len, section_data_len); + LoggerD("offset:%d tag:0x%x | Read total_section_len:%d (data len:%d)", section_offset, + cur_marker, total_section_len, section_data_len); offset += 2; // Read data size - 2 bytes if (total_section_len < 0) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", ("offset:%d tag:0x%x | Error: total_section_len is: %d < 0", - offset, cur_marker, total_section_len)); + offset, cur_marker, total_section_len)); } if (section_offset + 2 + total_section_len > m_in_data_size) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", ("offset:%d tag:0x%x | Error: current section offset:%d" - " + 2 + total_section_len:%d = %d is greater then file size:%d", - offset, cur_marker, - section_offset, total_section_len, - section_offset + total_section_len, m_in_data_size)); + " + 2 + total_section_len:%d = %d is greater then file size:%d", + offset, cur_marker, section_offset, total_section_len, + section_offset + total_section_len, m_in_data_size)); } if (JPEG_MARKER_APP1 == cur_marker) { const unsigned int exif_data_size = total_section_len + 2; - section->exif_data = exif_data_new_from_data(section_begin, - exif_data_size); + section->exif_data = exif_data_new_from_data(section_begin, exif_data_size); - LoggerD("offset:%d tag:0x%x | Loading exif from offset:%d" + LoggerD( + "offset:%d tag:0x%x | Loading exif from offset:%d" " len:%d exif_data_new_from_data returned: %p", - offset, cur_marker, section_offset, exif_data_size, - section->exif_data); + offset, cur_marker, section_offset, exif_data_size, section->exif_data); if (!section->exif_data) { - LoggerW("offset:%d tag:0x%x | Couldn't load Exif!", - offset, cur_marker); + LoggerW("offset:%d tag:0x%x | Couldn't load Exif!", offset, cur_marker); } } @@ -360,17 +354,20 @@ common::PlatformResult JpegFile::generateListOfSections() { // // -2 (exclude ending EOI marker (2 bytes) std::size_t image_size = m_in_data_size - image_data_offset - 2; - LoggerW("offset:%d tag:0x%x" + LoggerW( + "offset:%d tag:0x%x" " | Image data offset:%d Estimated image size:%d", offset, cur_marker, image_data_offset, image_size); m_image_data = m_in_data + image_data_offset; std::size_t eoi_tag_index = 0; - bool found_eoi_tag = searchForTagInBuffer(m_in_data + image_data_offset, - m_in_data + m_in_data_size, JPEG_MARKER_EOI, eoi_tag_index); + bool found_eoi_tag = + searchForTagInBuffer(m_in_data + image_data_offset, m_in_data + m_in_data_size, + JPEG_MARKER_EOI, eoi_tag_index); if (!found_eoi_tag) { - LoggerE("Could not find EOI tag!" + LoggerE( + "Could not find EOI tag!" " Assume that there is no EOI and rest of " "JPEG file contains image data stream: image_size+= 2"); image_size += 2; // Skip expected EOI tag which is not present @@ -378,29 +375,28 @@ common::PlatformResult JpegFile::generateListOfSections() { LoggerD("EOI tag found at offset: %d from SOS data", eoi_tag_index); if (eoi_tag_index != image_size) { - LoggerW("Estimated image size:%d doesn't match EOI tag index:%d" - " delta:%d", image_size, eoi_tag_index, - image_size - eoi_tag_index); + LoggerW( + "Estimated image size:%d doesn't match EOI tag index:%d" + " delta:%d", + image_size, eoi_tag_index, image_size - eoi_tag_index); LoggerW("Setting image_size to EOI tag: %d", eoi_tag_index); image_size = eoi_tag_index; m_padding_data = m_image_data + image_size + 2; // (skip EOI tag) m_padding_data_size = (m_in_data + m_in_data_size) - m_padding_data; - LoggerW("Saving padding data from offset:%d with size:%d", - m_padding_data - m_in_data, m_padding_data_size); + LoggerW("Saving padding data from offset:%d with size:%d", m_padding_data - m_in_data, + m_padding_data_size); } } m_image_size = image_size; offset = image_data_offset + image_size; - LoggerD("offset:%d tag:0x%x | SOS Offset moved to next marker", offset, - cur_marker); + LoggerD("offset:%d tag:0x%x | SOS Offset moved to next marker", offset, cur_marker); } else { offset += section_data_len; - LoggerD("offset:%d tag:0x%x | Offset moved to next marker", - offset, cur_marker); + LoggerD("offset:%d tag:0x%x | Offset moved to next marker", offset, cur_marker); } } } @@ -409,11 +405,9 @@ common::PlatformResult JpegFile::generateListOfSections() { } bool JpegFile::searchForTagInBuffer(const unsigned char* buffer_start, - const unsigned char* buffer_end, - const JpegMarker marker, - std::size_t& out_index) { - LoggerD("Entered start:%p end:%p marker:0x%x", - buffer_start, buffer_end, marker); + const unsigned char* buffer_end, const JpegMarker marker, + std::size_t& out_index) { + LoggerD("Entered start:%p end:%p marker:0x%x", buffer_start, buffer_end, marker); if (!buffer_start) { LoggerE("buffer_start is NULL"); @@ -434,8 +428,8 @@ bool JpegFile::searchForTagInBuffer(const unsigned char* buffer_start, const unsigned char marker_uchar = static_cast(marker); for (const unsigned char* ptr = buffer_start; ptr < buffer_end; ++ptr) { - if ((0xff == *ptr) && (ptr+1 < buffer_end)) { - if (marker_uchar == *(ptr+1)) { + if ((0xff == *ptr) && (ptr + 1 < buffer_end)) { + if (marker_uchar == *(ptr + 1)) { out_index = static_cast(ptr - buffer_start); return true; } @@ -456,9 +450,8 @@ PlatformResult JpegFile::setNewExifData(ExifData* new_exif_data) { { JpegFileSection* new_sec = new (std::nothrow) JpegFileSection(); if (!new_sec) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Memory allocation failed", - ("Couldn't allocate JpegFileSection")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed", + ("Couldn't allocate JpegFileSection")); } new_sec->type = JPEG_MARKER_APP1; @@ -478,7 +471,7 @@ PlatformResult JpegFile::setNewExifData(ExifData* new_exif_data) { if (!soi_is_present) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "JPEG file is invalid", - ("SOI section is missing")); + ("SOI section is missing")); } // Insert new Exif sections just after SOI @@ -517,13 +510,12 @@ PlatformResult JpegFile::saveToFile(const std::string& out_path) { LoggerD("Entered out_path:%s", out_path.c_str()); PlatformResult status = saveToFilePriv(out_path); - if (status) - return status; + if (status) return status; - LoggerE("Exception occured during saveToFilePriv " + LoggerE( + "Exception occured during saveToFilePriv " "original file: [%] new: [%s]", - m_source_file_path.c_str(), - out_path.c_str()); + m_source_file_path.c_str(), out_path.c_str()); if (out_path == m_source_file_path) { LoggerD("Trying to recover broken JPEG file: [%s]", out_path.c_str()); @@ -532,21 +524,20 @@ PlatformResult JpegFile::saveToFile(const std::string& out_path) { FILE* outf = fopen(out_path.c_str(), "wb"); if (!outf) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Couldn't open output file", - ("Couldn't open output file:" - " [%s] - JPEG file will not be restored!", out_path.c_str())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Couldn't open output file", + ("Couldn't open output file:" + " [%s] - JPEG file will not be restored!", + out_path.c_str())); } std::size_t bytes_wrote = fwrite(m_in_data, 1, m_in_data_size, outf); if (bytes_wrote != m_in_data_size) { fclose(outf); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Couldn't restore whole file", - ("Couldn't restore whole JPEG! " - "Only %d of %d bytes have been wrote!", - bytes_wrote, m_in_data_size)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Couldn't restore whole file", + ("Couldn't restore whole JPEG! " + "Only %d of %d bytes have been wrote!", + bytes_wrote, m_in_data_size)); } if (EOF == fclose(outf)) { LoggerE("Couldn't close restore output file: [%s]", out_path.c_str()); @@ -571,14 +562,12 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { std::size_t offset = 0; int section_index = 0; - for (SectionsVec::iterator it = m_sections.begin(); - it != m_sections.end(); - ++it, ++section_index) { + for (SectionsVec::iterator it = m_sections.begin(); it != m_sections.end(); + ++it, ++section_index) { JpegFileSectionPtr cur = *it; const JpegMarker cur_marker = cur->type; - LoggerD("offset:%d | Section: %d marker 0x%x", - offset, section_index, cur_marker); + LoggerD("offset:%d | Section: %d marker 0x%x", offset, section_index, cur_marker); std::size_t bytes_to_write = 0; std::size_t bytes_wrote = 0; @@ -593,19 +582,16 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { std::unique_ptr exif_output_data; unsigned int exif_output_size = 0; - if (cur_marker != JPEG_MARKER_SOI && - cur_marker != JPEG_MARKER_EOI) { + if (cur_marker != JPEG_MARKER_SOI && cur_marker != JPEG_MARKER_EOI) { unsigned short section_size = 2; if (JPEG_MARKER_APP1 && cur->exif_data) { unsigned char* tmp = NULL; exif_data_save_data(cur->exif_data, &tmp, &exif_output_size); if (!tmp || 0 == exif_output_size) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not save Exif in JPEG file"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not save Exif in JPEG file"); } - LoggerD("offset:%d | Generated Exif RAW Data length:%d", offset, - exif_output_size); + LoggerD("offset:%d | Generated Exif RAW Data length:%d", offset, exif_output_size); exif_output_data.reset(tmp); @@ -613,8 +599,8 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Exif data is to big to be saved in JPEG file", ("exif_output_size:%d is greater then maximum JPEG section" - "data block size: %d", exif_output_size, - MAX_AVAILABLE_JPEG_SECTION_DATA_SIZE)); + "data block size: %d", + exif_output_size, MAX_AVAILABLE_JPEG_SECTION_DATA_SIZE)); } section_size += exif_output_size; write_exif_data = true; @@ -627,17 +613,18 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { bytes_to_write += 2; } - LoggerD("offset:%d | Writing section:" - " marker:0x%x size:%d", offset, cur_marker, cur->size); + LoggerD( + "offset:%d | Writing section:" + " marker:0x%x size:%d", + offset, cur_marker, cur->size); bytes_wrote = fwrite(tmp_buf, 1, bytes_to_write, m_out_file); offset += bytes_wrote; if (bytes_wrote != bytes_to_write) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not write JPEG file", - ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, - bytes_wrote)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not write JPEG file", + ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, bytes_wrote)); } if (write_section_data && cur->size > 0) { @@ -648,57 +635,49 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { offset += bytes_wrote; if (bytes_wrote != bytes_to_write) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not write JPEG file", - ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, - bytes_wrote)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not write JPEG file", + ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, bytes_wrote)); } } if (write_exif_data && exif_output_data && exif_output_size > 0) { - LoggerD("offset:%d | Writing new exif data with length:%d", offset, - exif_output_size); + LoggerD("offset:%d | Writing new exif data with length:%d", offset, exif_output_size); bytes_to_write = exif_output_size; - bytes_wrote = fwrite(exif_output_data.get(), 1, bytes_to_write, - m_out_file); + bytes_wrote = fwrite(exif_output_data.get(), 1, bytes_to_write, m_out_file); offset += bytes_wrote; if (bytes_wrote != bytes_to_write) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not write JPEG file", - ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, - bytes_wrote)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not write JPEG file", + ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, bytes_wrote)); } } if (JPEG_MARKER_SOS == cur_marker) { - LoggerD("offset:%d | Writing image data stream with lenght:%d", offset, - m_image_size); + LoggerD("offset:%d | Writing image data stream with lenght:%d", offset, m_image_size); bytes_to_write = m_image_size; bytes_wrote = fwrite(m_image_data, 1, bytes_to_write, m_out_file); offset += bytes_wrote; if (bytes_wrote != bytes_to_write) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not write JPEG file", - ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, - bytes_wrote)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not write JPEG file", + ("Couldn't wrote %d bytes! Only %d bytes wrote", bytes_to_write, bytes_wrote)); } } } if (m_padding_data && m_padding_data_size > 0) { LoggerD("Padding data exists and contains:%d bytes saving to JPEG file"); - const std::size_t bytes_wrote = fwrite(m_image_data, 1, m_padding_data_size, - m_out_file); + const std::size_t bytes_wrote = fwrite(m_image_data, 1, m_padding_data_size, m_out_file); if (bytes_wrote != m_padding_data_size) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not write JPEG file", - ("Couldn't wrote %d bytes! Only %d bytes wrote", - m_padding_data_size, bytes_wrote)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Could not write JPEG file", + ("Couldn't wrote %d bytes! Only %d bytes wrote", m_padding_data_size, bytes_wrote)); } } @@ -716,13 +695,13 @@ JpegFileSectionPtr JpegFile::getExifSection() { std::size_t num_exif_sections = 0; JpegFileSectionPtr first_exif_section; - for (SectionsVec::iterator it = m_sections.begin(); - it != m_sections.end(); ++it) { + for (SectionsVec::iterator it = m_sections.begin(); it != m_sections.end(); ++it) { JpegFileSectionPtr cur = *it; if (JPEG_MARKER_APP1 == cur->type) { if (!cur->exif_data) { - LoggerW("Warning: found APP1 section but exif_data is NULL" + LoggerW( + "Warning: found APP1 section but exif_data is NULL" " (Not Exif?)"); continue; } @@ -731,7 +710,8 @@ JpegFileSectionPtr JpegFile::getExifSection() { if (!first_exif_section) { first_exif_section = cur; } else { - LoggerW("Warning: found %d APP1/Exif sections -" + LoggerW( + "Warning: found %d APP1/Exif sections -" " only first is currently supported!"); } } diff --git a/src/exif/jpeg_file.h b/src/exif/jpeg_file.h old mode 100755 new mode 100644 index 49554c1..19d46c3 --- a/src/exif/jpeg_file.h +++ b/src/exif/jpeg_file.h @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include #include @@ -32,25 +32,22 @@ namespace extension { namespace exif { -enum JpegMarker{ - JPEG_MARKER_UNKNOWN = 0x00, - JPEG_MARKER_LOWEST_ID = 0xc0, - JPEG_MARKER_SOI = 0xd8, // Start Of Image - JPEG_MARKER_EOI = 0xd9, // End Of Image - JPEG_MARKER_SOS = 0xda, // Start Of Stream - JPEG_MARKER_APP1 = 0xe1, // Application Data 1 - for Exif - JPEG_MARKER_HIGHEST_ID = 0xfe +enum JpegMarker { + JPEG_MARKER_UNKNOWN = 0x00, + JPEG_MARKER_LOWEST_ID = 0xc0, + JPEG_MARKER_SOI = 0xd8, // Start Of Image + JPEG_MARKER_EOI = 0xd9, // End Of Image + JPEG_MARKER_SOS = 0xda, // Start Of Stream + JPEG_MARKER_APP1 = 0xe1, // Application Data 1 - for Exif + JPEG_MARKER_HIGHEST_ID = 0xfe }; struct JpegFileSection; typedef std::shared_ptr JpegFileSectionPtr; struct JpegFileSection { - JpegFileSection() : - type(JPEG_MARKER_UNKNOWN), - data_ptr(NULL), - size(0), - exif_data(NULL) {} + JpegFileSection() : type(JPEG_MARKER_UNKNOWN), data_ptr(NULL), size(0), exif_data(NULL) { + } JpegMarker type; unsigned char* data_ptr; @@ -59,14 +56,12 @@ struct JpegFileSection { ExifData* exif_data; }; - class JpegFile; typedef std::shared_ptr JpegFilePtr; class JpegFile { public: - static common::PlatformResult loadFile(const std::string& path, - JpegFilePtr* jpg_ptr); + static common::PlatformResult loadFile(const std::string& path, JpegFilePtr* jpg_ptr); ~JpegFile(); common::PlatformResult setNewExifData(ExifData* new_exif_data); @@ -86,21 +81,20 @@ class JpegFile { private: JpegFile(); - //not copyable, not assignable + // not copyable, not assignable JpegFile(JpegFile const&) = delete; JpegFile& operator=(JpegFile const&) = delete; - common::PlatformResult load(const std::string &path); + common::PlatformResult load(const std::string& path); common::PlatformResult generateListOfSections(); - std::string getPartOfFile(const std::size_t offset, - const std::size_t num_bytes_before = 10, + std::string getPartOfFile(const std::size_t offset, const std::size_t num_bytes_before = 10, const std::size_t num_bytes_after = 10); JpegFileSectionPtr getExifSection(); - common::PlatformResult saveToFilePriv(const std::string &out_path); + common::PlatformResult saveToFilePriv(const std::string& out_path); /** * Search for first occurrence of specific tag inside buffer. @@ -111,9 +105,8 @@ class JpegFile { * For example EOI - search for first 'ffd9' in buffer */ static bool searchForTagInBuffer(const unsigned char* buffer_start, - const unsigned char* buffer_end, - const JpegMarker marker, - std::size_t& out_index); + const unsigned char* buffer_end, const JpegMarker marker, + std::size_t& out_index); std::string m_source_file_path; diff --git a/src/exif/rational.cc b/src/exif/rational.cc old mode 100755 new mode 100644 index 3aaaf91..2df6970 --- a/src/exif/rational.cc +++ b/src/exif/rational.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "exif/rational.h" #include @@ -30,19 +30,14 @@ namespace { const double DOUBLE_ERROR_REPRESENTATION = static_cast(0x7FFFFFFF); } // namespace -Rational::Rational() : - nominator(0), - denominator(0) { +Rational::Rational() : nominator(0), denominator(0) { } -Rational::Rational(ExifLong nom, ExifLong denom) : - nominator(nom), - denominator(denom) { +Rational::Rational(ExifLong nom, ExifLong denom) : nominator(nom), denominator(denom) { } -Rational::Rational(const ExifRational& exif_rational) : - nominator(exif_rational.numerator), - denominator(exif_rational.denominator) { +Rational::Rational(const ExifRational& exif_rational) + : nominator(exif_rational.numerator), denominator(exif_rational.denominator) { } Rational Rational::createFromDouble(const double value, const long precision) { @@ -83,7 +78,7 @@ Rational Rational::createFromDouble(const double value, const long precision) { m[1][0] = t; if (x == static_cast(ai)) { - break; // AF: division by zero + break; // AF: division by zero } x = 1 / (x - static_cast(ai)); @@ -95,8 +90,7 @@ Rational Rational::createFromDouble(const double value, const long precision) { // now remaining x is between 0 and 1/ai // approx as either 0 or 1/m where m is max that will fit in precision // first try zero - const double error0 = - startx - (static_cast(m[0][0]) / static_cast(m[1][0])); + const double error0 = startx - (static_cast(m[0][0]) / static_cast(m[1][0])); const long numerator0 = m[0][0]; const long denominator0 = m[1][0]; @@ -107,8 +101,7 @@ Rational Rational::createFromDouble(const double value, const long precision) { m[0][0] = m[0][0] * ai + m[0][1]; m[1][0] = m[1][0] * ai + m[1][1]; - double error1m = startx - - (static_cast(m[0][0]) / static_cast(m[1][0])); + double error1m = startx - (static_cast(m[0][0]) / static_cast(m[1][0])); LoggerD("%ld/%ld, error = %e\n", m[0][0], m[1][0], error1m); long result_numerator = 0; @@ -129,8 +122,8 @@ Rational Rational::createFromDouble(const double value, const long precision) { result_denominator *= -1; } - LoggerD("Rational(%d, %d) error0 < error1m:%d", - result_numerator, result_denominator, error0 < error1m); + LoggerD("Rational(%d, %d) error0 < error1m:%d", result_numerator, result_denominator, + error0 < error1m); return Rational(numerator0, denominator0); } @@ -182,8 +175,7 @@ Rational Rational::createFromExposureTimeString(const std::string& exp_time) { if (first_slash_at > 0) { if (first_space_at > 0) { integer_part = exp_time.substr(0, first_space_at); - fraction_part = exp_time.substr(first_space_at + 1, - exp_time.size() - (first_space_at + 1)); + fraction_part = exp_time.substr(first_space_at + 1, exp_time.size() - (first_space_at + 1)); } else { fraction_part = exp_time; } @@ -191,9 +183,8 @@ Rational Rational::createFromExposureTimeString(const std::string& exp_time) { integer_part = exp_time; } - LoggerD("first_space_at: %d first_slash_at:%d int: [%s] , frac: [%s]", - first_space_at, first_slash_at, - integer_part.c_str(), fraction_part.c_str()); + LoggerD("first_space_at: %d first_slash_at:%d int: [%s] , frac: [%s]", first_space_at, + first_slash_at, integer_part.c_str(), fraction_part.c_str()); long integer_value = 0; long nominator = 0; @@ -204,17 +195,14 @@ Rational Rational::createFromExposureTimeString(const std::string& exp_time) { } if (fraction_part.length() > 0) { - if (sscanf( - fraction_part.c_str(), "%5ld/%5ld", &nominator, &denominator) != 2) { - LoggerD("Failed to parse nominator/denominator string: [%s]", - fraction_part.c_str()); + if (sscanf(fraction_part.c_str(), "%5ld/%5ld", &nominator, &denominator) != 2) { + LoggerD("Failed to parse nominator/denominator string: [%s]", fraction_part.c_str()); return Rational::createInvalid(); } } nominator += denominator * integer_value; - LoggerD("%d/%d -> %f", - nominator, denominator, static_cast(nominator) / denominator); + LoggerD("%d/%d -> %f", nominator, denominator, static_cast(nominator) / denominator); if (0 == nominator) { // Exposure time = 0 is invalid value diff --git a/src/exif/rational.h b/src/exif/rational.h old mode 100755 new mode 100644 index a88c51d..ac50ffb --- a/src/exif/rational.h +++ b/src/exif/rational.h @@ -17,13 +17,13 @@ #ifndef EXIF_EXIF_RATIONAL_H_ #define EXIF_EXIF_RATIONAL_H_ -#include -#include #include +#include +#include +#include #include #include -#include namespace extension { namespace exif { @@ -47,8 +47,7 @@ class Rational { Rational(ExifLong nom, ExifLong denom); explicit Rational(const ExifRational& exif_rational); - static Rational createFromDouble(const double value, - const long precision = 1000); + static Rational createFromDouble(const double value, const long precision = 1000); static Rational createInvalid(); /** diff --git a/src/feedback/feedback_extension.cc b/src/feedback/feedback_extension.cc old mode 100755 new mode 100644 index 7e686ea..a351c6e --- a/src/feedback/feedback_extension.cc +++ b/src/feedback/feedback_extension.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "feedback/feedback_extension.h" #include "feedback/feedback_instance.h" @@ -30,7 +30,8 @@ FeedbackExtension::FeedbackExtension() { SetJavaScriptAPI(kSource_feedback_api); } -FeedbackExtension::~FeedbackExtension() {} +FeedbackExtension::~FeedbackExtension() { +} common::Instance* FeedbackExtension::CreateInstance() { return new extension::feedback::FeedbackInstance; diff --git a/src/feedback/feedback_instance.cc b/src/feedback/feedback_instance.cc old mode 100755 new mode 100644 index ee04359..fe5719b --- a/src/feedback/feedback_instance.cc +++ b/src/feedback/feedback_instance.cc @@ -20,9 +20,9 @@ #include #include -#include "common/picojson.h" #include "common/logger.h" #include "common/picojson.h" +#include "common/picojson.h" #include "common/platform_exception.h" #include "common/platform_result.h" #include "common/tools.h" @@ -40,40 +40,33 @@ using common::QuotaExceededException; namespace { const std::string kPrivilegeHaptic = "http://tizen.org/privilege/haptic"; -} //namespace +} // namespace FeedbackInstance::FeedbackInstance() : m_feedbackMapsPtr(new FeedbackMaps), - m_feedbackManagerPtr(new FeedbackManager(this->m_feedbackMapsPtr)) - { + m_feedbackManagerPtr(new FeedbackManager(this->m_feedbackMapsPtr)) { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&FeedbackInstance::x, this, _1, _2)); - REGISTER_SYNC("FeedbackManager_isPatternSupported", - IsPatternSupported); - REGISTER_SYNC("FeedbackManager_play", - Play); - REGISTER_SYNC("FeedbackManager_stop", - Stop); - #undef REGISTER_SYNC +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&FeedbackInstance::x, this, _1, _2)); + REGISTER_SYNC("FeedbackManager_isPatternSupported", IsPatternSupported); + REGISTER_SYNC("FeedbackManager_play", Play); + REGISTER_SYNC("FeedbackManager_stop", Stop); +#undef REGISTER_SYNC } FeedbackInstance::~FeedbackInstance() { LoggerD("Enter"); } -void FeedbackInstance::IsPatternSupported - (const picojson::value& args, picojson::object& out) { +void FeedbackInstance::IsPatternSupported(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const auto pattern = args.get("pattern").get(); const auto type = args.get("type").get(); bool patternStatus = false; - PlatformResult result = - m_feedbackManagerPtr->isPatternSupported(pattern, type, &patternStatus); + PlatformResult result = m_feedbackManagerPtr->isPatternSupported(pattern, type, &patternStatus); if (result.IsSuccess()) { ReportSuccess(picojson::value(patternStatus), out); } else { @@ -81,8 +74,7 @@ void FeedbackInstance::IsPatternSupported } } -void FeedbackInstance::Play - (const picojson::value& args, picojson::object& out) { +void FeedbackInstance::Play(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeHaptic, &out); @@ -90,8 +82,7 @@ void FeedbackInstance::Play const auto pattern = args.get("pattern").get(); const auto type = args.get("type").get(); - PlatformResult result = - m_feedbackManagerPtr->play(pattern, type); + PlatformResult result = m_feedbackManagerPtr->play(pattern, type); if (result.IsSuccess()) { ReportSuccess(out); } else { @@ -99,14 +90,12 @@ void FeedbackInstance::Play } } -void FeedbackInstance::Stop - (const picojson::value& args, picojson::object& out) { +void FeedbackInstance::Stop(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeHaptic, &out); - PlatformResult result = - m_feedbackManagerPtr->stop(); + PlatformResult result = m_feedbackManagerPtr->stop(); if (result.IsSuccess()) { ReportSuccess(out); } else { diff --git a/src/feedback/feedback_instance.h b/src/feedback/feedback_instance.h old mode 100755 new mode 100644 index 98f4bda..1978e2d --- a/src/feedback/feedback_instance.h +++ b/src/feedback/feedback_instance.h @@ -17,8 +17,8 @@ #ifndef FEEDBACK_FEEDBACK_INSTANCE_H_ #define FEEDBACK_FEEDBACK_INSTANCE_H_ -#include "common/extension.h" #include +#include "common/extension.h" namespace extension { namespace feedback { @@ -34,12 +34,9 @@ class FeedbackInstance : public common::ParsedInstance { private: std::shared_ptr m_feedbackMapsPtr; std::unique_ptr m_feedbackManagerPtr; - void IsPatternSupported - (const picojson::value& args, picojson::object& out); - void Play - (const picojson::value& args, picojson::object& out); - void Stop - (const picojson::value& args, picojson::object& out); + void IsPatternSupported(const picojson::value& args, picojson::object& out); + void Play(const picojson::value& args, picojson::object& out); + void Stop(const picojson::value& args, picojson::object& out); }; } // namespace feedback diff --git a/src/feedback/feedback_manager.cc b/src/feedback/feedback_manager.cc index 57f3e0c..cc5da3d 100644 --- a/src/feedback/feedback_manager.cc +++ b/src/feedback/feedback_manager.cc @@ -14,15 +14,15 @@ * limitations under the License. */ -#include #include +#include #include "common/assert.h" #include "common/converter.h" #include "common/extension.h" #include "common/logger.h" -#include "common/platform_exception.h" #include "common/picojson.h" +#include "common/platform_exception.h" #include "common/platform_result.h" #include "common/tools.h" @@ -33,62 +33,56 @@ using common::tools::ReportError; namespace extension { namespace feedback { -FeedbackMaps::FeedbackMaps() : - mTypeMap{ - {"TYPE_SOUND", FEEDBACK_TYPE_SOUND}, - {"TYPE_VIBRATION", FEEDBACK_TYPE_VIBRATION} - }, - mPatternMap{ - {"TAP", FEEDBACK_PATTERN_TAP}, - {"SIP", FEEDBACK_PATTERN_SIP}, - {"KEY0", FEEDBACK_PATTERN_KEY0}, - {"KEY1", FEEDBACK_PATTERN_KEY1}, - {"KEY2", FEEDBACK_PATTERN_KEY2}, - {"KEY3", FEEDBACK_PATTERN_KEY3}, - {"KEY4", FEEDBACK_PATTERN_KEY4}, - {"KEY5", FEEDBACK_PATTERN_KEY5}, - {"KEY6", FEEDBACK_PATTERN_KEY6}, - {"KEY7", FEEDBACK_PATTERN_KEY7}, - {"KEY8", FEEDBACK_PATTERN_KEY8}, - {"KEY9", FEEDBACK_PATTERN_KEY9}, - {"KEY_STAR", FEEDBACK_PATTERN_KEY_STAR}, - {"KEY_SHARP", FEEDBACK_PATTERN_KEY_SHARP}, - {"KEY_BACK", FEEDBACK_PATTERN_KEY_BACK}, - {"HOLD", FEEDBACK_PATTERN_HOLD}, - {"HW_TAP", FEEDBACK_PATTERN_HW_TAP}, - {"HW_HOLD", FEEDBACK_PATTERN_HW_HOLD}, - {"MESSAGE", FEEDBACK_PATTERN_MESSAGE}, - {"EMAIL", FEEDBACK_PATTERN_EMAIL}, - {"WAKEUP", FEEDBACK_PATTERN_WAKEUP}, - {"SCHEDULE", FEEDBACK_PATTERN_SCHEDULE}, - {"TIMER", FEEDBACK_PATTERN_TIMER}, - {"GENERAL", FEEDBACK_PATTERN_GENERAL}, - {"POWERON", FEEDBACK_PATTERN_POWERON}, - {"POWEROFF", FEEDBACK_PATTERN_POWEROFF}, - {"CHARGERCONN", FEEDBACK_PATTERN_CHARGERCONN}, - {"CHARGING_ERROR", FEEDBACK_PATTERN_CHARGING_ERROR}, - {"FULLCHARGED", FEEDBACK_PATTERN_FULLCHARGED}, - {"LOWBATT", FEEDBACK_PATTERN_LOWBATT}, - {"LOCK", FEEDBACK_PATTERN_LOCK}, - {"UNLOCK", FEEDBACK_PATTERN_UNLOCK}, - {"VIBRATION_ON", FEEDBACK_PATTERN_VIBRATION_ON}, - {"SILENT_OFF", FEEDBACK_PATTERN_SILENT_OFF}, - {"BT_CONNECTED", FEEDBACK_PATTERN_BT_CONNECTED}, - {"BT_DISCONNECTED", FEEDBACK_PATTERN_BT_DISCONNECTED}, - {"LIST_REORDER", FEEDBACK_PATTERN_LIST_REORDER}, - {"LIST_SLIDER", FEEDBACK_PATTERN_LIST_SLIDER}, - {"VOLUME_KEY", FEEDBACK_PATTERN_VOLUME_KEY} - } -{}; - -FeedbackMaps::~FeedbackMaps() -{} +FeedbackMaps::FeedbackMaps() + : mTypeMap{{"TYPE_SOUND", FEEDBACK_TYPE_SOUND}, {"TYPE_VIBRATION", FEEDBACK_TYPE_VIBRATION}}, + mPatternMap{{"TAP", FEEDBACK_PATTERN_TAP}, + {"SIP", FEEDBACK_PATTERN_SIP}, + {"KEY0", FEEDBACK_PATTERN_KEY0}, + {"KEY1", FEEDBACK_PATTERN_KEY1}, + {"KEY2", FEEDBACK_PATTERN_KEY2}, + {"KEY3", FEEDBACK_PATTERN_KEY3}, + {"KEY4", FEEDBACK_PATTERN_KEY4}, + {"KEY5", FEEDBACK_PATTERN_KEY5}, + {"KEY6", FEEDBACK_PATTERN_KEY6}, + {"KEY7", FEEDBACK_PATTERN_KEY7}, + {"KEY8", FEEDBACK_PATTERN_KEY8}, + {"KEY9", FEEDBACK_PATTERN_KEY9}, + {"KEY_STAR", FEEDBACK_PATTERN_KEY_STAR}, + {"KEY_SHARP", FEEDBACK_PATTERN_KEY_SHARP}, + {"KEY_BACK", FEEDBACK_PATTERN_KEY_BACK}, + {"HOLD", FEEDBACK_PATTERN_HOLD}, + {"HW_TAP", FEEDBACK_PATTERN_HW_TAP}, + {"HW_HOLD", FEEDBACK_PATTERN_HW_HOLD}, + {"MESSAGE", FEEDBACK_PATTERN_MESSAGE}, + {"EMAIL", FEEDBACK_PATTERN_EMAIL}, + {"WAKEUP", FEEDBACK_PATTERN_WAKEUP}, + {"SCHEDULE", FEEDBACK_PATTERN_SCHEDULE}, + {"TIMER", FEEDBACK_PATTERN_TIMER}, + {"GENERAL", FEEDBACK_PATTERN_GENERAL}, + {"POWERON", FEEDBACK_PATTERN_POWERON}, + {"POWEROFF", FEEDBACK_PATTERN_POWEROFF}, + {"CHARGERCONN", FEEDBACK_PATTERN_CHARGERCONN}, + {"CHARGING_ERROR", FEEDBACK_PATTERN_CHARGING_ERROR}, + {"FULLCHARGED", FEEDBACK_PATTERN_FULLCHARGED}, + {"LOWBATT", FEEDBACK_PATTERN_LOWBATT}, + {"LOCK", FEEDBACK_PATTERN_LOCK}, + {"UNLOCK", FEEDBACK_PATTERN_UNLOCK}, + {"VIBRATION_ON", FEEDBACK_PATTERN_VIBRATION_ON}, + {"SILENT_OFF", FEEDBACK_PATTERN_SILENT_OFF}, + {"BT_CONNECTED", FEEDBACK_PATTERN_BT_CONNECTED}, + {"BT_DISCONNECTED", FEEDBACK_PATTERN_BT_DISCONNECTED}, + {"LIST_REORDER", FEEDBACK_PATTERN_LIST_REORDER}, + {"LIST_SLIDER", FEEDBACK_PATTERN_LIST_SLIDER}, + {"VOLUME_KEY", FEEDBACK_PATTERN_VOLUME_KEY}} {}; + +FeedbackMaps::~FeedbackMaps() { +} -feedback_pattern_e const & FeedbackMaps::getPatternFromMap(const std::string& pattern) { +feedback_pattern_e const &FeedbackMaps::getPatternFromMap(const std::string &pattern) { return mPatternMap[pattern]; } -feedback_type_e const & FeedbackMaps::getTypeFromMap(const std::string& type) { +feedback_type_e const &FeedbackMaps::getTypeFromMap(const std::string &type) { return mTypeMap[type]; } @@ -107,16 +101,13 @@ void FeedbackMaps::setPatternSupport(const feedback_pattern_e pattern, const fee mSupportedMap[std::make_pair(pattern, type)] = isSupported; } -FeedbackManager::FeedbackManager(std::shared_ptr maps) - : m_feedbackMapsPtr(maps) -{ +FeedbackManager::FeedbackManager(std::shared_ptr maps) : m_feedbackMapsPtr(maps) { LoggerD("Entered"); // feedback API initialization int ret = feedback_initialize(); - if(ret != FEEDBACK_ERROR_NONE) { + if (ret != FEEDBACK_ERROR_NONE) { LoggerE("Could not initialize Feedback Manager, error: %d", ret); } - } FeedbackManager::~FeedbackManager() { @@ -124,14 +115,14 @@ FeedbackManager::~FeedbackManager() { // feedback library deinitialization int ret = feedback_deinitialize(); - if(ret != FEEDBACK_ERROR_NONE) { + if (ret != FEEDBACK_ERROR_NONE) { LoggerE("Could not deinitialize Feedback Manager, error: %d", ret); } } common::PlatformResult FeedbackManager::isPatternSupported(const std::string &pattern, const std::string &type, - bool* patternStatus) { + bool *patternStatus) { LoggerD("Entered"); auto &pattern_e = m_feedbackMapsPtr->getPatternFromMap(pattern); @@ -186,7 +177,7 @@ common::PlatformResult FeedbackManager::stop() { LoggerD("Entered"); int ret = feedback_stop(); - if(ret != FEEDBACK_ERROR_NONE && ret != FEEDBACK_ERROR_NOT_SUPPORTED) { + if (ret != FEEDBACK_ERROR_NONE && ret != FEEDBACK_ERROR_NOT_SUPPORTED) { LoggerE("stop failed: %d", ret); return CodeToResult(ret, getFeedbackErrorMessage(ret).c_str()); } @@ -194,11 +185,10 @@ common::PlatformResult FeedbackManager::stop() { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult FeedbackManager::CodeToResult(const int errorCode, - const std::string& message) { +PlatformResult FeedbackManager::CodeToResult(const int errorCode, const std::string &message) { LoggerD("Entered"); - switch(errorCode) { + switch (errorCode) { case FEEDBACK_ERROR_NOT_SUPPORTED: return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, message); case FEEDBACK_ERROR_INVALID_PARAMETER: @@ -212,7 +202,7 @@ PlatformResult FeedbackManager::CodeToResult(const int errorCode, const std::string FeedbackManager::getFeedbackErrorMessage(const int error_code) { LoggerD("Error code : %d", error_code); - switch(error_code) { + switch (error_code) { case FEEDBACK_ERROR_OPERATION_FAILED: return "Operation not permitted"; case FEEDBACK_ERROR_INVALID_PARAMETER: @@ -226,5 +216,5 @@ const std::string FeedbackManager::getFeedbackErrorMessage(const int error_code) } } -}// feedback -}// extension +} // feedback +} // extension diff --git a/src/feedback/feedback_manager.h b/src/feedback/feedback_manager.h index 34c2a12..6c980e6 100644 --- a/src/feedback/feedback_manager.h +++ b/src/feedback/feedback_manager.h @@ -35,11 +35,13 @@ class FeedbackMaps { public: FeedbackMaps(); virtual ~FeedbackMaps(); - feedback_pattern_e const & getPatternFromMap(const std::string& pattern); - feedback_type_e const & getTypeFromMap(const std::string& type); + feedback_pattern_e const& getPatternFromMap(const std::string& pattern); + feedback_type_e const& getTypeFromMap(const std::string& type); bool isPatternSupportChecked(const feedback_pattern_e pattern, const feedback_type_e type); bool isPatternSupported(const feedback_pattern_e pattern, const feedback_type_e type); - void setPatternSupport(const feedback_pattern_e pattern, const feedback_type_e type, const bool isSupported); + void setPatternSupport(const feedback_pattern_e pattern, const feedback_type_e type, + const bool isSupported); + private: stringTypeMap mTypeMap; stringPatternMap mPatternMap; @@ -51,18 +53,18 @@ class FeedbackManager { FeedbackManager(std::shared_ptr maps); virtual ~FeedbackManager(); - common::PlatformResult isPatternSupported( - const std::string &pattern, const std::string &type, bool* patternStatus); - common::PlatformResult play(const std::string &pattern, const std::string &type); + common::PlatformResult isPatternSupported(const std::string& pattern, const std::string& type, + bool* patternStatus); + common::PlatformResult play(const std::string& pattern, const std::string& type); common::PlatformResult stop(); + private: const std::string getFeedbackErrorMessage(const int error_code); - common::PlatformResult CodeToResult( - const int errorCode, const std::string& message); + common::PlatformResult CodeToResult(const int errorCode, const std::string& message); std::shared_ptr m_feedbackMapsPtr; }; -} // feedback -} // extension +} // feedback +} // extension -#endif // FEEDBACK_MANAGER_H_ +#endif // FEEDBACK_MANAGER_H_ diff --git a/src/filesystem/filesystem_extension.cc b/src/filesystem/filesystem_extension.cc old mode 100755 new mode 100644 index 0116ae6..7935185 --- a/src/filesystem/filesystem_extension.cc +++ b/src/filesystem/filesystem_extension.cc @@ -30,7 +30,8 @@ FilesystemExtension::FilesystemExtension() { SetJavaScriptAPI(kSource_filesystem_api); } -FilesystemExtension::~FilesystemExtension() {} +FilesystemExtension::~FilesystemExtension() { +} common::Instance* FilesystemExtension::CreateInstance() { return new extension::filesystem::FilesystemInstance; diff --git a/src/filesystem/filesystem_extension.h b/src/filesystem/filesystem_extension.h old mode 100755 new mode 100644 index b3d8bec..43ee75b --- a/src/filesystem/filesystem_extension.h +++ b/src/filesystem/filesystem_extension.h @@ -28,4 +28,4 @@ class FilesystemExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // FILESYSTEM_FILESYSTEM_EXTENSION_H_ +#endif // FILESYSTEM_FILESYSTEM_EXTENSION_H_ diff --git a/src/filesystem/filesystem_file.cc b/src/filesystem/filesystem_file.cc index a12047e..bc0734c 100644 --- a/src/filesystem/filesystem_file.cc +++ b/src/filesystem/filesystem_file.cc @@ -15,10 +15,10 @@ */ #include "filesystem_file.h" +#include +#include #include #include -#include -#include namespace extension { namespace filesystem { @@ -63,8 +63,8 @@ char numberToCharacter(uint8_t i) { } bool validateCharacter(char c) { - if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || (c == '=') || (c == '+') || (c == '/')) { + if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '=') || + (c == '+') || (c == '/')) { return true; } return false; @@ -118,9 +118,8 @@ bool FilesystemBuffer::DecodeData(const std::string& data) { } for (size_t i = 0; i < data.length(); i += 4) { - uint8_t part[] = { - characterToNumber(data[i + 0]), characterToNumber(data[i + 1]), - characterToNumber(data[i + 2]), characterToNumber(data[i + 3])}; + uint8_t part[] = {characterToNumber(data[i + 0]), characterToNumber(data[i + 1]), + characterToNumber(data[i + 2]), characterToNumber(data[i + 3])}; push_back(uint8_t((part[0] << 2) | (part[1] >> 4))); if ((data.length() - i != 4) || (padding < 2)) { push_back(uint8_t((part[1] << 4) | (part[2] >> 2))); @@ -144,8 +143,7 @@ std::string FilesystemBuffer::EncodeData() const { out.push_back(numberToCharacter(0x3F & (part[2]))); } - if (out.size() == 0) - return out; + if (out.size() == 0) return out; // Add padding int fillup = (size() % 3); @@ -160,12 +158,10 @@ std::string FilesystemBuffer::EncodeData() const { return out; } -FilesystemFile::FilesystemFile(const std::string& path_) - : path(path_) {} +FilesystemFile::FilesystemFile(const std::string& path_) : path(path_) { +} -bool FilesystemFile::Read(FilesystemBuffer* data, - size_t offset, - size_t length) { +bool FilesystemFile::Read(FilesystemBuffer* data, size_t offset, size_t length) { LoggerD("Enter"); if (!data) { LoggerE("Missing output buffer"); diff --git a/src/filesystem/filesystem_file.h b/src/filesystem/filesystem_file.h index c7f2ece..124467e 100644 --- a/src/filesystem/filesystem_file.h +++ b/src/filesystem/filesystem_file.h @@ -17,9 +17,9 @@ #ifndef FILESYSTEM_FILESYSTEM_FILE_H #define FILESYSTEM_FILESYSTEM_FILE_H +#include #include #include -#include namespace extension { namespace filesystem { diff --git a/src/filesystem/filesystem_instance.cc b/src/filesystem/filesystem_instance.cc index 5434c51..3c94825 100644 --- a/src/filesystem/filesystem_instance.cc +++ b/src/filesystem/filesystem_instance.cc @@ -18,8 +18,8 @@ #include -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" #include "common/task-queue.h" #include "common/tools.h" @@ -42,8 +42,7 @@ FilesystemInstance::FilesystemInstance() { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&FilesystemInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&FilesystemInstance::x, this, _1, _2)); #define REGISTER_ASYNC(c, x) \ RegisterSyncHandler(c, std::bind(&FilesystemInstance::x, this, _1, _2)); @@ -57,15 +56,11 @@ FilesystemInstance::FilesystemInstance() { REGISTER_ASYNC("File_write", FileWrite); REGISTER_SYNC("File_writeSync", FileWriteSync); REGISTER_SYNC("Filesystem_fetchVirtualRoots", FilesystemFetchVirtualRoots); - REGISTER_SYNC("FileSystemManager_addStorageStateChangeListener", - StartListening); - REGISTER_SYNC("FileSystemManager_removeStorageStateChangeListener", - StopListening); - REGISTER_SYNC("FileSystemManager_fetchStorages", - FileSystemManagerFetchStorages); + REGISTER_SYNC("FileSystemManager_addStorageStateChangeListener", StartListening); + REGISTER_SYNC("FileSystemManager_removeStorageStateChangeListener", StopListening); + REGISTER_SYNC("FileSystemManager_fetchStorages", FileSystemManagerFetchStorages); REGISTER_ASYNC("FileSystemManager_mkdir", FileSystemManagerMakeDirectory); - REGISTER_SYNC("FileSystemManager_mkdirSync", - FileSystemManagerMakeDirectorySync); + REGISTER_SYNC("FileSystemManager_mkdirSync", FileSystemManagerMakeDirectorySync); REGISTER_ASYNC("File_unlinkFile", UnlinkFile); REGISTER_ASYNC("File_removeDirectory", RemoveDirectory); REGISTER_ASYNC("File_copyTo", CopyTo); @@ -81,14 +76,13 @@ FilesystemInstance::~FilesystemInstance() { FilesystemManager::GetInstance().RemoveListener(); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) { \ +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ LogAndReportError(TypeMismatchException(name " is required argument"), out); \ - return; \ + return; \ } -void FilesystemInstance::FileCreateSync(const picojson::value& args, picojson::object& out) -{ +void FilesystemInstance::FileCreateSync(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) @@ -108,8 +102,7 @@ void FilesystemInstance::FileCreateSync(const picojson::value& args, picojson::o FilesystemManager::GetInstance().CreateFile(location, onSuccess, onError); } -void FilesystemInstance::FileRename(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileRename(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -139,12 +132,11 @@ void FilesystemInstance::FileRename(const picojson::value& args, }; FilesystemManager& fsm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::Rename, &fsm, oldPath, newPath, onSuccess, onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::Rename, &fsm, oldPath, newPath, onSuccess, onError)); } -void FilesystemInstance::FileRead(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileRead(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) @@ -175,17 +167,11 @@ void FilesystemInstance::FileRead(const picojson::value& args, }; FilesystemManager& fsm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind(&FilesystemManager::FileRead, - &fsm, - location, - offset, - length, - onSuccess, - onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::FileRead, &fsm, location, offset, length, onSuccess, onError)); } -void FilesystemInstance::FileReadSync(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileReadSync(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "location", out) @@ -206,12 +192,10 @@ void FilesystemInstance::FileReadSync(const picojson::value& args, PrepareError(e, out); }; - FilesystemManager::GetInstance().FileRead( - location, offset, length, onSuccess, onError); + FilesystemManager::GetInstance().FileRead(location, offset, length, onSuccess, onError); } -void FilesystemInstance::FileWrite(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileWrite(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) @@ -244,19 +228,11 @@ void FilesystemInstance::FileWrite(const picojson::value& args, }; FilesystemManager& fsm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async( - std::bind(&FilesystemManager::FileWrite, - &fsm, - location, - data, - offset, - rewrite, - onSuccess, - onError)); + common::TaskQueue::GetInstance().Async(std::bind(&FilesystemManager::FileWrite, &fsm, location, + data, offset, rewrite, onSuccess, onError)); } -void FilesystemInstance::FileWriteSync(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileWriteSync(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) @@ -279,12 +255,10 @@ void FilesystemInstance::FileWriteSync(const picojson::value& args, PrepareError(e, out); }; - FilesystemManager::GetInstance().FileWrite( - location, data, offset, rewrite, onSuccess, onError); + FilesystemManager::GetInstance().FileWrite(location, data, offset, rewrite, onSuccess, onError); } -void FilesystemInstance::FileStat(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileStat(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "callbackId", out) @@ -312,12 +286,11 @@ void FilesystemInstance::FileStat(const picojson::value& args, }; FilesystemManager& fsm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::StatPath, &fsm, location, onSuccess, onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::StatPath, &fsm, location, onSuccess, onError)); } -void FilesystemInstance::FileStatSync(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileStatSync(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "location", out) @@ -337,8 +310,8 @@ void FilesystemInstance::FileStatSync(const picojson::value& args, FilesystemManager::GetInstance().StatPath(location, onSuccess, onError); } -void FilesystemInstance::FilesystemFetchVirtualRoots( - const picojson::value& args, picojson::object& out) { +void FilesystemInstance::FilesystemFetchVirtualRoots(const picojson::value& args, + picojson::object& out) { LoggerD("enter"); auto onSuccess = [&](const std::vector& result) { @@ -358,9 +331,8 @@ void FilesystemInstance::FilesystemFetchVirtualRoots( FilesystemManager::GetInstance().GetVirtualRoots(onSuccess, onError); } -void FilesystemInstance::FileSystemManagerFetchStorages( - const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileSystemManagerFetchStorages(const picojson::value& args, + picojson::object& out) { LoggerD("enter"); auto onSuccess = [&](const common::Storages& result) { @@ -380,18 +352,14 @@ void FilesystemInstance::FileSystemManagerFetchStorages( FilesystemManager::GetInstance().FetchStorages(onSuccess, onError); } -void FilesystemInstance::StartListening( - const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::StartListening(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); FilesystemManager::GetInstance().StartListening(); ReportSuccess(out); } -void FilesystemInstance::StopListening( - const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::StopListening(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); FilesystemManager::GetInstance().StopListening(); @@ -420,9 +388,8 @@ void FilesystemInstance::onFilesystemStateChangeErrorCallback() { Instance::PostMessage(this, event.serialize().c_str()); } -void FilesystemInstance::FileSystemManagerMakeDirectory( - const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileSystemManagerMakeDirectory(const picojson::value& args, + picojson::object& out) { LoggerD("enter"); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) @@ -449,9 +416,8 @@ void FilesystemInstance::FileSystemManagerMakeDirectory( common::TaskQueue::GetInstance().Async(onAction); } -void FilesystemInstance::FileSystemManagerMakeDirectorySync( - const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::FileSystemManagerMakeDirectorySync(const picojson::value& args, + picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) @@ -469,8 +435,7 @@ void FilesystemInstance::FileSystemManagerMakeDirectorySync( FilesystemManager::GetInstance().MakeDirectory(location, onResult); } -void FilesystemInstance::ReadDir(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::ReadDir(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "pathToDir", out) @@ -481,12 +446,13 @@ void FilesystemInstance::ReadDir(const picojson::value& args, auto onSuccess = [this, callback_id](const std::vector& paths) { LoggerD("enter"); - picojson::value result = picojson::value(picojson::array());; + picojson::value result = picojson::value(picojson::array()); + ; picojson::array& statPaths = result.get(); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); - for(auto path : paths) { + for (auto path : paths) { FilesystemStat stat = FilesystemStat::getStat(path); statPaths.push_back(stat.toJSON()); } @@ -504,12 +470,11 @@ void FilesystemInstance::ReadDir(const picojson::value& args, }; FilesystemManager& fm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::ReadDir, &fm, pathToDir, onSuccess, onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::ReadDir, &fm, pathToDir, onSuccess, onError)); } -void FilesystemInstance::UnlinkFile(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::UnlinkFile(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "pathToFile", out) @@ -537,12 +502,11 @@ void FilesystemInstance::UnlinkFile(const picojson::value& args, }; FilesystemManager& fm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::UnlinkFile, &fm, pathToFile, onSuccess, onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::UnlinkFile, &fm, pathToFile, onSuccess, onError)); } -void FilesystemInstance::RemoveDirectory(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::RemoveDirectory(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "pathToDelete", out) @@ -570,12 +534,11 @@ void FilesystemInstance::RemoveDirectory(const picojson::value& args, }; FilesystemManager& fm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::RemoveDirectory, &fm, pathToDelete, onSuccess, onError)); + common::TaskQueue::GetInstance().Async( + std::bind(&FilesystemManager::RemoveDirectory, &fm, pathToDelete, onSuccess, onError)); } -void FilesystemInstance::CopyTo(const picojson::value& args, - picojson::object& out) { +void FilesystemInstance::CopyTo(const picojson::value& args, picojson::object& out) { LoggerD("enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -608,12 +571,11 @@ void FilesystemInstance::CopyTo(const picojson::value& args, }; FilesystemManager& fm = FilesystemManager::GetInstance(); - common::TaskQueue::GetInstance().Async(std::bind( - &FilesystemManager::CopyTo, &fm, originPath, destinationPath, overwrite, onSuccess, onError)); + common::TaskQueue::GetInstance().Async(std::bind(&FilesystemManager::CopyTo, &fm, originPath, + destinationPath, overwrite, onSuccess, onError)); } -void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::object& out) -{ +void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::object& out) { LoggerD("enter"); switch (error) { case FilesystemError::None: @@ -632,12 +594,10 @@ void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::ob ("IOException - Directory already exists")); break; case FilesystemError::PermissionDenied: - LogAndReportError(IOException("Permission denied"), out, - ("IOException - Permission denied")); + LogAndReportError(IOException("Permission denied"), out, ("IOException - Permission denied")); break; case FilesystemError::IOError: - LogAndReportError(IOException("IO Error"), out, - ("IOException - IO Error")); + LogAndReportError(IOException("IO Error"), out, ("IOException - IO Error")); break; case FilesystemError::Other: LogAndReportError(UnknownException("PLATFORM ERROR other"), out, @@ -654,10 +614,10 @@ void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::ob } } -void FilesystemInstance::FileSystemManagerGetCanonicalPath(const picojson::value& args, picojson::object& out) -{ +void FilesystemInstance::FileSystemManagerGetCanonicalPath(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); - //TODO: any privilege needed? + // TODO: any privilege needed? CHECK_EXIST(args, "path", out); const std::string& path = args.get("path").get(); diff --git a/src/filesystem/filesystem_instance.h b/src/filesystem/filesystem_instance.h index e70d7c7..2212323 100644 --- a/src/filesystem/filesystem_instance.h +++ b/src/filesystem/filesystem_instance.h @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef FILESYSTEM_FILESYSTEM_INSTANCE_H_ #define FILESYSTEM_FILESYSTEM_INSTANCE_H_ #include "common/extension.h" -#include "filesystem_utils.h" -#include "filesystem/filesystem_manager.h" #include "common/filesystem/filesystem_storage.h" +#include "filesystem/filesystem_manager.h" +#include "filesystem_utils.h" namespace extension { namespace filesystem { -class FilesystemInstance : public common::ParsedInstance, - FilesystemStateChangeListener { +class FilesystemInstance : public common::ParsedInstance, FilesystemStateChangeListener { public: FilesystemInstance(); virtual ~FilesystemInstance(); @@ -40,14 +39,10 @@ class FilesystemInstance : public common::ParsedInstance, void FileReadSync(const picojson::value& args, picojson::object& out); void FileWrite(const picojson::value& args, picojson::object& out); void FileWriteSync(const picojson::value& args, picojson::object& out); - void FilesystemFetchVirtualRoots(const picojson::value& args, - picojson::object& out); - void FileSystemManagerFetchStorages(const picojson::value& args, - picojson::object& out); - void FileSystemManagerMakeDirectory(const picojson::value& args, - picojson::object& out); - void FileSystemManagerMakeDirectorySync(const picojson::value& args, - picojson::object& out); + void FilesystemFetchVirtualRoots(const picojson::value& args, picojson::object& out); + void FileSystemManagerFetchStorages(const picojson::value& args, picojson::object& out); + void FileSystemManagerMakeDirectory(const picojson::value& args, picojson::object& out); + void FileSystemManagerMakeDirectorySync(const picojson::value& args, picojson::object& out); void ReadDir(const picojson::value& args, picojson::object& out); void UnlinkFile(const picojson::value& args, picojson::object& out); void RemoveDirectory(const picojson::value& args, picojson::object& out); diff --git a/src/filesystem/filesystem_manager.cc b/src/filesystem/filesystem_manager.cc index 304ba79..b0bdcfd 100644 --- a/src/filesystem/filesystem_manager.cc +++ b/src/filesystem/filesystem_manager.cc @@ -17,15 +17,15 @@ #include "filesystem/filesystem_manager.h" #include +#include +#include #include #include #include -#include -#include -#include -#include #include #include +#include +#include #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 500 #endif @@ -33,10 +33,10 @@ #undef _XOPEN_SOURCE #include +#include "common/extension.h" #include "common/logger.h" -#include "common/tools.h" #include "common/scope_exit.h" -#include "common/extension.h" +#include "common/tools.h" #include "filesystem/filesystem_file.h" namespace extension { @@ -46,27 +46,22 @@ using common::tools::GetErrorString; namespace { -int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, - struct FTW* ftwbuf) { - if (ftwbuf->level == 0) - return 0; +int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) { + if (ftwbuf->level == 0) return 0; int result = remove(fpath); - if (result) - LoggerE("error occured"); + if (result) LoggerE("error occured"); return result; } -int unlink_with_base_dir_cb(const char* fpath, const struct stat* sb, - int typeflag, struct FTW* ftwbuf) { +int unlink_with_base_dir_cb(const char* fpath, const struct stat* sb, int typeflag, + struct FTW* ftwbuf) { int result = remove(fpath); - if (result) - LoggerE("error occured"); + if (result) LoggerE("error occured"); return result; } -FilesystemError copyFile(const std::string& originPath, - const std::string& destPath) { +FilesystemError copyFile(const std::string& originPath, const std::string& destPath) { LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); std::ifstream src(originPath, std::ios::in | std::ios::binary); @@ -84,8 +79,7 @@ FilesystemError copyFile(const std::string& originPath, return FilesystemError::None; } -FilesystemError copyDirectory(const std::string& originPath, - const std::string& destPath) { +FilesystemError copyDirectory(const std::string& originPath, const std::string& destPath) { LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); FilesystemStat destStat = FilesystemStat::getStat(destPath); @@ -109,13 +103,10 @@ FilesystemError copyDirectory(const std::string& originPath, errno = 0; struct dirent* entry = nullptr; while (nullptr != (entry = readdir(dp))) { - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - continue; + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; - std::string oldLocation = originPath + std::string("/") - + std::string(entry->d_name); - std::string newLocation = destPath + std::string("/") - + std::string(entry->d_name); + std::string oldLocation = originPath + std::string("/") + std::string(entry->d_name); + std::string newLocation = destPath + std::string("/") + std::string(entry->d_name); FilesystemError fstatus = FilesystemError::None; if (entry->d_type == DT_DIR) { fstatus = copyDirectory(oldLocation, newLocation); @@ -135,8 +126,8 @@ FilesystemError copyDirectory(const std::string& originPath, return FilesystemError::None; } -FilesystemError perform_deep_copy(const std::string& originPath, - const std::string& destPath, bool overwrite) { +FilesystemError perform_deep_copy(const std::string& originPath, const std::string& destPath, + bool overwrite) { LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); FilesystemStat originStat = FilesystemStat::getStat(originPath); FilesystemStat destStat = FilesystemStat::getStat(destPath); @@ -159,22 +150,19 @@ FilesystemError perform_deep_copy(const std::string& originPath, if (destStat.isDirectory) { path.append("/"); if (originStat.isFile) { - std::string dstPathWithFilename = originPath.substr( - originPath.find_last_of("/") + 1); + std::string dstPathWithFilename = originPath.substr(originPath.find_last_of("/") + 1); path.append(dstPathWithFilename); FilesystemStat destStatWithFilename = FilesystemStat::getStat(path); if (destStatWithFilename.valid) { status = remove(path.c_str()); if (status) { - LoggerE("Cannot remove old file: %s", - GetErrorString(errno).c_str()); + LoggerE("Cannot remove old file: %s", GetErrorString(errno).c_str()); return FilesystemError::Other; } } } else { const int maxDirOpened = 64; - if (nftw(path.c_str(), unlink_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) - != 0) { + if (nftw(path.c_str(), unlink_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) != 0) { LoggerE("Error occured"); return FilesystemError::Other; } @@ -182,8 +170,7 @@ FilesystemError perform_deep_copy(const std::string& originPath, } else { status = remove(path.c_str()); if (status) { - LoggerE("Cannot remove old directory: %s", - GetErrorString(errno).c_str()); + LoggerE("Cannot remove old directory: %s", GetErrorString(errno).c_str()); return FilesystemError::Other; } } @@ -236,8 +223,7 @@ void FilesystemManager::FetchStorages( } FilesystemManager::FilesystemManager() - : listener_(nullptr), - fs_provider_(common::FilesystemProvider::Create()) { + : listener_(nullptr), fs_provider_(common::FilesystemProvider::Create()) { LoggerD("enter"); } @@ -251,11 +237,9 @@ FilesystemManager& FilesystemManager::GetInstance() { return instance; } -void FilesystemManager::StatPath( - const std::string& path, - const std::function& success_cb, - const std::function& error_cb) { - +void FilesystemManager::StatPath(const std::string& path, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); FilesystemStat statData = FilesystemStat::getStat(path); if (!statData.valid) { @@ -273,25 +257,21 @@ void FilesystemManager::GetVirtualRoots( success_cb(fs_provider_.GetVirtualPaths()); } -void FilesystemManager::CreateFile( - const std::string& path, - const std::function& success_cb, - const std::function& error_cb) { +void FilesystemManager::CreateFile(const std::string& path, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); const mode_t create_mode = S_IRWXU | S_IRWXG | S_IRWXO; int status; - status = TEMP_FAILURE_RETRY( - open(path.c_str(), O_RDWR | O_CREAT, create_mode)); + status = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDWR | O_CREAT, create_mode)); if (-1 == status) { - LoggerE("Cannot create or open file %s: %s", path.c_str(), - GetErrorString(errno).c_str()); + LoggerE("Cannot create or open file %s: %s", path.c_str(), GetErrorString(errno).c_str()); error_cb(FilesystemError::Other); return; } status = close(status); if (0 != status) { - LoggerE("Cannot close file %s: %s", path.c_str(), - GetErrorString(errno).c_str()); + LoggerE("Cannot close file %s: %s", path.c_str(), GetErrorString(errno).c_str()); error_cb(FilesystemError::Other); return; } @@ -304,33 +284,30 @@ void FilesystemManager::CreateFile( } } -void FilesystemManager::MakeDirectory( - const std::string& path, - const std::function& result_cb) { +void FilesystemManager::MakeDirectory(const std::string& path, + const std::function& result_cb) { LoggerD("enter"); result_cb(make_directory_worker(path)); } -void FilesystemManager::Rename( - const std::string& oldPath, const std::string& newPath, - const std::function& success_cb, - const std::function& error_cb) { - +void FilesystemManager::Rename(const std::string& oldPath, const std::string& newPath, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); int status = rename(oldPath.c_str(), newPath.c_str()); if (0 != status) { - if(EXDEV != errno) { + if (EXDEV != errno) { LoggerE("Error while moving file"); error_cb(FilesystemError::Other); return; } LoggerD("Files are not on the same mounted file system"); - //In case of EXDEV we need to copy and remove file - //EXDEV - oldpath and newpath are not on the same mounted file system. - //Linux permits a file system to be mounted at multiple points, but rename() does not work - //across different mount points, even if the same file system is mounted on both. + // In case of EXDEV we need to copy and remove file + // EXDEV - oldpath and newpath are not on the same mounted file system. + // Linux permits a file system to be mounted at multiple points, but rename() does not work + // across different mount points, even if the same file system is mounted on both. if (FilesystemError::None != copyFile(oldPath, newPath)) { LoggerE("Error while copying file"); @@ -367,12 +344,11 @@ void FilesystemManager::Rename( } void FilesystemManager::ReadDir( - const std::string& path, - const std::function&)>& success_cb, + const std::string& path, const std::function&)>& success_cb, const std::function& error_cb) { LoggerD("entered"); - std::vector < std::string > fileList; + std::vector fileList; DIR* dp = nullptr; struct dirent* entry = nullptr; @@ -383,7 +359,7 @@ void FilesystemManager::ReadDir( if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) fileList.push_back(path + "/" + std::string(entry->d_name)); } - (void) closedir(dp); + (void)closedir(dp); if (0 == errno) { success_cb(fileList); } else { @@ -397,9 +373,8 @@ void FilesystemManager::ReadDir( } } -void FilesystemManager::UnlinkFile( - const std::string& path, const std::function& success_cb, - const std::function& error_cb) { +void FilesystemManager::UnlinkFile(const std::string& path, const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); if (unlink(path.c_str()) != 0) { LoggerE("Error occured while deleting file"); @@ -409,13 +384,12 @@ void FilesystemManager::UnlinkFile( success_cb(); } -void FilesystemManager::RemoveDirectory( - const std::string& path, const std::function& success_cb, - const std::function& error_cb) { +void FilesystemManager::RemoveDirectory(const std::string& path, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); const int maxDirOpened = 64; - if (nftw(path.c_str(), unlink_with_base_dir_cb, maxDirOpened, - FTW_DEPTH | FTW_PHYS) != 0) { + if (nftw(path.c_str(), unlink_with_base_dir_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) != 0) { LoggerE("Error occured"); error_cb(FilesystemError::Other); } @@ -423,13 +397,9 @@ void FilesystemManager::RemoveDirectory( return; } -void FilesystemManager::FileRead( - const std::string& path, - size_t offset, - size_t length, - const std::function& success_cb, - const std::function& error_cb) { - +void FilesystemManager::FileRead(const std::string& path, size_t offset, size_t length, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); FilesystemFile file(path); FilesystemBuffer buffer; @@ -443,14 +413,9 @@ void FilesystemManager::FileRead( success_cb(out_data); } -void FilesystemManager::FileWrite( - const std::string& path, - const std::string& data, - size_t offset, - bool rewrite, - const std::function& success_cb, - const std::function& error_cb) { - +void FilesystemManager::FileWrite(const std::string& path, const std::string& data, size_t offset, + bool rewrite, const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); FilesystemFile file(path); FilesystemBuffer buffer; @@ -471,9 +436,8 @@ void FilesystemManager::FileWrite( void FilesystemManager::StartListening() { LoggerD("Entered"); - auto set = std::bind(&FilesystemManager::OnStorageDeviceChanged, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3); + auto set = std::bind(&FilesystemManager::OnStorageDeviceChanged, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3); fs_provider_.RegisterDeviceChangeState(set); } @@ -493,13 +457,12 @@ void FilesystemManager::OnStorageDeviceChanged(common::Storage const& _storage, } } -void FilesystemManager::CopyTo( - const std::string& originFilePath, const std::string& destinationFilePath, - const bool overwrite, const std::function& success_cb, - const std::function& error_cb) { +void FilesystemManager::CopyTo(const std::string& originFilePath, + const std::string& destinationFilePath, const bool overwrite, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("enter"); - FilesystemError retval = perform_deep_copy(originFilePath, - destinationFilePath, overwrite); + FilesystemError retval = perform_deep_copy(originFilePath, destinationFilePath, overwrite); if (FilesystemError::None == retval) { success_cb(); } else { @@ -519,10 +482,10 @@ void FilesystemManager::RemoveListener() { } void FilesystemManager::GetCanonicalPath(const std::string& path, - const std::function& success_cb, - const std::function& error_cb) { + const std::function& success_cb, + const std::function& error_cb) { LoggerD("Enter"); - char *canonicalPath = nullptr; + char* canonicalPath = nullptr; SCOPE_EXIT { free(canonicalPath); @@ -532,7 +495,8 @@ void FilesystemManager::GetCanonicalPath(const std::string& path, int tmpErrno; if (!canonicalPath) { tmpErrno = errno; - LoggerE("Cannot get realpath of %s. Error: %s!", path.c_str(), GetErrorString(tmpErrno).c_str()); + LoggerE("Cannot get realpath of %s. Error: %s!", path.c_str(), + GetErrorString(tmpErrno).c_str()); error_cb(FilesystemError::Other); } diff --git a/src/filesystem/filesystem_manager.h b/src/filesystem/filesystem_manager.h index 0ef1815..41903ce 100644 --- a/src/filesystem/filesystem_manager.h +++ b/src/filesystem/filesystem_manager.h @@ -18,25 +18,25 @@ #define FILESYSTEM_FILESYSTEM_MANAGER_H #include +#include +#include #include #include -#include -#include #include "filesystem/filesystem_stat.h" #include "filesystem/filesystem_utils.h" -#include "common/filesystem/filesystem_storage.h" #include "common/filesystem/filesystem_provider.h" +#include "common/filesystem/filesystem_storage.h" namespace extension { namespace filesystem { class FilesystemStateChangeListener { public: - virtual ~FilesystemStateChangeListener() {} - virtual void onFilesystemStateChangeSuccessCallback( - const common::Storage& storage) = 0; + virtual ~FilesystemStateChangeListener() { + } + virtual void onFilesystemStateChangeSuccessCallback(const common::Storage& storage) = 0; virtual void onFilesystemStateChangeErrorCallback() = 0; }; @@ -48,73 +48,57 @@ class FilesystemManager { common::FilesystemProvider& fs_provider_; public: - virtual ~FilesystemManager(); static FilesystemManager& GetInstance(); - void UnlinkFile( - const std::string& path, - const std::function& success_cb, - const std::function& error_cb); + void UnlinkFile(const std::string& path, const std::function& success_cb, + const std::function& error_cb); void StatPath(const std::string& path, const std::function& success_cb, const std::function& error_cb); - void FetchStorages( - const std::function& success_cb, - const std::function& error_cb); + void FetchStorages(const std::function& success_cb, + const std::function& error_cb); - void GetVirtualRoots( - const std::function& success_cb, - const std::function& error_cb); + void GetVirtualRoots(const std::function& success_cb, + const std::function& error_cb); void CreateFile(const std::string& path, const std::function& success_cb, const std::function& error_cb); - void Rename(const std::string& oldPath, - const std::string& newPath, + void Rename(const std::string& oldPath, const std::string& newPath, const std::function& success_cb, const std::function& error_cb); void MakeDirectory(const std::string& path, const std::function& result_cb); - void ReadDir( - const std::string& path, - const std::function&)>& success_cb, - const std::function& error_cb); + void ReadDir(const std::string& path, + const std::function&)>& success_cb, + const std::function& error_cb); - void RemoveDirectory( - const std::string& path, - const std::function& success_cb, - const std::function& error_cb); + void RemoveDirectory(const std::string& path, const std::function& success_cb, + const std::function& error_cb); - void FileRead(const std::string& path, - size_t offset, - size_t length, + void FileRead(const std::string& path, size_t offset, size_t length, const std::function& success_cb, const std::function& error_cb); - void FileWrite(const std::string& path, - const std::string& data, - size_t offset, - bool rewrite, + void FileWrite(const std::string& path, const std::string& data, size_t offset, bool rewrite, const std::function& success_cb, const std::function& error_cb); -void CopyTo(const std::string& originFilePath, - const std::string& destinationFilePath, - const bool overwrite, - const std::function& success_cb, - const std::function& error_cb); + void CopyTo(const std::string& originFilePath, const std::string& destinationFilePath, + const bool overwrite, const std::function& success_cb, + const std::function& error_cb); void StartListening(); void StopListening(); - void OnStorageDeviceChanged(common::Storage const& _virtualStorage, - common::StorageState _old, common::StorageState _new); + void OnStorageDeviceChanged(common::Storage const& _virtualStorage, common::StorageState _old, + common::StorageState _new); void AddListener(FilesystemStateChangeListener* listener); void RemoveListener(); diff --git a/src/filesystem/filesystem_stat.cc b/src/filesystem/filesystem_stat.cc old mode 100755 new mode 100644 index 40667cf..ebc78ac --- a/src/filesystem/filesystem_stat.cc +++ b/src/filesystem/filesystem_stat.cc @@ -16,13 +16,13 @@ #include "filesystem_stat.h" -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include namespace extension { namespace filesystem { @@ -86,15 +86,13 @@ FilesystemStat FilesystemStat::getStat(const std::string& path) { if (getuid() == aStatObj.st_uid && (aStatObj.st_mode & S_IWUSR) == S_IWUSR) { _result.readOnly = false; - } else if (getgid() == aStatObj.st_gid && - (aStatObj.st_mode & S_IWGRP) == S_IWGRP) { + } else if (getgid() == aStatObj.st_gid && (aStatObj.st_mode & S_IWGRP) == S_IWGRP) { _result.readOnly = false; } else if ((aStatObj.st_mode & S_IWOTH) == S_IWOTH) { _result.readOnly = false; } else if (n_groups > 0) { - for(int i=0; i #include +#include #include "common/picojson.h" namespace extension { diff --git a/src/humanactivitymonitor/gesture_manager.cc b/src/humanactivitymonitor/gesture_manager.cc index 050d79e..1168f4b 100644 --- a/src/humanactivitymonitor/gesture_manager.cc +++ b/src/humanactivitymonitor/gesture_manager.cc @@ -18,12 +18,12 @@ #include +#include "common/extension.h" #include "common/logger.h" #include "common/optional.h" #include "common/picojson.h" -#include "common/tools.h" #include "common/scope_exit.h" -#include "common/extension.h" +#include "common/tools.h" namespace extension { namespace humanactivitymonitor { @@ -148,7 +148,7 @@ std::string GestureEventToStr(gesture_event_e event, gesture_type_e gesture) { } void GestureRecognitionDefaultCb(gesture_type_e gesture, const gesture_data_h data, - double timestamp, gesture_error_e error, void *user_data) { + double timestamp, gesture_error_e error, void* user_data) { ScopeLogger(); GestureManager* manager = static_cast(user_data); @@ -161,7 +161,7 @@ void GestureRecognitionDefaultCb(gesture_type_e gesture, const gesture_data_h da } void GestureRecognitionAlwaysOnCb(gesture_type_e gesture, const gesture_data_h data, - double timestamp, gesture_error_e error, void *user_data) { + double timestamp, gesture_error_e error, void* user_data) { ScopeLogger(); GestureManager* manager = static_cast(user_data); @@ -175,10 +175,8 @@ void GestureRecognitionAlwaysOnCb(gesture_type_e gesture, const gesture_data_h d } // namespace -GestureManager::GestureManager() : - m_callback(nullptr), - m_recognition_default_map(), - m_recognition_always_on_map() { +GestureManager::GestureManager() + : m_callback(nullptr), m_recognition_default_map(), m_recognition_always_on_map() { ScopeLogger(); } @@ -226,9 +224,9 @@ PlatformResult GestureManager::IsSupported(const std::string& type, bool* is_sup int ret = gesture_is_supported(type_e, is_supported); if (GESTURE_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Checking gesture failed", - ("Checking gesture failed, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Checking gesture failed", + ("Checking gesture failed, error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -261,10 +259,8 @@ void GestureManager::FillTiltData(const gesture_data_h data, picojson::object* o obj->insert(std::make_pair("y", picojson::value(static_cast(y)))); } -void GestureManager::CompleteGestureListenerCb(gesture_type_e gesture, - const gesture_data_h data, - double timestamp, - gesture_error_e error, +void GestureManager::CompleteGestureListenerCb(gesture_type_e gesture, const gesture_data_h data, + double timestamp, gesture_error_e error, bool always_on) { ScopeLogger(); @@ -277,7 +273,8 @@ void GestureManager::CompleteGestureListenerCb(gesture_type_e gesture, if (GESTURE_ERROR_NONE != error) { obj.insert(std::make_pair(kAction, picojson::value(kOnError))); - PlatformResult result = LogAndCreateResult(getErrorCode(error), "Error occurred during recognition"); + PlatformResult result = + LogAndCreateResult(getErrorCode(error), "Error occurred during recognition"); ReportError(result, &obj); } else { gesture_event_e event = GetGestureEvent(data); @@ -324,17 +321,17 @@ PlatformResult GestureManager::AddListener(gesture_type_e type, gesture_option_e int ret = gesture_create(&handle); if (GESTURE_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Creating handle failed", - ("Creating handle failed, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Creating handle failed", + ("Creating handle failed, error: %d (%s)", ret, get_error_message(ret))); } ret = gesture_start_recognition(handle, type, option, callback, this); if (GESTURE_ERROR_NONE != ret) { gesture_release(handle); - return LogAndCreateResult(getErrorCode(ret), - "Starting recognition failed", - ("Starting recognition failed, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Starting recognition failed", + ("Starting recognition failed, error: %d (%s)", ret, get_error_message(ret))); } gesture_map[type] = handle; @@ -342,10 +339,8 @@ PlatformResult GestureManager::AddListener(gesture_type_e type, gesture_option_e return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult GestureManager::AddGestureRecognitionListener(const std::string& type, - bool always_on, - JsonCallback cb) { + bool always_on, JsonCallback cb) { ScopeLogger(); gesture_type_e type_e = GESTURE_DOUBLE_TAP; @@ -393,9 +388,9 @@ PlatformResult GestureManager::RemoveGestureRecognitionListener(const std::strin if (handle) { int ret = gesture_stop_recognition(handle); if (GESTURE_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Stoping recognition failed", - ("Stoping recognition failed, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Stoping recognition failed", + ("Stoping recognition failed, error: %d (%s)", ret, get_error_message(ret))); } ret = gesture_release(handle); diff --git a/src/humanactivitymonitor/gesture_manager.h b/src/humanactivitymonitor/gesture_manager.h index 081b81d..75b05f9 100644 --- a/src/humanactivitymonitor/gesture_manager.h +++ b/src/humanactivitymonitor/gesture_manager.h @@ -17,9 +17,9 @@ #ifndef HUMANACTIVITYMONITOR_GESTURE_MANAGER_H #define HUMANACTIVITYMONITOR_GESTURE_MANAGER_H -#include -#include #include +#include +#include #include "common/picojson.h" #include "common/platform_result.h" @@ -47,14 +47,14 @@ class GestureManager { gesture_event_e GetGestureEvent(const gesture_data_h data); void FillTiltData(const gesture_data_h data, picojson::object* obj); common::PlatformResult AddListener(gesture_type_e type, gesture_option_e option, - RecognitionMap& gesture_map, gesture_recognition_cb callback); + RecognitionMap& gesture_map, gesture_recognition_cb callback); JsonCallback m_callback; RecognitionMap m_recognition_default_map; RecognitionMap m_recognition_always_on_map; }; -} // namespace humanactivitymonitor -} // namespace extension +} // namespace humanactivitymonitor +} // namespace extension #endif // HUMANACTIVITYMONITOR_GESTURE_MANAGER_H diff --git a/src/humanactivitymonitor/humanactivitymonitor_extension.cc b/src/humanactivitymonitor/humanactivitymonitor_extension.cc old mode 100755 new mode 100644 index d116516..6074271 --- a/src/humanactivitymonitor/humanactivitymonitor_extension.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_extension.cc @@ -29,7 +29,8 @@ HumanActivityMonitorExtension::HumanActivityMonitorExtension() { SetJavaScriptAPI(kSource_humanactivitymonitor_api); } -HumanActivityMonitorExtension::~HumanActivityMonitorExtension() {} +HumanActivityMonitorExtension::~HumanActivityMonitorExtension() { +} common::Instance* HumanActivityMonitorExtension::CreateInstance() { return new extension::humanactivitymonitor::HumanActivityMonitorInstance; diff --git a/src/humanactivitymonitor/humanactivitymonitor_instance.cc b/src/humanactivitymonitor/humanactivitymonitor_instance.cc old mode 100755 new mode 100644 index 69c1c2a..2ba412d --- a/src/humanactivitymonitor/humanactivitymonitor_instance.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_instance.cc @@ -20,8 +20,8 @@ #include #include -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_result.h" #include "common/task-queue.h" #include "common/tools.h" @@ -35,28 +35,25 @@ namespace { const std::string kPrivilegeHealthInfo = "http://tizen.org/privilege/healthinfo"; const std::string kPrivilegeLocation = "http://tizen.org/privilege/location"; -const int DEFAULT_HRM_INTERVAL = 1440; // 1440 (1 day) default value for HRM's interval -const int DEFAULT_RETENTION_PERIOD = 1; // 1 hour default value for retention period +const int DEFAULT_HRM_INTERVAL = 1440; // 1440 (1 day) default value for HRM's interval +const int DEFAULT_RETENTION_PERIOD = 1; // 1 hour default value for retention period } // namespace using common::PlatformResult; using common::ErrorCode; using common::TaskQueue; -HumanActivityMonitorInstance::HumanActivityMonitorInstance() : - gesture_manager_() { +HumanActivityMonitorInstance::HumanActivityMonitorInstance() : gesture_manager_() { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&HumanActivityMonitorInstance::x, this, _1, _2)); + RegisterSyncHandler(c, std::bind(&HumanActivityMonitorInstance::x, this, _1, _2)); REGISTER_SYNC("HumanActivityMonitorManager_getHumanActivityData", HumanActivityMonitorManagerGetHumanActivityData); - REGISTER_SYNC("HumanActivityMonitorManager_start", - HumanActivityMonitorManagerStart); - REGISTER_SYNC("HumanActivityMonitorManager_stop", - HumanActivityMonitorManagerStop); + REGISTER_SYNC("HumanActivityMonitorManager_start", HumanActivityMonitorManagerStart); + REGISTER_SYNC("HumanActivityMonitorManager_stop", HumanActivityMonitorManagerStop); REGISTER_SYNC("HumanActivityMonitorManager_addActivityRecognitionListener", HumanActivityMonitorManagerAddActivityRecognitionListener); REGISTER_SYNC("HumanActivityMonitorManager_removeActivityRecognitionListener", @@ -66,9 +63,8 @@ HumanActivityMonitorInstance::HumanActivityMonitorInstance() : REGISTER_SYNC("HumanActivityMonitorManager_stopRecorder", HumanActivityMonitorManagerStopRecorder); REGISTER_SYNC("HumanActivityMonitorManager_readRecorderData", - HumanActivityMonitorManagerReadRecorderData); - REGISTER_SYNC("GestureManager_isGestureSupported", - GestureManagerIsGestureSupported); + HumanActivityMonitorManagerReadRecorderData); + REGISTER_SYNC("GestureManager_isGestureSupported", GestureManagerIsGestureSupported); REGISTER_SYNC("GestureManager_addGestureRecognitionListener", GestureManagerAddGestureRecognitionListener); REGISTER_SYNC("GestureManager_removeGestureRecognitionListener", @@ -83,7 +79,6 @@ HumanActivityMonitorInstance::~HumanActivityMonitorInstance() { PlatformResult HumanActivityMonitorInstance::Init() { LoggerD("Enter"); if (!manager_) { - manager_ = std::make_shared(); const PlatformResult& result = manager_->Init(); if (!result) { @@ -96,13 +91,12 @@ PlatformResult HumanActivityMonitorInstance::Init() { return PlatformResult(ErrorCode::NO_ERROR); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) { \ - LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, \ - name" is required argument"), &out); \ - return; \ - } - +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, name " is required argument"), \ + &out); \ + return; \ + } void HumanActivityMonitorInstance::HumanActivityMonitorManagerGetHumanActivityData( const picojson::value& args, picojson::object& out) { @@ -147,8 +141,8 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerGetHumanActivityDa ReportSuccess(out); } -void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart( - const picojson::value& args, picojson::object& out) { +void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "type", out) @@ -188,8 +182,8 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart( } } -void HumanActivityMonitorInstance::HumanActivityMonitorManagerStop( - const picojson::value& args, picojson::object& out) { +void HumanActivityMonitorInstance::HumanActivityMonitorManagerStop(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "type", out) @@ -357,7 +351,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerReadRecorderData( /* check if given human activity recorder type is supported */ if (!manager_->IsSupported(type)) { - LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"), &out); + LogAndReportError(PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"), &out); return; } @@ -368,7 +362,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerReadRecorderData( picojson::object& response_obj = response.get(); response_obj["callbackId"] = picojson::value(callback_id); - //picojson::value data = picojson::value(); + // picojson::value data = picojson::value(); picojson::value array_value{picojson::array{}}; auto* array = &array_value.get(); @@ -388,8 +382,8 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerReadRecorderData( ReportSuccess(out); } -void HumanActivityMonitorInstance::GestureManagerIsGestureSupported( - const picojson::value& args, picojson::object& out) { +void HumanActivityMonitorInstance::GestureManagerIsGestureSupported(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "type", out) @@ -443,7 +437,8 @@ void HumanActivityMonitorInstance::GestureManagerRemoveGestureRecognitionListene if (result) { ReportSuccess(out); } else { - LogAndReportError(result, &out, ("Failed: gesture_manager_->RemoveGestureRecognitionListener()")); + LogAndReportError(result, &out, + ("Failed: gesture_manager_->RemoveGestureRecognitionListener()")); } } diff --git a/src/humanactivitymonitor/humanactivitymonitor_instance.h b/src/humanactivitymonitor/humanactivitymonitor_instance.h old mode 100755 new mode 100644 index c58e37c..e0ed215 --- a/src/humanactivitymonitor/humanactivitymonitor_instance.h +++ b/src/humanactivitymonitor/humanactivitymonitor_instance.h @@ -21,8 +21,8 @@ #include "common/extension.h" #include "common/platform_result.h" -#include "humanactivitymonitor/humanactivitymonitor_manager.h" #include "humanactivitymonitor/gesture_manager.h" +#include "humanactivitymonitor/humanactivitymonitor_manager.h" namespace extension { namespace humanactivitymonitor { @@ -33,35 +33,30 @@ class HumanActivityMonitorInstance : public common::ParsedInstance { virtual ~HumanActivityMonitorInstance(); private: - void HumanActivityMonitorManagerStop( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerGetHumanActivityData( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerStart( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerAddActivityRecognitionListener( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerRemoveActivityRecognitionListener( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerStartRecorder( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerStopRecorder( - const picojson::value& args, picojson::object& out); - void HumanActivityMonitorManagerReadRecorderData( - const picojson::value& args, picojson::object& out); - void GestureManagerIsGestureSupported( - const picojson::value& args, picojson::object& out); - void GestureManagerAddGestureRecognitionListener( - const picojson::value& args, picojson::object& out); - void GestureManagerRemoveGestureRecognitionListener( - const picojson::value& args, picojson::object& out); + void HumanActivityMonitorManagerStop(const picojson::value& args, picojson::object& out); + void HumanActivityMonitorManagerGetHumanActivityData(const picojson::value& args, + picojson::object& out); + void HumanActivityMonitorManagerStart(const picojson::value& args, picojson::object& out); + void HumanActivityMonitorManagerAddActivityRecognitionListener(const picojson::value& args, + picojson::object& out); + void HumanActivityMonitorManagerRemoveActivityRecognitionListener(const picojson::value& args, + picojson::object& out); + void HumanActivityMonitorManagerStartRecorder(const picojson::value& args, picojson::object& out); + void HumanActivityMonitorManagerStopRecorder(const picojson::value& args, picojson::object& out); + void HumanActivityMonitorManagerReadRecorderData(const picojson::value& args, + picojson::object& out); + void GestureManagerIsGestureSupported(const picojson::value& args, picojson::object& out); + void GestureManagerAddGestureRecognitionListener(const picojson::value& args, + picojson::object& out); + void GestureManagerRemoveGestureRecognitionListener(const picojson::value& args, + picojson::object& out); std::shared_ptr manager_; GestureManager gesture_manager_; common::PlatformResult Init(); }; -} // namespace humanactivitymonitor -} // namespace extension +} // namespace humanactivitymonitor +} // namespace extension #endif // HUMANACTIVITYMONITOR_HUMANACTIVITYMONITOR_INSTANCE_H_ diff --git a/src/humanactivitymonitor/humanactivitymonitor_manager.cc b/src/humanactivitymonitor/humanactivitymonitor_manager.cc old mode 100755 new mode 100644 index dda7ba1..a741783 --- a/src/humanactivitymonitor/humanactivitymonitor_manager.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_manager.cc @@ -27,8 +27,8 @@ #include "common/logger.h" #include "common/optional.h" #include "common/picojson.h" -#include "common/tools.h" #include "common/scope_exit.h" +#include "common/tools.h" namespace extension { namespace humanactivitymonitor { @@ -93,7 +93,7 @@ const std::string kRecordedAverage = "average"; const std::string kRecordedAnchorTime = "anchorTime"; const std::string kRecordedInterval = "interval"; -ErrorCode getErrorCode (const int errorCode) { +ErrorCode getErrorCode(const int errorCode) { ScopeLogger(); switch (errorCode) { case SENSOR_ERROR_IO_ERROR: @@ -151,8 +151,7 @@ struct PedometerDataWrapper : public sensor_pedometer_data_t { } }; -static int64_t getCurrentTimeStamp(unsigned long long evTime) -{ +static int64_t getCurrentTimeStamp(unsigned long long evTime) { LoggerD("Enter"); struct timespec t; unsigned long long systemCurrentTime = 0; @@ -160,15 +159,16 @@ static int64_t getCurrentTimeStamp(unsigned long long evTime) unsigned long long timeDiff = 0; int64_t timeStamp = 0; - //get current system monotonic time + // get current system monotonic time clock_gettime(CLOCK_MONOTONIC, &t); - systemCurrentTime = ((unsigned long long)(t.tv_sec)*1000000000LL + t.tv_nsec) /1000000; //convert millisecond - timeDiff = (systemCurrentTime - (evTime/1000)); + systemCurrentTime = + ((unsigned long long)(t.tv_sec) * 1000000000LL + t.tv_nsec) / 1000000; // convert millisecond + timeDiff = (systemCurrentTime - (evTime / 1000)); - //get current epoch time(millisecond) + // get current epoch time(millisecond) clock_gettime(CLOCK_REALTIME, &t); - realCurrentTime = ((unsigned long long)(t.tv_sec)*1000000000LL + t.tv_nsec) /1000000; - timeStamp =static_cast(realCurrentTime -timeDiff); + realCurrentTime = ((unsigned long long)(t.tv_sec) * 1000000000LL + t.tv_nsec) / 1000000; + timeStamp = static_cast(realCurrentTime - timeDiff); return timeStamp; } @@ -208,9 +208,8 @@ PlatformResult ConvertRecordedTime(void* data, picojson::object* obj) { int ret = sensor_recorder_data_get_time(data, &start_time, &end_time); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to get time", - ("Failed to get time, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(getErrorCode(ret), "Failed to get time", + ("Failed to get time, error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair(kRecordedStartTime, picojson::value(static_cast(start_time)))); @@ -229,9 +228,9 @@ PlatformResult ConvertRecordedInt(void* data, picojson::object* obj, for (auto& it : map) { ret = sensor_recorder_data_get_int(data, it.first, &tmp); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to get int value", - ("Failed to get int value, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Failed to get int value", + ("Failed to get int value, error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair(it.second, picojson::value(static_cast(tmp)))); @@ -250,9 +249,9 @@ PlatformResult ConvertRecordedDouble(void* data, picojson::object* obj, for (auto& it : map) { ret = sensor_recorder_data_get_double(data, it.first, &tmp); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to get double value", - ("Failed to get double value, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Failed to get double value", + ("Failed to get double value, error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair(it.second, picojson::value(static_cast(tmp)))); @@ -370,32 +369,32 @@ class HumanActivityMonitorManager::Monitor { virtual PlatformResult SetListenerImpl(const picojson::value& args) { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } virtual PlatformResult UnsetListenerImpl() { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } virtual PlatformResult GetDataImpl(picojson::value* data) const { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } virtual PlatformResult StartDataRecorderImpl(int interval, int retention_period) const { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } virtual PlatformResult StopDataRecorderImpl() const { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } virtual PlatformResult ReadRecorderDataImpl(picojson::array* data, const picojson::value& query) { ScopeLogger(type()); - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } public: @@ -415,7 +414,7 @@ class HumanActivityMonitorManager::Monitor { if (*is_supported_) { return PlatformResult(ErrorCode::NO_ERROR); } else { - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR,"NOT_SUPPORTED_ERR"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NOT_SUPPORTED_ERR"); } } @@ -425,7 +424,8 @@ class HumanActivityMonitorManager::Monitor { JsonCallback event_callback_; }; -class HumanActivityMonitorManager::Monitor::GestureMonitor : public HumanActivityMonitorManager::Monitor { +class HumanActivityMonitorManager::Monitor::GestureMonitor + : public HumanActivityMonitorManager::Monitor { public: explicit GestureMonitor(const std::string& t) : Monitor(t), handle_(nullptr) { ScopeLogger(type()); @@ -445,13 +445,13 @@ class HumanActivityMonitorManager::Monitor::GestureMonitor : public HumanActivit int ret = gesture_is_supported(GESTURE_WRIST_UP, &supported); if (ret != SENSOR_ERROR_NONE) { if (ret == GESTURE_ERROR_NOT_SUPPORTED) { - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "WRIST_UP gesture check failed", - ("gesture_is_supported(GESTURE_WRIST_UP), error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "WRIST_UP gesture check failed", + ("gesture_is_supported(GESTURE_WRIST_UP), error: %d (%s)", ret, + get_error_message(ret))); } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "WRIST_UP gesture check failed", - ("gesture_is_supported(GESTURE_WRIST_UP), error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "WRIST_UP gesture check failed", + ("gesture_is_supported(GESTURE_WRIST_UP), error: %d (%s)", ret, + get_error_message(ret))); } } @@ -465,20 +465,17 @@ class HumanActivityMonitorManager::Monitor::GestureMonitor : public HumanActivit if (!handle_) { int ret = gesture_create(&handle_); if (GESTURE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create WRIST_UP listener", - ("Failed to create WRIST_UP handle, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to create WRIST_UP listener", + ("Failed to create WRIST_UP handle, error: %d (%s)", ret, get_error_message(ret))); } - ret = gesture_start_recognition(handle_, - GESTURE_WRIST_UP, - GESTURE_OPTION_DEFAULT, - OnWristUpEvent, - this); + ret = gesture_start_recognition(handle_, GESTURE_WRIST_UP, GESTURE_OPTION_DEFAULT, + OnWristUpEvent, this); if (GESTURE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to start WRIST_UP listener", - ("Failed to start WRIST_UP listener, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to start WRIST_UP listener", + ("Failed to start WRIST_UP listener, error: %d (%s)", ret, get_error_message(ret))); } } @@ -508,11 +505,8 @@ class HumanActivityMonitorManager::Monitor::GestureMonitor : public HumanActivit // GetData is not supported by gesture monitor private: - static void OnWristUpEvent(gesture_type_e gesture, - const gesture_data_h data, - double timestamp, - gesture_error_e error, - void* user_data) { + static void OnWristUpEvent(gesture_type_e gesture, const gesture_data_h data, double timestamp, + gesture_error_e error, void* user_data) { ScopeLogger(); auto monitor = static_cast(user_data); @@ -530,13 +524,21 @@ class HumanActivityMonitorManager::Monitor::GestureMonitor : public HumanActivit gesture_h handle_; }; -class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivityMonitorManager::Monitor { +class HumanActivityMonitorManager::Monitor::SensorMonitor + : public HumanActivityMonitorManager::Monitor { public: - using SensorEventConverter = std::function; + using SensorEventConverter = + std::function; using SensorRecordedConverter = std::function; - SensorMonitor(const std::string& t, sensor_type_e s, const SensorEventConverter& c, const SensorRecordedConverter& r) - : Monitor(t), sensor_(s), handle_(nullptr), converter_(c), converter_recorded_(r), recorded_data_(nullptr) { + SensorMonitor(const std::string& t, sensor_type_e s, const SensorEventConverter& c, + const SensorRecordedConverter& r) + : Monitor(t), + sensor_(s), + handle_(nullptr), + converter_(c), + converter_recorded_(r), + recorded_data_(nullptr) { ScopeLogger(type()); } @@ -553,9 +555,9 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity int ret = sensor_is_supported(sensor_, &supported); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Sensor support check failed", - ("sensor_is_supported(%d), error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Sensor support check failed", + ("sensor_is_supported(%d), error: %d (%s)", sensor_, ret, get_error_message(ret))); } *s = supported; @@ -570,23 +572,23 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity int ret = sensor_get_default_sensor(sensor_, &sensor_handle); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get default sensor", - ("Failed to get (%d) sensor, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to get default sensor", + ("Failed to get (%d) sensor, error: %d (%s)", sensor_, ret, get_error_message(ret))); } ret = sensor_create_listener(sensor_handle, &handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create sensor listener", - ("Failed to create (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create sensor listener", + ("Failed to create (%d) sensor listener, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } ret = sensor_listener_set_option(handle_, SENSOR_OPTION_ALWAYS_ON); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set sensor listener option", - ("Failed to set (%d) sensor listener option, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set sensor listener option", + ("Failed to set (%d) sensor listener option, error: %d (%s)", + sensor_, ret, get_error_message(ret))); } int interval = 0; @@ -597,21 +599,18 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity LoggerD("callbackInterval: %d", interval); } - ret = sensor_listener_set_event_cb(handle_, - interval, - OnSensorEvent, - this); + ret = sensor_listener_set_event_cb(handle_, interval, OnSensorEvent, this); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set sensor listener", - ("Failed to set (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set sensor listener", + ("Failed to set (%d) sensor listener, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } ret = sensor_listener_start(handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to start sensor listener", - ("Failed to start (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to start sensor listener", + ("Failed to start (%d) sensor listener, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } } @@ -624,23 +623,23 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity if (handle_) { int ret = sensor_listener_stop(handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to stop sensor listener", - ("Failed to stop (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to stop sensor listener", + ("Failed to stop (%d) sensor listener, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } ret = sensor_listener_unset_event_cb(handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to unset sensor listener", - ("Failed to unset (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unset sensor listener", + ("Failed to unset (%d) sensor listener, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } ret = sensor_destroy_listener(handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to destroy sensor listener", - ("Failed to destroy (%d) sensor listener, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to destroy sensor listener", + ("Failed to destroy (%d) sensor listener, error: %d (%s)", + sensor_, ret, get_error_message(ret))); } handle_ = nullptr; @@ -653,22 +652,22 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity ScopeLogger(type()); if (!handle_) { - return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR,"SERVICE_NOT_AVAILABLE_ERR"); + return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "SERVICE_NOT_AVAILABLE_ERR"); } sensor_event_s event = {0}; int ret = sensor_listener_read_data(handle_, &event); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get sensor data", - ("Failed to get (%d) sensor data, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to get sensor data", + ("Failed to get (%d) sensor data, error: %d (%s)", sensor_, ret, get_error_message(ret))); } - if (SENSOR_HUMAN_PEDOMETER == sensor_ ){ - //read data of pedometer does not have valid diff[] , so diff_count set 0 - const auto pedometer_data = (PedometerDataWrapper *)(&event); - pedometer_data->diffs_count = 0; + if (SENSOR_HUMAN_PEDOMETER == sensor_) { + // read data of pedometer does not have valid diff[] , so diff_count set 0 + const auto pedometer_data = (PedometerDataWrapper*)(&event); + pedometer_data->diffs_count = 0; } *data = picojson::value(picojson::object()); @@ -687,9 +686,9 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity int ret = sensor_recorder_create_option(&option); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to create recorder option", - ("Failed to create (%d) recorder option, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(getErrorCode(ret), "Failed to create recorder option", + ("Failed to create (%d) recorder option, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } SCOPE_EXIT { @@ -703,9 +702,9 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity ret = sensor_recorder_start(sensor_, option); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to start recording", - ("Failed to start (%d) recording, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Failed to start recording", + ("Failed to start (%d) recording, error: %d (%s)", sensor_, ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -716,15 +715,16 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity int ret = sensor_recorder_stop(sensor_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to stop recording", - ("Failed to stop (%d) recording, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Failed to stop recording", + ("Failed to stop (%d) recording, error: %d (%s)", sensor_, ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } - virtual PlatformResult ReadRecorderDataImpl(picojson::array* data, const picojson::value& query) override { + virtual PlatformResult ReadRecorderDataImpl(picojson::array* data, + const picojson::value& query) override { ScopeLogger(type()); std::lock_guard lock(mutex_); @@ -733,9 +733,9 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity sensor_recorder_query_h query_h = nullptr; int ret = sensor_recorder_create_query(&query_h); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to create query", - ("Failed to create (%d) query, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult( + getErrorCode(ret), "Failed to create query", + ("Failed to create (%d) query, error: %d (%s)", sensor_, ret, get_error_message(ret))); } SCOPE_EXIT { @@ -749,11 +749,12 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity } } - ret = sensor_recorder_read_sync(sensor_, query_h, SensorRecordedDataCb, static_cast(this)); + ret = + sensor_recorder_read_sync(sensor_, query_h, SensorRecordedDataCb, static_cast(this)); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(getErrorCode(ret), - "Failed to read recorded data", - ("Failed to read (%d) recorded data, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(getErrorCode(ret), "Failed to read recorded data", + ("Failed to read (%d) recorded data, error: %d (%s)", sensor_, ret, + get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -801,44 +802,42 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity monitor->addRecordedData(&val); } - return true; // continue + return true; // continue } - PlatformResult SetOptions(sensor_recorder_option_h *option, - int interval, int retention_period) const { + PlatformResult SetOptions(sensor_recorder_option_h* option, int interval, + int retention_period) const { ScopeLogger(); int ret = SENSOR_ERROR_NONE; if (SENSOR_HRM == sensor_) { - ret = sensor_recorder_option_set_int( - *option, SENSOR_RECORDER_OPTION_INTERVAL, interval); + ret = sensor_recorder_option_set_int(*option, SENSOR_RECORDER_OPTION_INTERVAL, interval); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set recorder option", - ("Failed to set (%d) recorder option, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set recorder option", + ("Failed to set (%d) recorder option, error: %d (%s)", sensor_, + ret, get_error_message(ret))); } } - ret = sensor_recorder_option_set_int( - *option, SENSOR_RECORDER_OPTION_RETENTION_PERIOD, retention_period); + ret = sensor_recorder_option_set_int(*option, SENSOR_RECORDER_OPTION_RETENTION_PERIOD, + retention_period); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set recorder option", - ("Failed to set (%d) recorder option, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set recorder option", + ("Failed to set (%d) recorder option, error: %d (%s)", sensor_, ret, + get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult SetQuery(sensor_recorder_query_h *query_h, - const picojson::value& query) const { + PlatformResult SetQuery(sensor_recorder_query_h* query_h, const picojson::value& query) const { ScopeLogger(); - SensorRecorderQueryMap map_query { - {SENSOR_RECORDER_QUERY_START_TIME, kRecordedStartTime}, - {SENSOR_RECORDER_QUERY_END_TIME, kRecordedEndTime}, + SensorRecorderQueryMap map_query{ + {SENSOR_RECORDER_QUERY_START_TIME, kRecordedStartTime}, + {SENSOR_RECORDER_QUERY_END_TIME, kRecordedEndTime}, }; if (SENSOR_HUMAN_PEDOMETER == sensor_ || SENSOR_PRESSURE == sensor_) { @@ -853,9 +852,9 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity if (0 <= val) { int ret = sensor_recorder_query_set_time(query_h, it.first, val); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set query parameter", - ("Failed to set (%d) query parameter, error: %d (%s)", sensor_, ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set query parameter", + ("Failed to set (%d) query parameter, error: %d (%s)", + sensor_, ret, get_error_message(ret))); } } } @@ -872,7 +871,8 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor : public HumanActivity std::mutex mutex_; }; -class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMonitorManager::Monitor { +class HumanActivityMonitorManager::Monitor::GpsMonitor + : public HumanActivityMonitorManager::Monitor { public: explicit GpsMonitor(const std::string& t) : Monitor(t), handle_(nullptr) { ScopeLogger(type()); @@ -890,9 +890,9 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon int ret = 0; ret = system_info_get_platform_bool("http://tizen.org/feature/location.batch", s); if (SYSTEM_INFO_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get location.batch feature", - ("system_info_get_platform_bool error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to get location.batch feature", + ("system_info_get_platform_bool error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -905,25 +905,23 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon if (!handle_) { int ret = location_manager_create(LOCATIONS_METHOD_GPS, &handle_); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create location manager", - ("Failed to create location manager, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to create location manager", + ("Failed to create location manager, error: %d (%s)", ret, get_error_message(ret))); } - ret = location_manager_set_setting_changed_cb(LOCATIONS_METHOD_GPS, - OnGpsSettingEvent, - this); + ret = location_manager_set_setting_changed_cb(LOCATIONS_METHOD_GPS, OnGpsSettingEvent, this); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set setting listener", - ("Failed to set setting listener, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to set setting listener", + ("Failed to set setting listener, error: %d (%s)", ret, get_error_message(ret))); } } else { ret = location_manager_stop_batch(handle_); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to stop location manager", - ("Failed to stop location manager, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to stop location manager", + ("Failed to stop location manager, error: %d (%s)", ret, get_error_message(ret))); } } @@ -931,27 +929,26 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon int sample_interval = static_cast(args.get(kSampleInterval).get() / 1000); LoggerD("callbackInterval: %d, sampleInterval: %d", callback_interval, sample_interval); - ret = location_manager_set_location_batch_cb(handle_, - OnGpsEvent, - sample_interval, // batch_interval - callback_interval, // batch_period + ret = location_manager_set_location_batch_cb(handle_, OnGpsEvent, + sample_interval, // batch_interval + callback_interval, // batch_period this); if (LOCATIONS_ERROR_NONE != ret) { if (LOCATIONS_ERROR_INVALID_PARAMETER == ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Failed to set location listener", - ("Failed to set location listener, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::INVALID_VALUES_ERR, "Failed to set location listener", + ("Failed to set location listener, error: %d (%s)", ret, get_error_message(ret))); } - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set location listener", - ("Failed to set location listener, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to set location listener", + ("Failed to set location listener, error: %d (%s)", ret, get_error_message(ret))); } ret = location_manager_start_batch(handle_); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to start location manager", - ("Failed to start location manager, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to start location manager", + ("Failed to start location manager, error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -963,23 +960,24 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon if (handle_) { int ret = location_manager_stop_batch(handle_); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to stop location manager", - ("Failed to stop location manager, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to stop location manager", + ("Failed to stop location manager, error: %d (%s)", ret, get_error_message(ret))); } ret = location_manager_unset_setting_changed_cb(LOCATIONS_METHOD_GPS); if (LOCATIONS_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unset location setting changed cb", - ("Failed to unset location setting changed cb, error: %d (%s)", ret, get_error_message(ret))); + ("Failed to unset location setting changed cb, error: %d (%s)", + ret, get_error_message(ret))); } ret = location_manager_destroy(handle_); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to destroy location manager", - ("Failed to destroy location manager, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to destroy location manager", + ("Failed to destroy location manager, error: %d (%s)", ret, get_error_message(ret))); } handle_ = nullptr; @@ -992,33 +990,32 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon ScopeLogger(type()); if (!handle_) { - return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR,"SERVICE_NOT_AVAILABLE_ERR"); + return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "SERVICE_NOT_AVAILABLE_ERR"); } - double altitude = 0.0, latitude = 0.0, longitude = 0.0, climb = 0.0, - direction = 0.0, speed = 0.0, horizontal = 0.0, vertical = 0.0; + double altitude = 0.0, latitude = 0.0, longitude = 0.0, climb = 0.0, direction = 0.0, + speed = 0.0, horizontal = 0.0, vertical = 0.0; location_accuracy_level_e level = LOCATIONS_ACCURACY_NONE; time_t timestamp = 0; - int ret = location_manager_get_location(handle_, &altitude, &latitude, - &longitude, &climb, &direction, &speed, - &level, &horizontal, &vertical, - ×tamp); + int ret = + location_manager_get_location(handle_, &altitude, &latitude, &longitude, &climb, &direction, + &speed, &level, &horizontal, &vertical, ×tamp); if (LOCATIONS_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get location", - ("Failed to get location, error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to get location", + ("Failed to get location, error: %d (%s)", ret, get_error_message(ret))); } *data = picojson::value(picojson::array()); - ConvertGpsEvent(latitude, longitude, altitude, speed, direction, horizontal, - vertical, timestamp, &data->get()); + ConvertGpsEvent(latitude, longitude, altitude, speed, direction, horizontal, vertical, + timestamp, &data->get()); return PlatformResult(ErrorCode::NO_ERROR); } private: - static void OnGpsSettingEvent(location_method_e method, bool enable, void *user_data) { + static void OnGpsSettingEvent(location_method_e method, bool enable, void* user_data) { ScopeLogger(); if (LOCATIONS_METHOD_GPS != method) { @@ -1063,8 +1060,7 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon } picojson::value gps_info{picojson::array{}}; - int ret = location_manager_foreach_location_batch(monitor->handle_, - ConvertGpsEvent, + int ret = location_manager_foreach_location_batch(monitor->handle_, ConvertGpsEvent, &gps_info.get()); if (LOCATIONS_ERROR_NONE != ret) { LOGGER(ERROR) << "Failed to convert location, error: " << ret; @@ -1077,10 +1073,9 @@ class HumanActivityMonitorManager::Monitor::GpsMonitor : public HumanActivityMon callback(&out); } - static bool ConvertGpsEvent(double latitude, double longitude, double altitude, - double speed, double direction, double horizontal, - double vertical, time_t timestamp, - void* user_data) { + static bool ConvertGpsEvent(double latitude, double longitude, double altitude, double speed, + double direction, double horizontal, double vertical, + time_t timestamp, void* user_data) { ScopeLogger(); auto gps_info_array = static_cast(user_data); @@ -1119,8 +1114,7 @@ class HumanActivityMonitorManager::ActivityRecognition { activity_h handle = nullptr; int ret = activity_create(&handle); if (ACTIVITY_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create activity", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create activity", ("activity_create() error: %d - %s", ret, get_error_message(ret))); } @@ -1129,9 +1123,9 @@ class HumanActivityMonitorManager::ActivityRecognition { ret = activity_start_recognition(handle, activity_type, OnActivityRecognitionEvent, data.get()); if (ACTIVITY_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to start activity recognition", - ("activity_start_recognition() error: %d - %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to start activity recognition", + ("activity_start_recognition() error: %d - %s", ret, get_error_message(ret))); } activity_data_.insert(std::make_pair(id, data)); @@ -1155,9 +1149,7 @@ class HumanActivityMonitorManager::ActivityRecognition { private: struct ActivityData { ActivityData(long id, const JsonCallback& cb, activity_h h) - : watch_id(id), - callback(cb), - handle(h) { + : watch_id(id), callback(cb), handle(h) { } ~ActivityData() { @@ -1177,10 +1169,8 @@ class HumanActivityMonitorManager::ActivityRecognition { return ++id; } - static void OnActivityRecognitionEvent(activity_type_e type, - const activity_data_h data, - double timestamp, - activity_error_e callback_error, + static void OnActivityRecognitionEvent(activity_type_e type, const activity_data_h data, + double timestamp, activity_error_e callback_error, void* user_data) { ScopeLogger(); @@ -1189,12 +1179,13 @@ class HumanActivityMonitorManager::ActivityRecognition { picojson::value val{picojson::object{}}; auto& obj = val.get(); - obj.insert(std::make_pair("watchId", picojson::value(static_cast(activity_data->watch_id)))); + obj.insert( + std::make_pair("watchId", picojson::value(static_cast(activity_data->watch_id)))); if (ACTIVITY_ERROR_NONE != callback_error) { - LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "System operation has failed"), - &obj, - ("activity_recognition_cb() has failed with error code %d - %s", callback_error, get_error_message(callback_error))); + LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "System operation has failed"), &obj, + ("activity_recognition_cb() has failed with error code %d - %s", + callback_error, get_error_message(callback_error))); callback(&val); return; } @@ -1203,9 +1194,9 @@ class HumanActivityMonitorManager::ActivityRecognition { int ret = activity_get_accuracy(data, &accuracy); if (ret != ACTIVITY_ERROR_NONE) { - LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "System operation has failed"), - &obj, - ("activity_get_accuracy() has failed with error code %d - %s", ret, get_error_message(ret))); + LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "System operation has failed"), &obj, + ("activity_get_accuracy() has failed with error code %d - %s", ret, + get_error_message(ret))); callback(&val); return; } @@ -1232,58 +1223,56 @@ class HumanActivityMonitorManager::ActivityRecognition { int ret = activity_is_supported(type, &supported); if (ret == ACTIVITY_ERROR_NOT_SUPPORTED || !supported) { - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "Activity type is not supported", + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Activity type is not supported", ("Type %d not supported", type)); } else if (ret != ACTIVITY_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "activity_is_supported failed", - ("activity_is_supported error %d - %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "activity_is_supported failed", + ("activity_is_supported error %d - %s", ret, get_error_message(ret))); } else { return PlatformResult(ErrorCode::NO_ERROR); } } -#define ACTIVITY_TYPE_E \ +#define ACTIVITY_TYPE_E \ X(ACTIVITY_STATIONARY, "STATIONARY") \ - X(ACTIVITY_WALK, "WALKING") \ - X(ACTIVITY_RUN, "RUNNING") \ + X(ACTIVITY_WALK, "WALKING") \ + X(ACTIVITY_RUN, "RUNNING") \ X(ACTIVITY_IN_VEHICLE, "IN_VEHICLE") \ XD(static_cast(-1), "unknown") -#define ACTIVITY_ACCURACY_E \ - X(ACTIVITY_ACCURACY_LOW, "LOW") \ +#define ACTIVITY_ACCURACY_E \ + X(ACTIVITY_ACCURACY_LOW, "LOW") \ X(ACTIVITY_ACCURACY_MID, "MEDIUM") \ - X(ACTIVITY_ACCURACY_HIGH, "HIGH") \ + X(ACTIVITY_ACCURACY_HIGH, "HIGH") \ XD(static_cast(-1), "unknown") -#define X(v, s) case v: return s; -#define XD(v, s) \ - default: \ +#define X(v, s) \ + case v: \ + return s; +#define XD(v, s) \ + default: \ LoggerE("Unknown value: %d, returning default: %s", e, s); \ return s; static std::string FromActivityType(activity_type_e e) { ScopeLogger(); - switch (e) { - ACTIVITY_TYPE_E - } + switch (e) { ACTIVITY_TYPE_E } } static std::string FromActivityAccuracy(activity_accuracy_e e) { ScopeLogger(); - switch (e) { - ACTIVITY_ACCURACY_E - } + switch (e) { ACTIVITY_ACCURACY_E } } #undef X #undef XD -#define X(v, s) if (e == s) return v; -#define XD(v, s) \ +#define X(v, s) \ + if (e == s) return v; +#define XD(v, s) \ LoggerE("Unknown value: %s, returning default: %d", e.c_str(), v); \ return v; @@ -1320,28 +1309,45 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() data->insert(std::make_pair(kSpeed, picojson::value(pedometer_data->speed()))); data->insert(std::make_pair(kWalkingFrequency, picojson::value(pedometer_data->frequency()))); - data->insert(std::make_pair(kCumulativeDistance, picojson::value(pedometer_data->distance() - initial_pedometer_data.distance()))); - data->insert(std::make_pair(kCumulativeCalorie, picojson::value(pedometer_data->calories() - initial_pedometer_data.calories()))); - data->insert(std::make_pair(kCumulativeTotalStepCount, picojson::value(pedometer_data->steps() - initial_pedometer_data.steps()))); - data->insert(std::make_pair(kCumulativeWalkStepCount, picojson::value(pedometer_data->walk_steps() - initial_pedometer_data.walk_steps()))); - data->insert(std::make_pair(kCumulativeRunStepCount, picojson::value(pedometer_data->run_steps() - initial_pedometer_data.run_steps()))); - - data->insert(std::make_pair(kAccumulativeDistance, picojson::value(pedometer_data->distance()))); + data->insert(std::make_pair( + kCumulativeDistance, + picojson::value(pedometer_data->distance() - initial_pedometer_data.distance()))); + data->insert(std::make_pair( + kCumulativeCalorie, + picojson::value(pedometer_data->calories() - initial_pedometer_data.calories()))); + data->insert( + std::make_pair(kCumulativeTotalStepCount, + picojson::value(pedometer_data->steps() - initial_pedometer_data.steps()))); + data->insert(std::make_pair( + kCumulativeWalkStepCount, + picojson::value(pedometer_data->walk_steps() - initial_pedometer_data.walk_steps()))); + data->insert(std::make_pair( + kCumulativeRunStepCount, + picojson::value(pedometer_data->run_steps() - initial_pedometer_data.run_steps()))); + + data->insert( + std::make_pair(kAccumulativeDistance, picojson::value(pedometer_data->distance()))); data->insert(std::make_pair(kAccumulativeCalorie, picojson::value(pedometer_data->calories()))); - data->insert(std::make_pair(kAccumulativeTotalStepCount, picojson::value(pedometer_data->steps()))); - data->insert(std::make_pair(kAccumulativeWalkStepCount, picojson::value(pedometer_data->walk_steps()))); - data->insert(std::make_pair(kAccumulativeRunStepCount, picojson::value(pedometer_data->run_steps()))); - - auto& diffs = data->insert(std::make_pair(kStepCountDifferences, picojson::value{picojson::array{}})).first->second.get(); + data->insert( + std::make_pair(kAccumulativeTotalStepCount, picojson::value(pedometer_data->steps()))); + data->insert( + std::make_pair(kAccumulativeWalkStepCount, picojson::value(pedometer_data->walk_steps()))); + data->insert( + std::make_pair(kAccumulativeRunStepCount, picojson::value(pedometer_data->run_steps()))); + + auto& diffs = + data->insert(std::make_pair(kStepCountDifferences, picojson::value{picojson::array{}})) + .first->second.get(); LOGGER(DEBUG) << " pedometer_data->diffs_coun: " << pedometer_data->diffs_count; if (pedometer_data->diffs_count > 0) { for (int i = 0; i < pedometer_data->diffs_count; ++i) { InsertStepDifference(pedometer_data->diffs[i].steps, - getCurrentTimeStamp(pedometer_data->diffs[i].timestamp) / 1000, &diffs); + getCurrentTimeStamp(pedometer_data->diffs[i].timestamp) / 1000, + &diffs); } } else { InsertStepDifference(steps_so_far > 0.0 ? pedometer_data->steps() - steps_so_far : 0.0, - getCurrentTimeStamp(pedometer_data->timestamp) / 1000, &diffs); + getCurrentTimeStamp(pedometer_data->timestamp) / 1000, &diffs); } steps_so_far = pedometer_data->steps(); @@ -1364,14 +1370,13 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() LOGGER(DEBUG) << " |- values[0]: " << event->values[0]; LOGGER(DEBUG) << " |- values[1]: " << event->values[1]; - float hr = floor( event->values[0] + 0.5); // heart beat rate 0 ~ 220 integer (bpm) + float hr = floor(event->values[0] + 0.5); // heart beat rate 0 ~ 220 integer (bpm) // there are no public native api for peak to peak interval. // but RRI = (60 / HR) * 1000 // or unofficially values[1] is rri (0 ~ 5000 ms) float rri = floor(event->values[1] + 0.5); - data->insert(std::make_pair("heartRate", picojson::value(static_cast(hr)))); data->insert(std::make_pair("rRInterval", picojson::value(static_cast(rri)))); @@ -1402,13 +1407,13 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() break; default: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown sleep state", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown sleep state", ("Unknown sleep state: %d", state)); } data->insert(std::make_pair(kStatus, picojson::value(sleep_state))); - data->insert(std::make_pair(kTimestamp, picojson::value(static_cast(getCurrentTimeStamp(event->timestamp))))); + data->insert(std::make_pair( + kTimestamp, picojson::value(static_cast(getCurrentTimeStamp(event->timestamp))))); return PlatformResult(ErrorCode::NO_ERROR); }; @@ -1416,16 +1421,12 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() auto convert_recorded_pedometer = [](void* data, picojson::object* obj) -> PlatformResult { ScopeLogger("convert_recorded_pedometer"); - SensorRecorderDataMap map_int { - {SENSOR_RECORDER_DATA_STEPS, kRecordedTotalStepCount}, - {SENSOR_RECORDER_DATA_WALK_STEPS, kRecordedWalkStepCount}, - {SENSOR_RECORDER_DATA_RUN_STEPS, kRecordedRunStepCount} - }; + SensorRecorderDataMap map_int{{SENSOR_RECORDER_DATA_STEPS, kRecordedTotalStepCount}, + {SENSOR_RECORDER_DATA_WALK_STEPS, kRecordedWalkStepCount}, + {SENSOR_RECORDER_DATA_RUN_STEPS, kRecordedRunStepCount}}; - SensorRecorderDataMap map_double { - {SENSOR_RECORDER_DATA_DISTANCE, kRecordedDistance}, - {SENSOR_RECORDER_DATA_CALORIE, kRecordedCalorie} - }; + SensorRecorderDataMap map_double{{SENSOR_RECORDER_DATA_DISTANCE, kRecordedDistance}, + {SENSOR_RECORDER_DATA_CALORIE, kRecordedCalorie}}; auto result = ConvertRecordedInt(data, obj, map_int); if (!result) { @@ -1443,8 +1444,8 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() auto convert_recorded_hrm = [](void* data, picojson::object* obj) -> PlatformResult { ScopeLogger("convert_recorded_hrm"); - SensorRecorderDataMap map_int { - {SENSOR_RECORDER_DATA_HEART_RATE, kRecordedHeartRate}, + SensorRecorderDataMap map_int{ + {SENSOR_RECORDER_DATA_HEART_RATE, kRecordedHeartRate}, }; auto result = ConvertRecordedInt(data, obj, map_int); @@ -1458,9 +1459,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() auto convert_recorded_sleep_monitor = [](void* data, picojson::object* obj) -> PlatformResult { ScopeLogger("convert_recorded_sleep_monitor"); - SensorRecorderDataMap map_int { - {SENSOR_RECORDER_DATA_SLEEP_STATE, kStatus} - }; + SensorRecorderDataMap map_int{{SENSOR_RECORDER_DATA_SLEEP_STATE, kStatus}}; auto result = ConvertRecordedInt(data, obj, map_int); if (!result) { @@ -1473,11 +1472,9 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() auto convert_recorded_pressure = [](void* data, picojson::object* obj) -> PlatformResult { ScopeLogger("convert_recorded_pressure"); - SensorRecorderDataMap map_double { - {SENSOR_RECORDER_DATA_MAX_PRESSURE, kRecordedMax}, - {SENSOR_RECORDER_DATA_MIN_PRESSURE, kRecordedMin}, - {SENSOR_RECORDER_DATA_AVERAGE_PRESSURE, kRecordedAverage} - }; + SensorRecorderDataMap map_double{{SENSOR_RECORDER_DATA_MAX_PRESSURE, kRecordedMax}, + {SENSOR_RECORDER_DATA_MIN_PRESSURE, kRecordedMin}, + {SENSOR_RECORDER_DATA_AVERAGE_PRESSURE, kRecordedAverage}}; auto result = ConvertRecordedDouble(data, obj, map_double); if (!result) { @@ -1487,12 +1484,24 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() return ConvertRecordedTime(data, obj); }; - monitors_.insert(std::make_pair(kActivityTypePedometer, std::make_shared(kActivityTypePedometer, SENSOR_HUMAN_PEDOMETER, convert_pedometer, convert_recorded_pedometer))); - monitors_.insert(std::make_pair(kActivityTypeWristUp, std::make_shared(kActivityTypeWristUp))); - monitors_.insert(std::make_pair(kActivityTypeHrm, std::make_shared(kActivityTypeHrm, SENSOR_HRM, convert_hrm, convert_recorded_hrm))); - monitors_.insert(std::make_pair(kActivityTypeGps, std::make_shared(kActivityTypeGps))); - monitors_.insert(std::make_pair(kActivityTypeSleepMonitor, std::make_shared(kActivityTypeSleepMonitor, SENSOR_HUMAN_SLEEP_MONITOR, convert_sleep, convert_recorded_sleep_monitor))); - monitors_.insert(std::make_pair(kActivityTypePressure, std::make_shared(kActivityTypePressure, SENSOR_PRESSURE, nullptr, convert_recorded_pressure))); + monitors_.insert(std::make_pair( + kActivityTypePedometer, + std::make_shared(kActivityTypePedometer, SENSOR_HUMAN_PEDOMETER, + convert_pedometer, convert_recorded_pedometer))); + monitors_.insert(std::make_pair(kActivityTypeWristUp, + std::make_shared(kActivityTypeWristUp))); + monitors_.insert(std::make_pair( + kActivityTypeHrm, std::make_shared( + kActivityTypeHrm, SENSOR_HRM, convert_hrm, convert_recorded_hrm))); + monitors_.insert( + std::make_pair(kActivityTypeGps, std::make_shared(kActivityTypeGps))); + monitors_.insert(std::make_pair(kActivityTypeSleepMonitor, + std::make_shared( + kActivityTypeSleepMonitor, SENSOR_HUMAN_SLEEP_MONITOR, + convert_sleep, convert_recorded_sleep_monitor))); + monitors_.insert(std::make_pair(kActivityTypePressure, std::make_shared( + kActivityTypePressure, SENSOR_PRESSURE, + nullptr, convert_recorded_pressure))); } HumanActivityMonitorManager::~HumanActivityMonitorManager() { @@ -1504,31 +1513,31 @@ PlatformResult HumanActivityMonitorManager::Init() { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult HumanActivityMonitorManager::IsSupported( const std::string& type ) { +PlatformResult HumanActivityMonitorManager::IsSupported(const std::string& type) { return this->GetMonitor(type)->IsSupported(); } -PlatformResult HumanActivityMonitorManager::SetListener( - const std::string& type, JsonCallback callback, - const picojson::value& args) { +PlatformResult HumanActivityMonitorManager::SetListener(const std::string& type, + JsonCallback callback, + const picojson::value& args) { ScopeLogger(); return GetMonitor(type)->SetListener(callback, args); } -PlatformResult HumanActivityMonitorManager::UnsetListener( - const std::string& type) { +PlatformResult HumanActivityMonitorManager::UnsetListener(const std::string& type) { ScopeLogger(); return GetMonitor(type)->UnsetListener(); } -PlatformResult HumanActivityMonitorManager::GetHumanActivityData( - const std::string& type, picojson::value* data) { +PlatformResult HumanActivityMonitorManager::GetHumanActivityData(const std::string& type, + picojson::value* data) { ScopeLogger(); return GetMonitor(type)->GetData(data); } -PlatformResult HumanActivityMonitorManager::AddActivityRecognitionListener( - const std::string& type, JsonCallback callback, long* watch_id) { +PlatformResult HumanActivityMonitorManager::AddActivityRecognitionListener(const std::string& type, + JsonCallback callback, + long* watch_id) { ScopeLogger(); return activity_recognition_->AddListener(type, callback, watch_id); } @@ -1538,8 +1547,8 @@ PlatformResult HumanActivityMonitorManager::RemoveActivityRecognitionListener(co return activity_recognition_->RemoveListener(watch_id); } -PlatformResult HumanActivityMonitorManager::StartDataRecorder(const std::string& type, - int interval, int retention_period) { +PlatformResult HumanActivityMonitorManager::StartDataRecorder(const std::string& type, int interval, + int retention_period) { ScopeLogger(); return GetMonitor(type)->StartDataRecorder(interval, retention_period); } @@ -1549,13 +1558,15 @@ PlatformResult HumanActivityMonitorManager::StopDataRecorder(const std::string& return GetMonitor(type)->StopDataRecorder(); } -PlatformResult HumanActivityMonitorManager::ReadRecorderData( - const std::string& type, picojson::array* data, const picojson::value& query) { +PlatformResult HumanActivityMonitorManager::ReadRecorderData(const std::string& type, + picojson::array* data, + const picojson::value& query) { ScopeLogger(); return GetMonitor(type)->ReadRecorderData(data, query); } -std::shared_ptr HumanActivityMonitorManager::GetMonitor(const std::string& type) { +std::shared_ptr HumanActivityMonitorManager::GetMonitor( + const std::string& type) { ScopeLogger(); const auto it = monitors_.find(type); diff --git a/src/humanactivitymonitor/humanactivitymonitor_manager.h b/src/humanactivitymonitor/humanactivitymonitor_manager.h old mode 100755 new mode 100644 index 8cd82be..0db67d1 --- a/src/humanactivitymonitor/humanactivitymonitor_manager.h +++ b/src/humanactivitymonitor/humanactivitymonitor_manager.h @@ -39,24 +39,20 @@ class HumanActivityMonitorManager { common::PlatformResult Init(); /* checks if given HumanActivityRecorderType is supported */ - common::PlatformResult IsSupported( const std::string& type ); + common::PlatformResult IsSupported(const std::string& type); - common::PlatformResult SetListener(const std::string& type, - JsonCallback callback, + common::PlatformResult SetListener(const std::string& type, JsonCallback callback, const picojson::value& args); common::PlatformResult UnsetListener(const std::string& type); - common::PlatformResult GetHumanActivityData(const std::string& type, - picojson::value* data); + common::PlatformResult GetHumanActivityData(const std::string& type, picojson::value* data); common::PlatformResult AddActivityRecognitionListener(const std::string& type, - JsonCallback callback, - long* watch_id); + JsonCallback callback, long* watch_id); common::PlatformResult RemoveActivityRecognitionListener(const long watchId); - common::PlatformResult StartDataRecorder(const std::string& type, - int interval, int retention_period); + common::PlatformResult StartDataRecorder(const std::string& type, int interval, + int retention_period); common::PlatformResult StopDataRecorder(const std::string& type); - common::PlatformResult ReadRecorderData(const std::string& type, - picojson::array* data, + common::PlatformResult ReadRecorderData(const std::string& type, picojson::array* data, const picojson::value& query); private: @@ -69,7 +65,7 @@ class HumanActivityMonitorManager { std::shared_ptr activity_recognition_; }; -} // namespace humanactivitymonitor -} // namespace extension +} // namespace humanactivitymonitor +} // namespace extension -#endif // HUMANACTIVITYMONITOR_HUMANACTIVITYMONITOR_MANAGER_H +#endif // HUMANACTIVITYMONITOR_HUMANACTIVITYMONITOR_MANAGER_H diff --git a/src/inputdevice/inputdevice_extension.cc b/src/inputdevice/inputdevice_extension.cc index cf59eab..2ccc78d 100644 --- a/src/inputdevice/inputdevice_extension.cc +++ b/src/inputdevice/inputdevice_extension.cc @@ -12,19 +12,20 @@ namespace extension { namespace inputdevice { InputDeviceExtension::InputDeviceExtension() { - SetExtensionName("tizen.inputdevice"); - SetJavaScriptAPI(kSource_inputdevice_api); + SetExtensionName("tizen.inputdevice"); + SetJavaScriptAPI(kSource_inputdevice_api); } -InputDeviceExtension::~InputDeviceExtension() {} +InputDeviceExtension::~InputDeviceExtension() { +} common::Instance* InputDeviceExtension::CreateInstance() { - return new InputDeviceInstance; + return new InputDeviceInstance; } } // namespace inputdevice } // namespace extension common::Extension* CreateExtension() { - return new extension::inputdevice::InputDeviceExtension; + return new extension::inputdevice::InputDeviceExtension; } diff --git a/src/inputdevice/inputdevice_extension.h b/src/inputdevice/inputdevice_extension.h index ae38ead..bd00230 100644 --- a/src/inputdevice/inputdevice_extension.h +++ b/src/inputdevice/inputdevice_extension.h @@ -12,15 +12,14 @@ namespace inputdevice { class InputDeviceExtension : public common::Extension { public: - InputDeviceExtension(); - virtual ~InputDeviceExtension(); + InputDeviceExtension(); + virtual ~InputDeviceExtension(); private: - virtual common::Instance* CreateInstance(); + virtual common::Instance* CreateInstance(); }; } // namespace inputdevice } // namespace extension #endif // SRC_INPUTDEVICE_INPUTDEVICE_EXTENSION_H_ - diff --git a/src/inputdevice/inputdevice_instance.cc b/src/inputdevice/inputdevice_instance.cc index ae3f954..91d3084 100644 --- a/src/inputdevice/inputdevice_instance.cc +++ b/src/inputdevice/inputdevice_instance.cc @@ -13,21 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "../inputdevice/inputdevice_instance.h" #include "common/logger.h" - namespace extension { namespace inputdevice { InputDeviceInstance::InputDeviceInstance() { - LoggerD("Enter"); + LoggerD("Enter"); } InputDeviceInstance::~InputDeviceInstance() { - LoggerD("Enter"); + LoggerD("Enter"); } } // namespace inputdevice diff --git a/src/inputdevice/inputdevice_instance.h b/src/inputdevice/inputdevice_instance.h index c09b16a..085738c 100644 --- a/src/inputdevice/inputdevice_instance.h +++ b/src/inputdevice/inputdevice_instance.h @@ -17,17 +17,16 @@ #ifndef SRC_INPUTDEVICE_INPUTDEVICE_INSTANCE_H_ #define SRC_INPUTDEVICE_INPUTDEVICE_INSTANCE_H_ -#include "common/picojson.h" #include "common/extension.h" - +#include "common/picojson.h" namespace extension { namespace inputdevice { class InputDeviceInstance : public common::ParsedInstance { public: - InputDeviceInstance(); - virtual ~InputDeviceInstance(); + InputDeviceInstance(); + virtual ~InputDeviceInstance(); private: }; diff --git a/src/iotcon/iotcon_client_manager.cc b/src/iotcon/iotcon_client_manager.cc index 7ecd9bb..bfa83fe 100644 --- a/src/iotcon/iotcon_client_manager.cc +++ b/src/iotcon/iotcon_client_manager.cc @@ -43,13 +43,11 @@ IotconClientManager& IotconClientManager::GetInstance() { return instance; } -void IotconClientManager::PresenceHandler(iotcon_presence_h presence, - iotcon_error_e err, - iotcon_presence_response_h response, - void *user_data) { +void IotconClientManager::PresenceHandler(iotcon_presence_h presence, iotcon_error_e err, + iotcon_presence_response_h response, void* user_data) { ScopeLogger(); - if(IOTCON_ERROR_NONE != err) { + if (IOTCON_ERROR_NONE != err) { LoggerE("Error in presence event callback!"); return; } @@ -59,8 +57,7 @@ void IotconClientManager::PresenceHandler(iotcon_presence_h presence, if (p.second->presence_listener && p.second->handle == presence) { picojson::value value{picojson::object{}}; auto& obj = value.get(); - auto ret = IotconUtils::PresenceResponseToJson(response, - &obj); + auto ret = IotconUtils::PresenceResponseToJson(response, &obj); if (!ret) { LoggerE("PresenceResponseToJson() failed"); return; @@ -72,13 +69,12 @@ void IotconClientManager::PresenceHandler(iotcon_presence_h presence, }; common::TizenResult IotconClientManager::AddPresenceEventListener( - const char* host, const iotcon_connectivity_type_e con_type_e, - const char* resource_type, PresenceEventPtr presence) { + const char* host, const iotcon_connectivity_type_e con_type_e, const char* resource_type, + PresenceEventPtr presence) { ScopeLogger(); auto result = IotconUtils::ConvertIotconError(iotcon_add_presence_cb( - host, con_type_e, resource_type, PresenceHandler, this, - &(presence->handle))); + host, con_type_e, resource_type, PresenceHandler, this, &(presence->handle))); // storing PresenceEvent into map presence->id = GetPresenceNextId(); @@ -151,6 +147,5 @@ TizenResult IotconClientManager::GetRemoteById(long long id, return TizenSuccess(); } - } // namespace iotcon } // namespace extension diff --git a/src/iotcon/iotcon_client_manager.h b/src/iotcon/iotcon_client_manager.h index 9b06b13..56bd87e 100644 --- a/src/iotcon/iotcon_client_manager.h +++ b/src/iotcon/iotcon_client_manager.h @@ -17,10 +17,10 @@ #ifndef WEBAPI_PLUGINS_IOTCON_CLIENT_MANAGER_H__ #define WEBAPI_PLUGINS_IOTCON_CLIENT_MANAGER_H__ -#include +#include #include +#include #include -#include #include "iotcon/iotcon_utils.h" @@ -50,16 +50,14 @@ class IotconClientManager { IotconClientManager& operator=(const IotconClientManager&) = delete; IotconClientManager& operator=(IotconClientManager&&) = delete; - static void PresenceHandler(iotcon_presence_h resource, - iotcon_error_e err, - iotcon_presence_response_h response, - void *user_data); + static void PresenceHandler(iotcon_presence_h resource, iotcon_error_e err, + iotcon_presence_response_h response, void* user_data); PresenceMap presence_map_; FoundRemotesMap remotes_map_; }; -} // namespace iotcon -} // namespace extension +} // namespace iotcon +} // namespace extension -#endif // WEBAPI_PLUGINS_IOTCON_CLIENT_MANAGER_H__ +#endif // WEBAPI_PLUGINS_IOTCON_CLIENT_MANAGER_H__ diff --git a/src/iotcon/iotcon_extension.cc b/src/iotcon/iotcon_extension.cc index 3f8d161..168b426 100644 --- a/src/iotcon/iotcon_extension.cc +++ b/src/iotcon/iotcon_extension.cc @@ -28,15 +28,13 @@ IotconExtension::IotconExtension() { SetExtensionName("tizen.iotcon"); SetJavaScriptAPI(kSource_iotcon_api); - const char* entry_points[] = { - "tizen.IotconOption", - "tizen.Query", - "tizen.QueryFilter", - "tizen.Representation", - "tizen.Response", - "tizen.State", - nullptr - }; + const char* entry_points[] = {"tizen.IotconOption", + "tizen.Query", + "tizen.QueryFilter", + "tizen.Representation", + "tizen.Response", + "tizen.State", + nullptr}; SetExtraJSEntryPoints(entry_points); } diff --git a/src/iotcon/iotcon_extension.h b/src/iotcon/iotcon_extension.h index 13b210c..c80080e 100644 --- a/src/iotcon/iotcon_extension.h +++ b/src/iotcon/iotcon_extension.h @@ -35,4 +35,3 @@ class IotconExtension : public common::Extension { } // namespace extension #endif // IOTCON_IOTCON_EXTENSION_H_ - diff --git a/src/iotcon/iotcon_instance.cc b/src/iotcon/iotcon_instance.cc index 1166063..9b31a3e 100644 --- a/src/iotcon/iotcon_instance.cc +++ b/src/iotcon/iotcon_instance.cc @@ -22,10 +22,10 @@ #include "common/scope_exit.h" #include "common/tools.h" -#include "iotcon/iotcon_utils.h" +#include "iotcon/iotcon_client_manager.h" #include "iotcon/iotcon_manager.h" #include "iotcon/iotcon_server_manager.h" -#include "iotcon/iotcon_client_manager.h" +#include "iotcon/iotcon_utils.h" #include "common/filesystem/filesystem_provider.h" @@ -41,17 +41,15 @@ struct CallbackData { struct CallbackData2 { common::PostCallback fun; - bool callback_called; + bool callback_called; }; long long GetId(const picojson::object& args) { return static_cast(args.find(kId)->second.get()); } -void RemoteResourceResponseCallback(iotcon_remote_resource_h resource, - iotcon_error_e err, - iotcon_request_type_e request_type, - iotcon_response_h response, +void RemoteResourceResponseCallback(iotcon_remote_resource_h resource, iotcon_error_e err, + iotcon_request_type_e request_type, iotcon_response_h response, void* user_data) { ScopeLogger(); @@ -62,15 +60,15 @@ void RemoteResourceResponseCallback(iotcon_remote_resource_h resource, common::TizenResult ret = common::TizenSuccess(); switch (err) { - case IOTCON_ERROR_NONE: - ret = IotconUtils::ResponseToJson(response, &value.get()); - break; - case IOTCON_ERROR_TIMEOUT: - LoggerD("IOTCON_TIMEOUT "); - default: - ret = IotconUtils::ConvertIotconError(err); - } - data->fun(ret, value); + case IOTCON_ERROR_NONE: + ret = IotconUtils::ResponseToJson(response, &value.get()); + break; + case IOTCON_ERROR_TIMEOUT: + LoggerD("IOTCON_TIMEOUT "); + default: + ret = IotconUtils::ConvertIotconError(err); + } + data->fun(ret, value); } else { LoggerE("Native callback data is null"); } @@ -82,12 +80,9 @@ const common::ListenerToken kFindResourceListenerToken{"FindResourceListener"}; const common::ListenerToken kFindDeviceInfoListenerToken{"FindDeviceInfoListener"}; const common::ListenerToken kFindPlatformInfoListenerToken{"FindPlatformInfoListener"}; const common::ListenerToken kPresenceEventListenerToken{"PresenceEventListener"}; -const common::ListenerToken kRemoteResourceStateChangeListener - {"RemoteResourceStateChangeListener"}; -const common::ListenerToken kRemoteResourceChangeListener - {"RemoteResourceChangeListener"}; -const common::ListenerToken kRemoteResourceCacheChangeListener - {"RemoteResourceCacheChangeListener"}; +const common::ListenerToken kRemoteResourceStateChangeListener{"RemoteResourceStateChangeListener"}; +const common::ListenerToken kRemoteResourceChangeListener{"RemoteResourceChangeListener"}; +const common::ListenerToken kRemoteResourceCacheChangeListener{"RemoteResourceCacheChangeListener"}; const std::string kObserverIds = "observerIds"; const std::string kQos = "qos"; @@ -112,14 +107,12 @@ IotconInstance::IotconInstance() observing_started_(false), caching_started_(false), monitoring_started_(false) { - ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&IotconInstance::x, this, _1)) +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&IotconInstance::x, this, _1)) REGISTER_SYNC("IotconResource_getObserverIds", ResourceGetObserverIds); REGISTER_SYNC("IotconResource_notify", ResourceNotify); @@ -130,15 +123,18 @@ IotconInstance::IotconInstance() REGISTER_SYNC("IotconResource_setRequestListener", ResourceSetRequestListener); REGISTER_SYNC("IotconResource_unsetRequestListener", ResourceUnsetRequestListener); REGISTER_SYNC("IotconResponse_send", ResponseSend); - REGISTER_SYNC("IotconRemoteResource_getCachedRepresentation", RemoteResourceGetCachedRepresentation); + REGISTER_SYNC("IotconRemoteResource_getCachedRepresentation", + RemoteResourceGetCachedRepresentation); REGISTER_SYNC("IotconRemoteResource_getOptions", RemoteResourceGetOptions); REGISTER_SYNC("IotconRemoteResource_setOptions", RemoteResourceSetOptions); REGISTER_SYNC("IotconRemoteResource_startObserving", RemoteResourceStartObserving); REGISTER_SYNC("IotconRemoteResource_stopObserving", RemoteResourceStopObserving); REGISTER_SYNC("IotconRemoteResource_startCaching", RemoteResourceStartCaching); REGISTER_SYNC("IotconRemoteResource_stopCaching", RemoteResourceStopCaching); - REGISTER_SYNC("IotconRemoteResource_setResourceStateChangeListener", RemoteResourceSetResourceStateChangeListener); - REGISTER_SYNC("IotconRemoteResource_unsetResourceStateChangeListener", RemoteResourceUnsetResourceStateChangeListener); + REGISTER_SYNC("IotconRemoteResource_setResourceStateChangeListener", + RemoteResourceSetResourceStateChangeListener); + REGISTER_SYNC("IotconRemoteResource_unsetResourceStateChangeListener", + RemoteResourceUnsetResourceStateChangeListener); REGISTER_SYNC("IotconRemoteResource_getTimeInterval", RemoteResourceGetTimeInterval); REGISTER_SYNC("IotconRemoteResource_setTimeInterval", RemoteResourceSetTimeInterval); REGISTER_SYNC("IotconClient_addPresenceEventListener", ClientAddPresenceEventListener); @@ -158,8 +154,7 @@ IotconInstance::IotconInstance() REGISTER_SYNC("IotconClient_findPlatformInfo", ClientFindPlatformInfo); #undef REGISTER_SYNC -#define REGISTER_ASYNC(c, x) \ - RegisterHandler(c, std::bind(&IotconInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterHandler(c, std::bind(&IotconInstance::x, this, _1, _2)); REGISTER_ASYNC("IotconRemoteResource_methodGet", RemoteResourceMethodGet); REGISTER_ASYNC("IotconRemoteResource_methodPut", RemoteResourceMethodPut); @@ -270,7 +265,8 @@ common::TizenResult IotconInstance::ResourceNotify(const picojson::object& args) // create representation from resource and attributes iotcon_representation_h representation = nullptr; - result = IotconUtils::RepresentationFromResource(resource, IotconUtils::GetArg(args, kAttributes), &representation); + result = IotconUtils::RepresentationFromResource(resource, IotconUtils::GetArg(args, kAttributes), + &representation); if (!result) { LogAndReturnTizenError(result, ("RepresentationFromResource() failed")); } @@ -279,7 +275,9 @@ common::TizenResult IotconInstance::ResourceNotify(const picojson::object& args) iotcon_representation_destroy(representation); }; - result = IotconUtils::ConvertIotconError(iotcon_resource_notify(resource->handle, representation, observers_handle, IotconUtils::ToQos(qos.get()))); + result = IotconUtils::ConvertIotconError( + iotcon_resource_notify(resource->handle, representation, observers_handle, + IotconUtils::ToQos(qos.get()))); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_notify() failed")); } @@ -306,8 +304,8 @@ common::TizenResult IotconInstance::ResourceAddResourceTypes(const picojson::obj for (const auto& type : types) { int ret = iotcon_resource_bind_type(resource->handle, type.get().c_str()); if (IOTCON_ERROR_NONE != ret && IOTCON_ERROR_ALREADY != ret) { - LogAndReturnTizenError( - IotconUtils::ConvertIotconError(ret), ("iotcon_resource_bind_type() failed")); + LogAndReturnTizenError(IotconUtils::ConvertIotconError(ret), + ("iotcon_resource_bind_type() failed")); } } @@ -331,8 +329,8 @@ common::TizenResult IotconInstance::ResourceAddResourceInterface(const picojson: int ret = iotcon_resource_bind_interface( resource->handle, IotconUtils::GetArg(args, kInterface).get().c_str()); if (IOTCON_ERROR_NONE != ret && IOTCON_ERROR_ALREADY != ret) { - LogAndReturnTizenError( - IotconUtils::ConvertIotconError(ret), ("iotcon_resource_bind_interface() failed")); + LogAndReturnTizenError(IotconUtils::ConvertIotconError(ret), + ("iotcon_resource_bind_interface() failed")); } return common::TizenSuccess(); @@ -362,8 +360,8 @@ common::TizenResult IotconInstance::ResourceAddChildResource(const picojson::obj int ret = iotcon_resource_bind_child_resource(parent->handle, child->handle); if (IOTCON_ERROR_NONE != ret && IOTCON_ERROR_ALREADY != ret) { - LogAndReturnTizenError( - IotconUtils::ConvertIotconError(ret), ("iotcon_resource_bind_child_resource() failed")); + LogAndReturnTizenError(IotconUtils::ConvertIotconError(ret), + ("iotcon_resource_bind_child_resource() failed")); } parent->children.insert(child); @@ -394,7 +392,8 @@ common::TizenResult IotconInstance::ResourceRemoveChildResource(const picojson:: LogAndReturnTizenError(result, ("GetResourceById() failed")); } - result = IotconUtils::ConvertIotconError(iotcon_resource_unbind_child_resource(parent->handle, child->handle)); + result = IotconUtils::ConvertIotconError( + iotcon_resource_unbind_child_resource(parent->handle, child->handle)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_unbind_child_resource() failed")); } @@ -419,8 +418,7 @@ common::TizenResult IotconInstance::ResourceSetRequestListener(const picojson::o } if (!resource->request_listener) { - resource->request_listener = [this, id](const common::TizenResult&, - const picojson::value& v) { + resource->request_listener = [this, id](const common::TizenResult&, const picojson::value& v) { picojson::value request{picojson::object{}}; auto& obj = request.get(); @@ -470,9 +468,11 @@ common::TizenResult IotconInstance::ResponseSend(const picojson::object& args) { if (!js_response_result.is()) { return LogAndCreateTizenError(TypeMismatchError, "ResponseResult should be a string"); } - iotcon_response_result_e response_result = IotconUtils::ToResponseResult(js_response_result.get()); + iotcon_response_result_e response_result = + IotconUtils::ToResponseResult(js_response_result.get()); - result = IotconUtils::ConvertIotconError(iotcon_response_set_result(response.get(), response_result)); + result = IotconUtils::ConvertIotconError( + iotcon_response_set_result(response.get(), response_result)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_result() failed")); } @@ -484,7 +484,8 @@ common::TizenResult IotconInstance::ResponseSend(const picojson::object& args) { return LogAndCreateTizenError(TypeMismatchError, "Representation should be an object"); } iotcon_representation_h representation = nullptr; - result = IotconUtils::RepresentationFromJson(js_representation.get(), &representation); + result = IotconUtils::RepresentationFromJson(js_representation.get(), + &representation); if (!result) { LogAndReturnTizenError(result, ("RepresentationFromJson() failed")); } @@ -493,9 +494,7 @@ common::TizenResult IotconInstance::ResponseSend(const picojson::object& args) { }; result = IotconUtils::ConvertIotconError( - iotcon_response_set_representation( - response.get(), - representation)); + iotcon_response_set_representation(response.get(), representation)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_representation() failed")); } @@ -515,7 +514,8 @@ common::TizenResult IotconInstance::ResponseSend(const picojson::object& args) { iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_response_set_options(response.get(), options)); + result = + IotconUtils::ConvertIotconError(iotcon_response_set_options(response.get(), options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } @@ -530,7 +530,8 @@ common::TizenResult IotconInstance::ResponseSend(const picojson::object& args) { return common::TizenSuccess(); } -common::TizenResult IotconInstance::RemoteResourceGetCachedRepresentation(const picojson::object& args) { +common::TizenResult IotconInstance::RemoteResourceGetCachedRepresentation( + const picojson::object& args) { ScopeLogger(); FoundRemoteInfoPtr ptr; @@ -565,8 +566,7 @@ common::TizenResult IotconInstance::RemoteResourceGetOptions(const picojson::obj } iotcon_options_h options = nullptr; - res = IotconUtils::ConvertIotconError( - iotcon_remote_resource_get_options(ptr->handle, &options)); + res = IotconUtils::ConvertIotconError(iotcon_remote_resource_get_options(ptr->handle, &options)); if (!res) { LogAndReturnTizenError(res, ("Gathering options failed")); } @@ -655,13 +655,15 @@ common::TizenResult IotconInstance::RemoteResourceMethodGet(const picojson::obje iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(resource->handle, options)); + result = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_options(resource->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } } - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_get(resource->handle, query, RemoteResourceResponseCallback, data.get())); + result = IotconUtils::ConvertIotconError(iotcon_remote_resource_get( + resource->handle, query, RemoteResourceResponseCallback, data.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_remote_resource_get() failed")); } @@ -687,7 +689,8 @@ common::TizenResult IotconInstance::RemoteResourceMethodPut(const picojson::obje } iotcon_representation_h representation = nullptr; - result = IotconUtils::RepresentationFromJson(IotconUtils::GetArg(args, kRepresentation).get(), &representation); + result = IotconUtils::RepresentationFromJson( + IotconUtils::GetArg(args, kRepresentation).get(), &representation); if (!result) { LogAndReturnTizenError(result, ("RepresentationFromJson() failed")); } @@ -725,13 +728,15 @@ common::TizenResult IotconInstance::RemoteResourceMethodPut(const picojson::obje iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(resource->handle, options)); + result = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_options(resource->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } } - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_put(resource->handle, representation, query, RemoteResourceResponseCallback, data.get())); + result = IotconUtils::ConvertIotconError(iotcon_remote_resource_put( + resource->handle, representation, query, RemoteResourceResponseCallback, data.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_remote_resource_put() failed")); } @@ -757,7 +762,8 @@ common::TizenResult IotconInstance::RemoteResourceMethodPost(const picojson::obj } iotcon_representation_h representation = nullptr; - result = IotconUtils::RepresentationFromJson(IotconUtils::GetArg(args, kRepresentation).get(), &representation); + result = IotconUtils::RepresentationFromJson( + IotconUtils::GetArg(args, kRepresentation).get(), &representation); if (!result) { LogAndReturnTizenError(result, ("RepresentationFromJson() failed")); } @@ -795,13 +801,15 @@ common::TizenResult IotconInstance::RemoteResourceMethodPost(const picojson::obj iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(resource->handle, options)); + result = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_options(resource->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } } - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_post(resource->handle, representation, query, RemoteResourceResponseCallback, data.get())); + result = IotconUtils::ConvertIotconError(iotcon_remote_resource_post( + resource->handle, representation, query, RemoteResourceResponseCallback, data.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_remote_resource_post() failed")); } @@ -840,13 +848,15 @@ common::TizenResult IotconInstance::RemoteResourceMethodDelete(const picojson::o iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(resource->handle, options)); + result = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_options(resource->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } } - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_delete(resource->handle, RemoteResourceResponseCallback, data.get())); + result = IotconUtils::ConvertIotconError( + iotcon_remote_resource_delete(resource->handle, RemoteResourceResponseCallback, data.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_remote_resource_delete() failed")); } @@ -858,7 +868,7 @@ common::TizenResult IotconInstance::RemoteResourceMethodDelete(const picojson::o } static void ObserveCallback(iotcon_remote_resource_h resource, iotcon_error_e err, - int sequence_number, iotcon_response_h response, void *user_data) { + int sequence_number, iotcon_response_h response, void* user_data) { ScopeLogger(); FoundRemoteInfo* ptr = static_cast(user_data); if (nullptr == ptr) { @@ -894,7 +904,7 @@ common::TizenResult IotconInstance::RemoteResourceStartObserving(const picojson: const auto& query_it = args.find(kQuery); if (args.end() != query_it) { result = IotconUtils::QueryFromJson(query_it->second.get(), &query); - if (!result){ + if (!result) { return result; } } @@ -904,8 +914,8 @@ common::TizenResult IotconInstance::RemoteResourceStartObserving(const picojson: } }; - iotcon_observe_policy_e observe_policy = IotconUtils::ToObservePolicy( - args.find(kObservePolicy)->second.get().c_str()); + iotcon_observe_policy_e observe_policy = + IotconUtils::ToObservePolicy(args.find(kObservePolicy)->second.get().c_str()); ptr->observe_listener = [this, ptr](const common::TizenResult& res, const picojson::value& v) { picojson::value response{picojson::object{}}; @@ -931,15 +941,15 @@ common::TizenResult IotconInstance::RemoteResourceStartObserving(const picojson: iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(ptr->handle, options)); + result = + IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(ptr->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } } - result = IotconUtils::ConvertIotconError( - iotcon_remote_resource_observe_register(ptr->handle, observe_policy, query, - ObserveCallback, ptr.get())); + result = IotconUtils::ConvertIotconError(iotcon_remote_resource_observe_register( + ptr->handle, observe_policy, query, ObserveCallback, ptr.get())); if (!result) { return result; } @@ -982,7 +992,8 @@ common::TizenResult IotconInstance::RemoteResourceStopObserving(const picojson:: iotcon_options_destroy(options); }; - result = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(ptr->handle, options)); + result = + IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options(ptr->handle, options)); if (!result) { LogAndReturnTizenError(result, ("iotcon_response_set_options() failed")); } @@ -998,8 +1009,7 @@ common::TizenResult IotconInstance::RemoteResourceStopObserving(const picojson:: } static void RepresentationChangedCallback(iotcon_remote_resource_h resource, - iotcon_representation_h representation, - void *user_data) { + iotcon_representation_h representation, void* user_data) { ScopeLogger(); FoundRemoteInfo* ptr = static_cast(user_data); if (nullptr == ptr) { @@ -1010,7 +1020,8 @@ static void RepresentationChangedCallback(iotcon_remote_resource_h resource, if (ptr->cache_change_listener) { picojson::value json_result = picojson::value(picojson::object()); - auto result = IotconUtils::RepresentationToJson(representation, &json_result.get()); + auto result = + IotconUtils::RepresentationToJson(representation, &json_result.get()); if (result) { ptr->cache_change_listener(common::TizenSuccess(), json_result); } else { @@ -1031,7 +1042,8 @@ common::TizenResult IotconInstance::RemoteResourceStartCaching(const picojson::o LogAndReturnTizenError(result, ("Failed to create remote resource handle")); } - ptr->cache_change_listener = [this, ptr](const common::TizenResult& res, const picojson::value& v) { + ptr->cache_change_listener = [this, ptr](const common::TizenResult& res, + const picojson::value& v) { picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1071,8 +1083,7 @@ common::TizenResult IotconInstance::RemoteResourceStopCaching(const picojson::ob LogAndReturnTizenError(result, ("Failed to create remote resource handle")); } - result = IotconUtils::ConvertIotconError( - iotcon_remote_resource_stop_caching(ptr->handle)); + result = IotconUtils::ConvertIotconError(iotcon_remote_resource_stop_caching(ptr->handle)); if (!result) { return result; } @@ -1083,7 +1094,7 @@ common::TizenResult IotconInstance::RemoteResourceStopCaching(const picojson::ob } static void MonitoringCallback(iotcon_remote_resource_h resource, - iotcon_remote_resource_state_e state, void *user_data) { + iotcon_remote_resource_state_e state, void* user_data) { ScopeLogger(); FoundRemoteInfo* ptr = static_cast(user_data); if (nullptr == ptr) { @@ -1099,7 +1110,8 @@ static void MonitoringCallback(iotcon_remote_resource_h resource, } } -common::TizenResult IotconInstance::RemoteResourceSetResourceStateChangeListener(const picojson::object& args) { +common::TizenResult IotconInstance::RemoteResourceSetResourceStateChangeListener( + const picojson::object& args) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeIotcon); @@ -1129,7 +1141,8 @@ common::TizenResult IotconInstance::RemoteResourceSetResourceStateChangeListener return common::TizenSuccess{IotconClientManager::GetInstance().StoreRemoteResource(ptr)}; } -common::TizenResult IotconInstance::RemoteResourceUnsetResourceStateChangeListener(const picojson::object& args) { +common::TizenResult IotconInstance::RemoteResourceUnsetResourceStateChangeListener( + const picojson::object& args) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeIotcon); @@ -1170,7 +1183,8 @@ common::TizenResult IotconInstance::RemoteResourceGetTimeInterval(const picojson int time_interval = 0; - res = IotconUtils::ConvertIotconError(iotcon_remote_resource_get_checking_interval(ptr->handle, &time_interval)); + res = IotconUtils::ConvertIotconError( + iotcon_remote_resource_get_checking_interval(ptr->handle, &time_interval)); if (!res) { LogAndReturnTizenError(res, ("iotcon_remote_resource_get_checking_interval() failed")); } @@ -1191,16 +1205,17 @@ common::TizenResult IotconInstance::RemoteResourceSetTimeInterval(const picojson LogAndReturnTizenError(res, ("Failed to build resource using json data")); } - res = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_checking_interval(ptr->handle, time_interval)); + res = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_checking_interval(ptr->handle, time_interval)); if (!res) { LogAndReturnTizenError(res, ("iotcon_remote_resource_set_checking_interval() failed")); } - return common::TizenSuccess{IotconClientManager::GetInstance().StoreRemoteResource(ptr)}; + return common::TizenSuccess{IotconClientManager::GetInstance().StoreRemoteResource(ptr)}; } -bool IotconInstance::ResourceFoundCallback(iotcon_remote_resource_h resource, - iotcon_error_e result, void *user_data) { +bool IotconInstance::ResourceFoundCallback(iotcon_remote_resource_h resource, iotcon_error_e result, + void* user_data) { ScopeLogger(); CallbackData2* data = static_cast(user_data); if (nullptr == data) { @@ -1213,9 +1228,9 @@ bool IotconInstance::ResourceFoundCallback(iotcon_remote_resource_h resource, break; case IOTCON_ERROR_TIMEOUT: LoggerD("IOTCON_TIMEOUT data->callback_called :%d", data->callback_called); - if(!data->callback_called){ - auto ret = IotconUtils::ConvertIotconError(result); - data->fun(ret, picojson::value{}); + if (!data->callback_called) { + auto ret = IotconUtils::ConvertIotconError(result); + data->fun(ret, picojson::value{}); } delete data; return IOTCON_FUNC_STOP; @@ -1267,8 +1282,8 @@ common::TizenResult IotconInstance::ClientFindResource(const picojson::object& a }; CHECK_EXIST(args, kConnectivityType); - int connectivity_type = IotconUtils::ToConnectivityType2( - args.find(kConnectivityType)->second.get()); + int connectivity_type = + IotconUtils::ToConnectivityType2(args.find(kConnectivityType)->second.get()); long long id = GetId(args); auto response = [this, id](const common::TizenResult& res, const picojson::value& v) { @@ -1276,7 +1291,7 @@ common::TizenResult IotconInstance::ClientFindResource(const picojson::object& a auto& obj = response.get(); obj.insert(std::make_pair(kId, picojson::value{static_cast(id)})); - if(res) { + if (res) { common::tools::ReportSuccess(v, obj); } else { common::tools::ReportError(res, &obj); @@ -1289,11 +1304,10 @@ common::TizenResult IotconInstance::ClientFindResource(const picojson::object& a data->fun = response; data->callback_called = false; - LoggerD("Running find with:\nhost_address: %s,\nconnectivity_type: %d", - host_address, connectivity_type); + LoggerD("Running find with:\nhost_address: %s,\nconnectivity_type: %d", host_address, + connectivity_type); auto result = IotconUtils::ConvertIotconError( - iotcon_find_resource(host_address, connectivity_type, query, - ResourceFoundCallback, data)); + iotcon_find_resource(host_address, connectivity_type, query, ResourceFoundCallback, data)); if (!result) { delete data; LogAndReturnTizenError(result); @@ -1325,12 +1339,12 @@ common::TizenResult IotconInstance::ClientAddPresenceEventListener(const picojso if (!con_type.is()) { return common::TypeMismatchError("connectivityType needs to be a string"); } - iotcon_connectivity_type_e con_type_e = IotconUtils::ToConnectivityType( - con_type.get()); + iotcon_connectivity_type_e con_type_e = + IotconUtils::ToConnectivityType(con_type.get()); PresenceEventPtr presence{new PresenceEvent()}; - auto ret = IotconClientManager::GetInstance().AddPresenceEventListener( - host, con_type_e, resource_type, presence); + auto ret = IotconClientManager::GetInstance().AddPresenceEventListener(host, con_type_e, + resource_type, presence); if (!ret) { return ret; } @@ -1350,7 +1364,8 @@ common::TizenResult IotconInstance::ClientAddPresenceEventListener(const picojso return common::TizenSuccess(picojson::value{static_cast(id)}); } -common::TizenResult IotconInstance::ClientRemovePresenceEventListener(const picojson::object& args) { +common::TizenResult IotconInstance::ClientRemovePresenceEventListener( + const picojson::object& args) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeIotcon); @@ -1366,8 +1381,7 @@ common::TizenResult IotconInstance::ClientRemovePresenceEventListener(const pico return common::TizenSuccess(); } -bool IotconDeviceInfoCb(iotcon_device_info_h device_info, - iotcon_error_e result, void *user_data) { +bool IotconDeviceInfoCb(iotcon_device_info_h device_info, iotcon_error_e result, void* user_data) { ScopeLogger(); CallbackData2* data = static_cast(user_data); @@ -1381,14 +1395,14 @@ bool IotconDeviceInfoCb(iotcon_device_info_h device_info, switch (result) { case IOTCON_ERROR_NONE: - ret = IotconUtils::DeviceInfoToJson(device_info,&v.get()); + ret = IotconUtils::DeviceInfoToJson(device_info, &v.get()); data->callback_called = true; break; case IOTCON_ERROR_TIMEOUT: LoggerD("IOTCON_TIMEOUT data->callback_called :%d", data->callback_called); - if(!data->callback_called){ - ret = IotconUtils::ConvertIotconError(result); - data->fun(ret, v); + if (!data->callback_called) { + ret = IotconUtils::ConvertIotconError(result); + data->fun(ret, v); } delete data; return IOTCON_FUNC_STOP; @@ -1439,7 +1453,7 @@ common::TizenResult IotconInstance::ClientFindDeviceInfo(const picojson::object& auto& obj = response.get(); obj.insert(std::make_pair(kId, picojson::value{static_cast(id)})); - if(res) { + if (res) { common::tools::ReportSuccess(v, obj); } else { common::tools::ReportError(res, &obj); @@ -1453,7 +1467,7 @@ common::TizenResult IotconInstance::ClientFindDeviceInfo(const picojson::object& data->callback_called = false; auto result = IotconUtils::ConvertIotconError( - iotcon_find_device_info(host_address, con_type_e, query, IotconDeviceInfoCb, data)); + iotcon_find_device_info(host_address, con_type_e, query, IotconDeviceInfoCb, data)); if (!result) { delete data; @@ -1463,8 +1477,8 @@ common::TizenResult IotconInstance::ClientFindDeviceInfo(const picojson::object& return common::TizenSuccess(); } -bool IotconPlatformInfoCb(iotcon_platform_info_h platform_info, - iotcon_error_e result, void *user_data) { +bool IotconPlatformInfoCb(iotcon_platform_info_h platform_info, iotcon_error_e result, + void* user_data) { ScopeLogger(); CallbackData2* data = static_cast(user_data); @@ -1478,14 +1492,14 @@ bool IotconPlatformInfoCb(iotcon_platform_info_h platform_info, switch (result) { case IOTCON_ERROR_NONE: - ret = IotconUtils::PlatformInfoToJson(platform_info,&v.get()); + ret = IotconUtils::PlatformInfoToJson(platform_info, &v.get()); data->callback_called = true; break; case IOTCON_ERROR_TIMEOUT: LoggerD("IOTCON_TIMEOUT data->callback_called :%d", data->callback_called); - if(!data->callback_called){ - ret = IotconUtils::ConvertIotconError(result); - data->fun(ret, v); + if (!data->callback_called) { + ret = IotconUtils::ConvertIotconError(result); + data->fun(ret, v); } delete data; return IOTCON_FUNC_STOP; @@ -1536,7 +1550,7 @@ common::TizenResult IotconInstance::ClientFindPlatformInfo(const picojson::objec auto& obj = response.get(); obj.insert(std::make_pair(kId, picojson::value{static_cast(id)})); - if(res) { + if (res) { common::tools::ReportSuccess(v, obj); } else { common::tools::ReportError(res, &obj); @@ -1550,7 +1564,7 @@ common::TizenResult IotconInstance::ClientFindPlatformInfo(const picojson::objec data->callback_called = false; auto result = IotconUtils::ConvertIotconError( - iotcon_find_platform_info(host_address, con_type_e, query, IotconPlatformInfoCb, data)); + iotcon_find_platform_info(host_address, con_type_e, query, IotconPlatformInfoCb, data)); if (!result) { delete data; @@ -1572,16 +1586,18 @@ common::TizenResult IotconInstance::ServerCreateResource(const picojson::object& const std::string& uri_path = args.find(kUriPath)->second.get(); const auto& types = IotconUtils::GetArg(args, kResourceTypes); - const auto& resource_types = types.is() ? types.get() : picojson::array(); + const auto& resource_types = + types.is() ? types.get() : picojson::array(); const auto& interfaces = IotconUtils::GetArg(args, kResourceInterfaces); - const auto& resource_interfaces = interfaces.is() ? interfaces.get() : picojson::array(); + const auto& resource_interfaces = + interfaces.is() ? interfaces.get() : picojson::array(); int properties = IotconUtils::GetProperties(args); ResourceInfoPtr resource{new ResourceInfo()}; - auto ret = IotconServerManager::GetInstance().CreateResource(uri_path, resource_interfaces, resource_types, - properties, resource); + auto ret = IotconServerManager::GetInstance().CreateResource( + uri_path, resource_interfaces, resource_types, properties, resource); if (!ret) { return ret; } @@ -1622,7 +1638,8 @@ common::TizenResult IotconInstance::ServerStartPresence(const picojson::object& return common::TizenSuccess(); } - unsigned int timeToLive = static_cast(IotconUtils::GetArg(args, kTimeToLive).get()); + unsigned int timeToLive = + static_cast(IotconUtils::GetArg(args, kTimeToLive).get()); auto result = IotconUtils::ConvertIotconError(iotcon_start_presence(timeToLive)); if (!result) { @@ -1685,10 +1702,11 @@ common::TizenResult IotconInstance::Initialize(const picojson::object& args) { CHECK_EXIST(args, kFilePath); const auto& filePath = IotconUtils::GetArg(args, kFilePath); - //convert virtual root (if present in path) for native iotcon_initialize function - std::string realPath = common::FilesystemProvider::Create().GetRealPath( filePath.get() ); + // convert virtual root (if present in path) for native iotcon_initialize function + std::string realPath = + common::FilesystemProvider::Create().GetRealPath(filePath.get()); - auto result = IotconUtils::ConvertIotconError( iotcon_initialize(realPath.c_str()) ); + auto result = IotconUtils::ConvertIotconError(iotcon_initialize(realPath.c_str())); if (!result) { LogAndReturnTizenError(result); } @@ -1734,7 +1752,7 @@ common::TizenResult IotconInstance::AddGeneratedPinListener(const picojson::obje picojson::object obj; obj[kId] = picojson::value{(double)watchId}; obj["pin"] = picojson::value{pin}; - this->Post(kGeneratedPinToken, common::TizenSuccess{ picojson::value{obj} }); + this->Post(kGeneratedPinToken, common::TizenSuccess{picojson::value{obj}}); }; return IotconManager::GetInstance().addGeneratedPinListener(listener); @@ -1749,7 +1767,8 @@ common::TizenResult IotconInstance::RemoveGeneratedPinListener(const picojson::o return IotconManager::GetInstance().removeGeneratedPinListener(watchId); } -common::PostCallback IotconInstance::PostForMethodCall(const common::AsyncToken& token, const FoundRemoteInfoPtr& resource) { +common::PostCallback IotconInstance::PostForMethodCall(const common::AsyncToken& token, + const FoundRemoteInfoPtr& resource) { ScopeLogger(); return [this, token, resource](const common::TizenResult& result, const picojson::value& v) { diff --git a/src/iotcon/iotcon_instance.h b/src/iotcon/iotcon_instance.h index 8cf67aa..8b35446 100644 --- a/src/iotcon/iotcon_instance.h +++ b/src/iotcon/iotcon_instance.h @@ -30,10 +30,11 @@ class IotconInstance : public common::TizenInstance { public: IotconInstance(); virtual ~IotconInstance(); + private: static void ConnectionChangedCallback(bool is_connected, void* user_data); - static bool ResourceFoundCallback(iotcon_remote_resource_h resource, - iotcon_error_e result, void *user_data); + static bool ResourceFoundCallback(iotcon_remote_resource_h resource, iotcon_error_e result, + void* user_data); common::TizenResult ResourceGetObserverIds(const picojson::object& args); common::TizenResult ResourceNotify(const picojson::object& args); @@ -79,7 +80,8 @@ class IotconInstance : public common::TizenInstance { common::TizenResult AddGeneratedPinListener(const picojson::object& args); common::TizenResult RemoveGeneratedPinListener(const picojson::object& args); - common::PostCallback PostForMethodCall(const common::AsyncToken& token, const FoundRemoteInfoPtr& resource); + common::PostCallback PostForMethodCall(const common::AsyncToken& token, + const FoundRemoteInfoPtr& resource); private: bool initialized_; diff --git a/src/iotcon/iotcon_manager.cc b/src/iotcon/iotcon_manager.cc index d0f6c49..037b9b6 100644 --- a/src/iotcon/iotcon_manager.cc +++ b/src/iotcon/iotcon_manager.cc @@ -18,9 +18,9 @@ #include +#include "common/logger.h" #include "iotcon/iotcon_manager.h" #include "iotcon/iotcon_utils.h" -#include "common/logger.h" namespace extension { namespace iotcon { @@ -33,11 +33,12 @@ IotconManager& IotconManager::GetInstance() { return instance; } -common::TizenResult IotconManager::addGeneratedPinListener(std::function listener) { +common::TizenResult IotconManager::addGeneratedPinListener( + std::function listener) { ScopeLogger(); using namespace std::placeholders; - //generate id + // generate id long watchId = nextWatchId++; std::function listener_with_id = std::bind(listener, _1, watchId); @@ -46,34 +47,35 @@ common::TizenResult IotconManager::addGeneratedPinListener(std::function mutex_lock{listeners_mutex}; - if( listeners.empty() ) { + if (listeners.empty()) { /* user_data is not used */ - auto result = IotconUtils::ConvertIotconError( iotcon_add_generated_pin_cb(callback, nullptr) ); - if( !result ) { + auto result = IotconUtils::ConvertIotconError(iotcon_add_generated_pin_cb(callback, nullptr)); + if (!result) { return result; } } - //store listener in map + // store listener in map this->listeners[watchId] = listener_with_id; } - return common::TizenSuccess{ picojson::value{(double)watchId} }; + return common::TizenSuccess{picojson::value{(double)watchId}}; } common::TizenResult IotconManager::removeGeneratedPinListener(long watchId) { std::lock_guard mutex_guard{listeners_mutex}; auto it = listeners.find(watchId); - if( it == listeners.end() ) { + if (it == listeners.end()) { return LogAndCreateTizenError(AbortError, "Listener with specified ID does not exist"); } listeners.erase(it); // If we deleted last listener, unregister our handler - if( listeners.empty() ) { - auto result = IotconUtils::ConvertIotconError( iotcon_remove_generated_pin_cb(IotconManager::ListenerHandler) ); + if (listeners.empty()) { + auto result = IotconUtils::ConvertIotconError( + iotcon_remove_generated_pin_cb(IotconManager::ListenerHandler)); if (!result) { return result; } @@ -82,16 +84,16 @@ common::TizenResult IotconManager::removeGeneratedPinListener(long watchId) { return common::TizenSuccess{}; } -void IotconManager::ListenerHandler(const char* pin, void *user_data) { +void IotconManager::ListenerHandler(const char* pin, void* user_data) { ScopeLogger(); /* user_data is not used */ auto& instance = IotconManager::GetInstance(); std::unique_lock mutex_guard{instance.listeners_mutex}; - for( auto& listener : instance.listeners ) { + for (auto& listener : instance.listeners) { listener.second(pin); } }; -} // namespace iotcon -} // namespace extension +} // namespace iotcon +} // namespace extension diff --git a/src/iotcon/iotcon_manager.h b/src/iotcon/iotcon_manager.h index 2d9876e..ce02975 100644 --- a/src/iotcon/iotcon_manager.h +++ b/src/iotcon/iotcon_manager.h @@ -17,8 +17,8 @@ #ifndef IOTCON_MANAGER_H_ #define IOTCON_MANAGER_H_ -#include #include +#include #include #include "common/tizen_result.h" @@ -30,11 +30,11 @@ class IotconManager { public: static IotconManager& GetInstance(); - common::TizenResult addGeneratedPinListener(std::function listener); + common::TizenResult addGeneratedPinListener(std::function listener); common::TizenResult removeGeneratedPinListener(long watchId); private: - static void ListenerHandler(const char* pin, void *user_data); + static void ListenerHandler(const char* pin, void* user_data); IotconManager(); IotconManager(const IotconManager&) = delete; @@ -43,12 +43,11 @@ class IotconManager { IotconManager& operator=(IotconManager&&) = delete; long nextWatchId; - std::map > listeners; + std::map> listeners; std::mutex listeners_mutex; }; -} // namespace iotcon -} // namespace extension - +} // namespace iotcon +} // namespace extension #endif /* IOTCON_MANAGER_H_ */ diff --git a/src/iotcon/iotcon_server_manager.cc b/src/iotcon/iotcon_server_manager.cc index 107343a..84c78ad 100644 --- a/src/iotcon/iotcon_server_manager.cc +++ b/src/iotcon/iotcon_server_manager.cc @@ -41,8 +41,8 @@ IotconServerManager& IotconServerManager::GetInstance() { return instance; } -void IotconServerManager::RequestHandler(iotcon_resource_h resource, - iotcon_request_h request, void *user_data) { +void IotconServerManager::RequestHandler(iotcon_resource_h resource, iotcon_request_h request, + void* user_data) { ScopeLogger(); auto that = static_cast(user_data); @@ -93,7 +93,8 @@ void IotconServerManager::RequestHandler(iotcon_resource_h resource, auto& obj = value.get(); iotcon_request_type_e request_type = IOTCON_REQUEST_UNKNOWN; - auto result = IotconUtils::ConvertIotconError(iotcon_request_get_request_type(request, &request_type)); + auto result = + IotconUtils::ConvertIotconError(iotcon_request_get_request_type(request, &request_type)); if (!result) { LoggerE("iotcon_request_get_request_type() failed"); return; @@ -131,7 +132,8 @@ void IotconServerManager::RequestHandler(iotcon_resource_h resource, // store data long long id = GetNextId(); obj.insert(std::make_pair(kId, picojson::value{static_cast(id)})); - r->pending_responses.insert(std::make_pair(id, ResponsePtr{response, &iotcon_response_destroy})); + r->pending_responses.insert( + std::make_pair(id, ResponsePtr{response, &iotcon_response_destroy})); // call listener r->request_listener(TizenSuccess(), value); @@ -140,8 +142,7 @@ void IotconServerManager::RequestHandler(iotcon_resource_h resource, TizenResult IotconServerManager::CreateResource(const std::string& uri_path, const picojson::array& interfaces_array, - const picojson::array& types_array, - int properties, + const picojson::array& types_array, int properties, ResourceInfoPtr res_pointer) { ScopeLogger(); @@ -165,17 +166,14 @@ TizenResult IotconServerManager::CreateResource(const std::string& uri_path, }; // Create resource - ret = iotcon_resource_create(uri_path.c_str(), - resource_types, - interfaces, - properties, - RequestHandler, // request_callback - this, // user_data + ret = iotcon_resource_create(uri_path.c_str(), resource_types, interfaces, properties, + RequestHandler, // request_callback + this, // user_data &(res_pointer->handle)); if (IOTCON_ERROR_NONE != ret || nullptr == res_pointer->handle) { - LogAndReturnTizenError(IotconUtils::ConvertIotconError(ret), - ("iotcon_resource_create() failed: %d (%s)", - ret, get_error_message(ret))); + LogAndReturnTizenError( + IotconUtils::ConvertIotconError(ret), + ("iotcon_resource_create() failed: %d (%s)", ret, get_error_message(ret))); } // storing ResourceInfo into map @@ -185,8 +183,7 @@ TizenResult IotconServerManager::CreateResource(const std::string& uri_path, return TizenSuccess(); } -TizenResult IotconServerManager::GetResourceById(long long id, - ResourceInfoPtr* res_pointer) const { +TizenResult IotconServerManager::GetResourceById(long long id, ResourceInfoPtr* res_pointer) const { ScopeLogger(); auto it = resource_map_.find(id); @@ -210,7 +207,8 @@ common::TizenResult IotconServerManager::DestroyResource(long long id) { // do not allow to destroy a resource which has a parent resource if (resource->parents.size() > 0) { - return LogAndCreateTizenError(InvalidStateError, "Cannot destroy child resource, remove it from parent first"); + return LogAndCreateTizenError(InvalidStateError, + "Cannot destroy child resource, remove it from parent first"); } // notify children they've lost a parent :( @@ -223,13 +221,14 @@ common::TizenResult IotconServerManager::DestroyResource(long long id) { return TizenSuccess(); } -common::TizenResult IotconServerManager::GetResourceByHandle( - iotcon_resource_h resource, ResourceInfoPtr* res_pointer) const { +common::TizenResult IotconServerManager::GetResourceByHandle(iotcon_resource_h resource, + ResourceInfoPtr* res_pointer) const { ScopeLogger(); - auto it = std::find_if(resource_map_.begin(), resource_map_.end(), [resource](const ResourceInfoMap::value_type& p) -> bool { - return p.second->handle == resource; - }); + auto it = std::find_if(resource_map_.begin(), resource_map_.end(), + [resource](const ResourceInfoMap::value_type& p) -> bool { + return p.second->handle == resource; + }); if (it == resource_map_.end()) { return LogAndCreateTizenError(NotFoundError, "Resource with specified handle does not exist"); diff --git a/src/iotcon/iotcon_server_manager.h b/src/iotcon/iotcon_server_manager.h index f800e0a..2713bfd 100644 --- a/src/iotcon/iotcon_server_manager.h +++ b/src/iotcon/iotcon_server_manager.h @@ -17,10 +17,10 @@ #ifndef WEBAPI_PLUGINS_IOTCON_SERVER_MANAGER_H__ #define WEBAPI_PLUGINS_IOTCON_SERVER_MANAGER_H__ -#include +#include #include +#include #include -#include #include "iotcon/iotcon_utils.h" @@ -37,12 +37,12 @@ class IotconServerManager { common::TizenResult CreateResource(const std::string& uri_path, const picojson::array& interfaces_array, - const picojson::array& types_array, - int properties, + const picojson::array& types_array, int properties, ResourceInfoPtr res_pointer); common::TizenResult GetResourceById(long long id, ResourceInfoPtr* res_pointer) const; common::TizenResult DestroyResource(long long id); - common::TizenResult GetResourceByHandle(iotcon_resource_h resource, ResourceInfoPtr* res_pointer) const; + common::TizenResult GetResourceByHandle(iotcon_resource_h resource, + ResourceInfoPtr* res_pointer) const; common::TizenResult GetResponseById(long long id, ResponsePtr* out) const; private: @@ -52,14 +52,13 @@ class IotconServerManager { IotconServerManager& operator=(const IotconServerManager&) = delete; IotconServerManager& operator=(IotconServerManager&&) = delete; - static void RequestHandler(iotcon_resource_h resource, - iotcon_request_h request, void *user_data); + static void RequestHandler(iotcon_resource_h resource, iotcon_request_h request, void* user_data); ResourceInfoMap resource_map_; std::map uri_map_; }; -} // namespace iotcon -} // namespace extension +} // namespace iotcon +} // namespace extension -#endif // WEBAPI_PLUGINS_IOTCON_SERVER_MANAGER_H__ +#endif // WEBAPI_PLUGINS_IOTCON_SERVER_MANAGER_H__ diff --git a/src/iotcon/iotcon_utils.cc b/src/iotcon/iotcon_utils.cc index c94661f..c616f3d 100644 --- a/src/iotcon/iotcon_utils.cc +++ b/src/iotcon/iotcon_utils.cc @@ -23,63 +23,63 @@ #include "common/scope_exit.h" #include "common/tools.h" -#include "iotcon/iotcon_server_manager.h" #include "iotcon/iotcon_client_manager.h" +#include "iotcon/iotcon_server_manager.h" namespace extension { namespace iotcon { namespace { -#define IOTCON_CONNECTIVITY_TYPE_E \ - X(IOTCON_CONNECTIVITY_IP, "IP") \ +#define IOTCON_CONNECTIVITY_TYPE_E \ + X(IOTCON_CONNECTIVITY_IP, "IP") \ X(IOTCON_CONNECTIVITY_PREFER_UDP, "PREFER_UDP") \ X(IOTCON_CONNECTIVITY_PREFER_TCP, "PREFER_TCP") \ - X(IOTCON_CONNECTIVITY_IPV4_ONLY, "IPV4_ONLY") \ - X(IOTCON_CONNECTIVITY_IPV6_ONLY, "IPV6_ONLY") \ - X(IOTCON_CONNECTIVITY_ALL, "ALL") \ + X(IOTCON_CONNECTIVITY_IPV4_ONLY, "IPV4_ONLY") \ + X(IOTCON_CONNECTIVITY_IPV6_ONLY, "IPV6_ONLY") \ + X(IOTCON_CONNECTIVITY_ALL, "ALL") \ XD(IOTCON_CONNECTIVITY_ALL, "unknown") -#define IOTCON_REQUEST_TYPE_E \ +#define IOTCON_REQUEST_TYPE_E \ X(IOTCON_REQUEST_UNKNOWN, "unknown") \ - X(IOTCON_REQUEST_GET, "GET") \ - X(IOTCON_REQUEST_PUT, "PUT") \ - X(IOTCON_REQUEST_POST, "POST") \ - X(IOTCON_REQUEST_DELETE, "DELETE") \ + X(IOTCON_REQUEST_GET, "GET") \ + X(IOTCON_REQUEST_PUT, "PUT") \ + X(IOTCON_REQUEST_POST, "POST") \ + X(IOTCON_REQUEST_DELETE, "DELETE") \ XD(IOTCON_REQUEST_UNKNOWN, "unknown") -#define IOTCON_OBSERVE_TYPE_E \ - X(IOTCON_OBSERVE_NO_TYPE, "NO_TYPE") \ - X(IOTCON_OBSERVE_REGISTER, "REGISTER") \ +#define IOTCON_OBSERVE_TYPE_E \ + X(IOTCON_OBSERVE_NO_TYPE, "NO_TYPE") \ + X(IOTCON_OBSERVE_REGISTER, "REGISTER") \ X(IOTCON_OBSERVE_DEREGISTER, "DEREGISTER") \ XD(IOTCON_OBSERVE_NO_TYPE, "unknown") -#define IOTCON_QOS_E \ - X(IOTCON_QOS_LOW, "LOW") \ +#define IOTCON_QOS_E \ + X(IOTCON_QOS_LOW, "LOW") \ X(IOTCON_QOS_HIGH, "HIGH") \ XD(IOTCON_QOS_LOW, "unknown") -#define IOTCON_PRESENCE_RESULT_E \ - X(IOTCON_PRESENCE_OK, "OK") \ +#define IOTCON_PRESENCE_RESULT_E \ + X(IOTCON_PRESENCE_OK, "OK") \ X(IOTCON_PRESENCE_STOPPED, "STOPPED") \ XD(IOTCON_PRESENCE_TIMEOUT, "TIMEOUT") -#define IOTCON_PRESENCE_TRIGGER_E \ +#define IOTCON_PRESENCE_TRIGGER_E \ X(IOTCON_PRESENCE_RESOURCE_CREATED, "CREATED") \ X(IOTCON_PRESENCE_RESOURCE_UPDATED, "UPDATED") \ XD(IOTCON_PRESENCE_RESOURCE_DESTROYED, "DESTROYED") -#define IOTCON_RESPONSE_RESULT_E \ - X(IOTCON_RESPONSE_OK, "SUCCESS") \ - X(IOTCON_RESPONSE_ERROR, "ERROR") \ +#define IOTCON_RESPONSE_RESULT_E \ + X(IOTCON_RESPONSE_OK, "SUCCESS") \ + X(IOTCON_RESPONSE_ERROR, "ERROR") \ X(IOTCON_RESPONSE_RESOURCE_CREATED, "RESOURCE_CREATED") \ X(IOTCON_RESPONSE_RESOURCE_DELETED, "RESOURCE_DELETED") \ X(IOTCON_RESPONSE_RESOURCE_CHANGED, "RESOURCE_CHANGED") \ - X(IOTCON_RESPONSE_SLOW, "SLOW") \ - X(IOTCON_RESPONSE_FORBIDDEN, "FORBIDDEN") \ + X(IOTCON_RESPONSE_SLOW, "SLOW") \ + X(IOTCON_RESPONSE_FORBIDDEN, "FORBIDDEN") \ XD(IOTCON_RESPONSE_ERROR, "unknown") -#define IOTCON_OBSERVE_POLICY_E \ +#define IOTCON_OBSERVE_POLICY_E \ X(IOTCON_OBSERVE_IGNORE_OUT_OF_ORDER, "IGNORE_OUT_OF_ORDER") \ X(IOTCON_OBSERVE_ACCEPT_OUT_OF_ORDER, "ACCEPT_OUT_OF_ORDER") \ XD(IOTCON_OBSERVE_ACCEPT_OUT_OF_ORDER, "unknown") @@ -164,22 +164,31 @@ int IotconUtils::GetProperties(const picojson::object& args) { int properties = IOTCON_RESOURCE_NO_POLICY; const auto& observable = IotconUtils::GetArg(args, kIsObservable); - properties |= (observable.is() ? observable.get() : false) ? IOTCON_RESOURCE_OBSERVABLE : IOTCON_RESOURCE_NO_POLICY; + properties |= (observable.is() ? observable.get() : false) + ? IOTCON_RESOURCE_OBSERVABLE + : IOTCON_RESOURCE_NO_POLICY; const auto& discoverable = IotconUtils::GetArg(args, kIsDiscoverable); - properties |= (discoverable.is() ? discoverable.get() : true) ? IOTCON_RESOURCE_DISCOVERABLE : IOTCON_RESOURCE_NO_POLICY; + properties |= (discoverable.is() ? discoverable.get() : true) + ? IOTCON_RESOURCE_DISCOVERABLE + : IOTCON_RESOURCE_NO_POLICY; const auto& active = IotconUtils::GetArg(args, kIsActive); - properties |= (active.is() ? active.get() : false) ? IOTCON_RESOURCE_ACTIVE : IOTCON_RESOURCE_NO_POLICY; + properties |= (active.is() ? active.get() : false) ? IOTCON_RESOURCE_ACTIVE + : IOTCON_RESOURCE_NO_POLICY; const auto& slow = IotconUtils::GetArg(args, kIsSlow); - properties |= (slow.is() ? slow.get() : false) ? IOTCON_RESOURCE_SLOW : IOTCON_RESOURCE_NO_POLICY; + properties |= (slow.is() ? slow.get() : false) ? IOTCON_RESOURCE_SLOW + : IOTCON_RESOURCE_NO_POLICY; const auto& secure = IotconUtils::GetArg(args, kIsSecure); - properties |= (secure.is() ? secure.get() : false) ? IOTCON_RESOURCE_SECURE : IOTCON_RESOURCE_NO_POLICY; + properties |= (secure.is() ? secure.get() : false) ? IOTCON_RESOURCE_SECURE + : IOTCON_RESOURCE_NO_POLICY; const auto& explicit_discoverable = IotconUtils::GetArg(args, kIsExplicitDiscoverable); - properties |= (explicit_discoverable.is() ? explicit_discoverable.get() : false) ? IOTCON_RESOURCE_EXPLICIT_DISCOVERABLE : IOTCON_RESOURCE_NO_POLICY; + properties |= (explicit_discoverable.is() ? explicit_discoverable.get() : false) + ? IOTCON_RESOURCE_EXPLICIT_DISCOVERABLE + : IOTCON_RESOURCE_NO_POLICY; return properties; } @@ -199,7 +208,8 @@ void IotconUtils::PropertiesToJson(int properties, picojson::object* res) { res->insert(std::make_pair(kIsExplicitDiscoverable, picojson::value(value))); } -TizenResult IotconUtils::ArrayToInterfaces(const picojson::array& i, iotcon_resource_interfaces_h* out) { +TizenResult IotconUtils::ArrayToInterfaces(const picojson::array& i, + iotcon_resource_interfaces_h* out) { ScopeLogger(); iotcon_resource_interfaces_h interfaces = nullptr; @@ -209,13 +219,16 @@ TizenResult IotconUtils::ArrayToInterfaces(const picojson::array& i, iotcon_reso LogAndReturnTizenError(result, ("iotcon_resource_interfaces_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_resource_interfaces_h)> ptr{interfaces, &iotcon_resource_interfaces_destroy}; + std::unique_ptr::type, + int (*)(iotcon_resource_interfaces_h)> + ptr{interfaces, &iotcon_resource_interfaces_destroy}; for (const auto& iter : i) { if (!iter.is()) { return LogAndCreateTizenError(InvalidValuesError, "Interface name should be a string"); } else { - result = ConvertIotconError(iotcon_resource_interfaces_add(interfaces, iter.get().c_str())); + result = ConvertIotconError( + iotcon_resource_interfaces_add(interfaces, iter.get().c_str())); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_interfaces_add() failed")); } @@ -226,21 +239,25 @@ TizenResult IotconUtils::ArrayToInterfaces(const picojson::array& i, iotcon_reso return TizenSuccess(); } -TizenResult IotconUtils::InterfacesToArray(iotcon_resource_interfaces_h interfaces, picojson::array* arr) { +TizenResult IotconUtils::InterfacesToArray(iotcon_resource_interfaces_h interfaces, + picojson::array* arr) { ScopeLogger(); if (interfaces) { - auto result = ConvertIotconError(iotcon_resource_interfaces_foreach(interfaces, [](const char* iface, void* user_data) -> bool { - ScopeLogger("iotcon_resource_interfaces_foreach"); - - if (iface) { - auto arr = static_cast(user_data); - arr->push_back(picojson::value(iface)); - } - - // always continue with iteration - return true; - }, arr)); + auto result = ConvertIotconError( + iotcon_resource_interfaces_foreach(interfaces, + [](const char* iface, void* user_data) -> bool { + ScopeLogger("iotcon_resource_interfaces_foreach"); + + if (iface) { + auto arr = static_cast(user_data); + arr->push_back(picojson::value(iface)); + } + + // always continue with iteration + return true; + }, + arr)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_interfaces_foreach() failed")); } @@ -259,13 +276,16 @@ TizenResult IotconUtils::ArrayToTypes(const picojson::array& types, iotcon_resou LogAndReturnTizenError(result, ("iotcon_resource_types_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_resource_types_h)> ptr{resource_types, &iotcon_resource_types_destroy}; + std::unique_ptr::type, + int (*)(iotcon_resource_types_h)> + ptr{resource_types, &iotcon_resource_types_destroy}; for (const auto& iter : types) { if (!iter.is()) { return LogAndCreateTizenError(InvalidValuesError, "Resource type should be a string"); } else { - result = ConvertIotconError(iotcon_resource_types_add(resource_types, iter.get().c_str())); + result = ConvertIotconError( + iotcon_resource_types_add(resource_types, iter.get().c_str())); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_types_add() failed")); } @@ -276,7 +296,7 @@ TizenResult IotconUtils::ArrayToTypes(const picojson::array& types, iotcon_resou return TizenSuccess(); } -static bool ResourceTypeIterator(const char *type, void *user_data) { +static bool ResourceTypeIterator(const char* type, void* user_data) { ScopeLogger(); picojson::array* array_data = static_cast(user_data); @@ -289,8 +309,7 @@ static bool ResourceTypeIterator(const char *type, void *user_data) { return true; } -TizenResult IotconUtils::ExtractFromResource(const ResourceInfoPtr& pointer, - char** uri_path, +TizenResult IotconUtils::ExtractFromResource(const ResourceInfoPtr& pointer, char** uri_path, iotcon_resource_types_h* res_types, iotcon_resource_interfaces_h* ifaces, uint8_t* properties) { @@ -318,8 +337,7 @@ TizenResult IotconUtils::ExtractFromResource(const ResourceInfoPtr& pointer, return TizenSuccess(); } -TizenResult IotconUtils::ResourceToJson(ResourceInfoPtr pointer, - picojson::object* res) { +TizenResult IotconUtils::ResourceToJson(ResourceInfoPtr pointer, picojson::object* res) { ScopeLogger(); char* uri_path = nullptr; @@ -327,7 +345,7 @@ TizenResult IotconUtils::ResourceToJson(ResourceInfoPtr pointer, iotcon_resource_interfaces_h ifaces = nullptr; uint8_t properties = 0; auto ret = ExtractFromResource(pointer, &uri_path, &res_types, &ifaces, &properties); - if (!ret){ + if (!ret) { return ret; } res->insert(std::make_pair(kId, picojson::value(static_cast(pointer->id)))); @@ -369,8 +387,8 @@ TizenResult IotconUtils::ExtractFromRemoteResource(RemoteResourceInfo* resource) LogAndReturnTizenError(result, ("Gathering uri path failed")); } - result = ConvertIotconError( - iotcon_remote_resource_get_connectivity_type(resource->resource, &resource->connectivity_type)); + result = ConvertIotconError(iotcon_remote_resource_get_connectivity_type( + resource->resource, &resource->connectivity_type)); if (!result) { LogAndReturnTizenError(result, ("Gathering connectivity type failed")); } @@ -393,8 +411,8 @@ TizenResult IotconUtils::ExtractFromRemoteResource(RemoteResourceInfo* resource) LogAndReturnTizenError(result, ("Gathering device name failed")); } - result = ConvertIotconError( - iotcon_remote_resource_get_types(resource->resource, &resource->types)); + result = + ConvertIotconError(iotcon_remote_resource_get_types(resource->resource, &resource->types)); if (!result) { LogAndReturnTizenError(result, ("Gathering types failed")); } @@ -411,12 +429,12 @@ TizenResult IotconUtils::ExtractFromRemoteResource(RemoteResourceInfo* resource) LogAndReturnTizenError(result, ("Gathering properties failed")); } - result = ConvertIotconError( - iotcon_remote_resource_get_cached_representation(resource->resource, &resource->representation)); + result = ConvertIotconError(iotcon_remote_resource_get_cached_representation( + resource->resource, &resource->representation)); if (!result) { LoggerD("Gathering cached representation failed"); - //TODO check: native method returns error here, now ignoring fail instead of returning error - //LogAndReturnTizenError(result, ("Gathering cached representation failed")); + // TODO check: native method returns error here, now ignoring fail instead of returning error + // LogAndReturnTizenError(result, ("Gathering cached representation failed")); } result = ConvertIotconError( @@ -435,12 +453,12 @@ TizenResult IotconUtils::RemoteResourceToJson(iotcon_remote_resource_h handle, RemoteResourceInfo remote_res; remote_res.resource = handle; auto result = ExtractFromRemoteResource(&remote_res); - if (!result){ + if (!result) { return result; } res->insert(std::make_pair(kUriPath, picojson::value(remote_res.uri_path))); - res->insert(std::make_pair(kConnectivityType, picojson::value( - FromConnectivityType(remote_res.connectivity_type)))); + res->insert(std::make_pair(kConnectivityType, + picojson::value(FromConnectivityType(remote_res.connectivity_type)))); res->insert(std::make_pair(kHostAddress, picojson::value(remote_res.host_address))); res->insert(std::make_pair(kDeviceId, picojson::value(remote_res.device_id))); res->insert(std::make_pair(kDeviceName, picojson::value(remote_res.device_name))); @@ -486,7 +504,7 @@ TizenResult IotconUtils::RemoteResourceToJson(iotcon_remote_resource_h handle, common::TizenResult IotconUtils::RemoteResourceFromJson(const picojson::object& source, FoundRemoteInfoPtr* ptr) { ScopeLogger(); - //checking if resource has id + // checking if resource has id long long id = 0; if (source.find(kId)->second.is()) { id = static_cast(source.find(kId)->second.get()); @@ -506,8 +524,8 @@ common::TizenResult IotconUtils::RemoteResourceFromJson(const picojson::object& } CHECK_EXIST(source, kConnectivityType); - iotcon_connectivity_type_e connectivity_type = IotconUtils::ToConnectivityType( - source.find(kConnectivityType)->second.get()); + iotcon_connectivity_type_e connectivity_type = + IotconUtils::ToConnectivityType(source.find(kConnectivityType)->second.get()); CHECK_EXIST(source, kUriPath); char* uri_path = nullptr; @@ -540,8 +558,8 @@ common::TizenResult IotconUtils::RemoteResourceFromJson(const picojson::object& }; res = IotconUtils::ConvertIotconError( - iotcon_remote_resource_create(host_address, connectivity_type, uri_path, - properties, resource_types, interfaces, &((*ptr)->handle))); + iotcon_remote_resource_create(host_address, connectivity_type, uri_path, properties, + resource_types, interfaces, &((*ptr)->handle))); if (!res) { LogAndReturnTizenError(res, ("creating handle failed")); } @@ -558,7 +576,8 @@ common::TizenResult IotconUtils::RemoteResourceFromJson(const picojson::object& return res; } } - res = IotconUtils::ConvertIotconError(iotcon_remote_resource_set_options((*ptr)->handle, options)); + res = IotconUtils::ConvertIotconError( + iotcon_remote_resource_set_options((*ptr)->handle, options)); if (!res) { LogAndReturnTizenError(res, ("iotcon_response_set_options() failed")); } @@ -567,8 +586,7 @@ common::TizenResult IotconUtils::RemoteResourceFromJson(const picojson::object& return TizenSuccess(); } -common::TizenResult IotconUtils::RequestToJson(iotcon_request_h request, - picojson::object* out) { +common::TizenResult IotconUtils::RequestToJson(iotcon_request_h request, picojson::object* out) { ScopeLogger(); if (request) { @@ -585,11 +603,13 @@ common::TizenResult IotconUtils::RequestToJson(iotcon_request_h request, { // connectivityType iotcon_connectivity_type_e connectivity_type; - auto result = ConvertIotconError(iotcon_request_get_connectivity_type(request, &connectivity_type)); + auto result = + ConvertIotconError(iotcon_request_get_connectivity_type(request, &connectivity_type)); if (!result) { LogAndReturnTizenError(result, ("iotcon_request_get_connectivity_type() failed")); } - out->insert(std::make_pair(kConnectivityType, picojson::value{FromConnectivityType(connectivity_type)})); + out->insert(std::make_pair(kConnectivityType, + picojson::value{FromConnectivityType(connectivity_type)})); } { @@ -654,7 +674,8 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re { // uriPath char* uri_path = nullptr; - auto result = ConvertIotconError(iotcon_representation_get_uri_path(representation, &uri_path)); + auto result = + ConvertIotconError(iotcon_representation_get_uri_path(representation, &uri_path)); if (!result || !uri_path) { LogAndReturnTizenError(result, ("iotcon_representation_get_uri_path() failed")); } @@ -664,19 +685,22 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re { // resourceTypes iotcon_resource_types_h resource_types = nullptr; - auto result = ConvertIotconError(iotcon_representation_get_resource_types(representation, &resource_types)); + auto result = ConvertIotconError( + iotcon_representation_get_resource_types(representation, &resource_types)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_get_resource_types() failed")); } picojson::value v{picojson::array{}}; - iotcon_resource_types_foreach(resource_types, ResourceTypeIterator, &v.get()); + iotcon_resource_types_foreach(resource_types, ResourceTypeIterator, + &v.get()); out->insert(std::make_pair(kResourceTypes, v)); } { // resourceInterfaces iotcon_resource_interfaces_h interfaces = nullptr; - auto result = ConvertIotconError(iotcon_representation_get_resource_interfaces(representation, &interfaces)); + auto result = ConvertIotconError( + iotcon_representation_get_resource_interfaces(representation, &interfaces)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_get_resource_interfaces() failed")); } @@ -691,7 +715,8 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re { // attributes iotcon_attributes_h attributes = nullptr; - auto result = ConvertIotconError(iotcon_representation_get_attributes(representation, &attributes)); + auto result = + ConvertIotconError(iotcon_representation_get_attributes(representation, &attributes)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_get_attributes() failed")); } @@ -706,16 +731,19 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re { // children picojson::value v{picojson::array{}}; - auto result = ConvertIotconError(iotcon_representation_foreach_children(representation, [](iotcon_representation_h child, void* user_data) -> bool { - auto arr = static_cast(user_data); - arr->push_back(picojson::value{picojson::object{}}); - auto result = RepresentationToJson(child, &arr->back().get()); - if (!result) { - LoggerE("Failed to convert child representation"); - } - // always continue with iteration - return true; - }, &v.get())); + auto result = ConvertIotconError(iotcon_representation_foreach_children( + representation, + [](iotcon_representation_h child, void* user_data) -> bool { + auto arr = static_cast(user_data); + arr->push_back(picojson::value{picojson::object{}}); + auto result = RepresentationToJson(child, &arr->back().get()); + if (!result) { + LoggerE("Failed to convert child representation"); + } + // always continue with iteration + return true; + }, + &v.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_foreach_children() failed")); } @@ -729,135 +757,126 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re } common::TizenResult IotconUtils::AttributesToJson(iotcon_attributes_h attributes, - picojson::object* out) { + picojson::object* out) { ScopeLogger(); if (attributes) { - auto result = ConvertIotconError(iotcon_attributes_foreach(attributes, [](iotcon_attributes_h attributes, const char* key, void* user_data) -> bool { - iotcon_type_e type = IOTCON_TYPE_NONE; - auto result = ConvertIotconError(iotcon_attributes_get_type(attributes, key, &type)); - - if (result) { - auto out = static_cast(user_data); - - switch (type) { - case IOTCON_TYPE_NONE: - LoggerE("Key %s has type NONE", key); - break; - - case IOTCON_TYPE_INT: - { - int value = 0; - result = ConvertIotconError(iotcon_attributes_get_int(attributes, key, &value)); - if (result) { - out->insert(std::make_pair(key, picojson::value{static_cast(value)})); - } else { - LoggerE("iotcon_attributes_get_int() failed"); - } - } - break; - - case IOTCON_TYPE_BOOL: - { - bool value = false; - result = ConvertIotconError(iotcon_attributes_get_bool(attributes, key, &value)); - if (result) { - out->insert(std::make_pair(key, picojson::value{value})); - } else { - LoggerE("iotcon_attributes_get_bool() failed"); - } - } - break; - - case IOTCON_TYPE_DOUBLE: - { - double value = 0.0; - result = ConvertIotconError(iotcon_attributes_get_double(attributes, key, &value)); - if (result) { - out->insert(std::make_pair(key, picojson::value{value})); - } else { - LoggerE("iotcon_attributes_get_double() failed"); - } - } - break; - - case IOTCON_TYPE_STR: - { - char* value = nullptr; - result = ConvertIotconError(iotcon_attributes_get_str(attributes, key, &value)); - if (result && value) { - out->insert(std::make_pair(key, picojson::value{value})); - } else { - LoggerE("iotcon_attributes_get_str() failed"); - } - } - break; - - case IOTCON_TYPE_BYTE_STR: - { - unsigned char* value = nullptr; - int length = 0; - result = ConvertIotconError(iotcon_attributes_get_byte_str(attributes, key, &value, &length)); - - if (result && length) { - std::unique_ptr data{new char[2 * length]}; - common::tools::BinToHex(value, length, data.get(), 2 * length); - out->insert(std::make_pair(key, picojson::value{kHexPrefix + data.get()})); - } else { - LoggerE("iotcon_attributes_get_byte_str() failed"); - } - } - break; - - case IOTCON_TYPE_NULL: - out->insert(std::make_pair(key, picojson::value{})); - break; + auto result = ConvertIotconError(iotcon_attributes_foreach( + attributes, + [](iotcon_attributes_h attributes, const char* key, void* user_data) -> bool { + iotcon_type_e type = IOTCON_TYPE_NONE; + auto result = ConvertIotconError(iotcon_attributes_get_type(attributes, key, &type)); - case IOTCON_TYPE_LIST: - { - iotcon_list_h list = nullptr; - result = ConvertIotconError(iotcon_attributes_get_list(attributes, key, &list)); - if (result) { - picojson::value value{picojson::array{}}; - - result = StateListToJson(list, &value.get()); - if (result) { - out->insert(std::make_pair(key, picojson::value{value})); - } else { - LoggerE("StateListToJson() failed"); - } - } else { - LoggerE("iotcon_attributes_get_list() failed"); - } - } - break; - - case IOTCON_TYPE_ATTRIBUTES: - { - iotcon_attributes_h child = nullptr; - result = ConvertIotconError(iotcon_attributes_get_attributes(attributes, key, &child)); - if (result) { - picojson::value value{picojson::object{}}; - - result = AttributesToJson(child, &value.get()); - if (result) { - out->insert(std::make_pair(key, picojson::value{value})); - } else { - LoggerE("AttributesToJson() failed"); - } - } else { - LoggerE("iotcon_attributes_get_attributes() failed"); + if (result) { + auto out = static_cast(user_data); + + switch (type) { + case IOTCON_TYPE_NONE: + LoggerE("Key %s has type NONE", key); + break; + + case IOTCON_TYPE_INT: { + int value = 0; + result = ConvertIotconError(iotcon_attributes_get_int(attributes, key, &value)); + if (result) { + out->insert(std::make_pair(key, picojson::value{static_cast(value)})); + } else { + LoggerE("iotcon_attributes_get_int() failed"); + } + } break; + + case IOTCON_TYPE_BOOL: { + bool value = false; + result = ConvertIotconError(iotcon_attributes_get_bool(attributes, key, &value)); + if (result) { + out->insert(std::make_pair(key, picojson::value{value})); + } else { + LoggerE("iotcon_attributes_get_bool() failed"); + } + } break; + + case IOTCON_TYPE_DOUBLE: { + double value = 0.0; + result = ConvertIotconError(iotcon_attributes_get_double(attributes, key, &value)); + if (result) { + out->insert(std::make_pair(key, picojson::value{value})); + } else { + LoggerE("iotcon_attributes_get_double() failed"); + } + } break; + + case IOTCON_TYPE_STR: { + char* value = nullptr; + result = ConvertIotconError(iotcon_attributes_get_str(attributes, key, &value)); + if (result && value) { + out->insert(std::make_pair(key, picojson::value{value})); + } else { + LoggerE("iotcon_attributes_get_str() failed"); + } + } break; + + case IOTCON_TYPE_BYTE_STR: { + unsigned char* value = nullptr; + int length = 0; + result = ConvertIotconError( + iotcon_attributes_get_byte_str(attributes, key, &value, &length)); + + if (result && length) { + std::unique_ptr data{new char[2 * length]}; + common::tools::BinToHex(value, length, data.get(), 2 * length); + out->insert(std::make_pair(key, picojson::value{kHexPrefix + data.get()})); + } else { + LoggerE("iotcon_attributes_get_byte_str() failed"); + } + } break; + + case IOTCON_TYPE_NULL: + out->insert(std::make_pair(key, picojson::value{})); + break; + + case IOTCON_TYPE_LIST: { + iotcon_list_h list = nullptr; + result = ConvertIotconError(iotcon_attributes_get_list(attributes, key, &list)); + if (result) { + picojson::value value{picojson::array{}}; + + result = StateListToJson(list, &value.get()); + if (result) { + out->insert(std::make_pair(key, picojson::value{value})); + } else { + LoggerE("StateListToJson() failed"); + } + } else { + LoggerE("iotcon_attributes_get_list() failed"); + } + } break; + + case IOTCON_TYPE_ATTRIBUTES: { + iotcon_attributes_h child = nullptr; + result = + ConvertIotconError(iotcon_attributes_get_attributes(attributes, key, &child)); + if (result) { + picojson::value value{picojson::object{}}; + + result = AttributesToJson(child, &value.get()); + if (result) { + out->insert(std::make_pair(key, picojson::value{value})); + } else { + LoggerE("AttributesToJson() failed"); + } + } else { + LoggerE("iotcon_attributes_get_attributes() failed"); + } + } break; } + } else { + LoggerE("iotcon_attributes_get_type() failed"); } - break; - } - } else { - LoggerE("iotcon_attributes_get_type() failed"); - } - // always continue with iteration - return true; - }, out)); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_foreach() failed")); @@ -869,8 +888,7 @@ common::TizenResult IotconUtils::AttributesToJson(iotcon_attributes_h attributes return TizenSuccess(); } -common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, - picojson::array* out) { +common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, picojson::array* out) { ScopeLogger(); if (list) { @@ -887,67 +905,82 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, break; case IOTCON_TYPE_INT: - result = ConvertIotconError(iotcon_list_foreach_int(list, [](int, int value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{static_cast(value)}); - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError( + iotcon_list_foreach_int(list, + [](int, int value, void* user_data) -> bool { + auto out = static_cast(user_data); + out->push_back(picojson::value{static_cast(value)}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_int() failed")); } break; case IOTCON_TYPE_BOOL: - result = ConvertIotconError(iotcon_list_foreach_bool(list, [](int, bool value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError( + iotcon_list_foreach_bool(list, + [](int, bool value, void* user_data) -> bool { + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_bool() failed")); } break; case IOTCON_TYPE_DOUBLE: - result = ConvertIotconError(iotcon_list_foreach_double(list, [](int, double value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError( + iotcon_list_foreach_double(list, + [](int, double value, void* user_data) -> bool { + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_double() failed")); } break; case IOTCON_TYPE_STR: - result = ConvertIotconError(iotcon_list_foreach_str(list, [](int, const char* value, void* user_data) -> bool { - if (value) { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - } - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError( + iotcon_list_foreach_str(list, + [](int, const char* value, void* user_data) -> bool { + if (value) { + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_str() failed")); } break; case IOTCON_TYPE_BYTE_STR: - result = ConvertIotconError(iotcon_list_foreach_byte_str(list, [](int, const unsigned char* value, int length, void* user_data) -> bool { - if (length) { - std::unique_ptr data{new char[2 * length]}; - common::tools::BinToHex(value, length, data.get(), 2 * length); - - auto out = static_cast(user_data); - out->push_back(picojson::value{kHexPrefix + data.get()}); - } - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError(iotcon_list_foreach_byte_str( + list, + [](int, const unsigned char* value, int length, void* user_data) -> bool { + if (length) { + std::unique_ptr data{new char[2 * length]}; + common::tools::BinToHex(value, length, data.get(), 2 * length); + + auto out = static_cast(user_data); + out->push_back(picojson::value{kHexPrefix + data.get()}); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_str() failed")); } @@ -958,36 +991,42 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, break; case IOTCON_TYPE_LIST: - result = ConvertIotconError(iotcon_list_foreach_list(list, [](int, iotcon_list_h list, void* user_data) -> bool { - picojson::value value{picojson::array{}}; - auto result = StateListToJson(list, &value.get()); - if (result) { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - } else { - LoggerE("StateListToJson() failed"); - } - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError(iotcon_list_foreach_list( + list, + [](int, iotcon_list_h list, void* user_data) -> bool { + picojson::value value{picojson::array{}}; + auto result = StateListToJson(list, &value.get()); + if (result) { + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + } else { + LoggerE("StateListToJson() failed"); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_list() failed")); } break; case IOTCON_TYPE_ATTRIBUTES: - result = ConvertIotconError(iotcon_list_foreach_attributes(list, [](int, iotcon_attributes_h attributes, void* user_data) -> bool { - picojson::value value{picojson::object{}}; - auto result = AttributesToJson(attributes, &value.get()); - if (result) { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - } else { - LoggerE("AttributesToJson() failed"); - } - // always continue with iteration - return true; - }, out)); + result = ConvertIotconError(iotcon_list_foreach_attributes( + list, + [](int, iotcon_attributes_h attributes, void* user_data) -> bool { + picojson::value value{picojson::object{}}; + auto result = AttributesToJson(attributes, &value.get()); + if (result) { + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + } else { + LoggerE("AttributesToJson() failed"); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_attributes() failed")); } @@ -1000,25 +1039,27 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, return TizenSuccess(); } -common::TizenResult IotconUtils::OptionsToJson(iotcon_options_h options, - picojson::array* out) { +common::TizenResult IotconUtils::OptionsToJson(iotcon_options_h options, picojson::array* out) { ScopeLogger(); if (options) { - auto result = ConvertIotconError(iotcon_options_foreach(options, [](unsigned short id, const char *data, void* user_data) -> bool { - if (data) { - picojson::value v{picojson::object{}}; - auto& obj = v.get(); + auto result = ConvertIotconError(iotcon_options_foreach( + options, + [](unsigned short id, const char* data, void* user_data) -> bool { + if (data) { + picojson::value v{picojson::object{}}; + auto& obj = v.get(); - obj.insert(std::make_pair(kOptionsId, picojson::value{static_cast(id)})); - obj.insert(std::make_pair(kOptionsData, picojson::value{data})); + obj.insert(std::make_pair(kOptionsId, picojson::value{static_cast(id)})); + obj.insert(std::make_pair(kOptionsData, picojson::value{data})); - auto out = static_cast(user_data); - out->push_back(v); - } - // always continue with iteration - return true; - }, out)); + auto out = static_cast(user_data); + out->push_back(v); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_options_foreach() failed")); @@ -1030,8 +1071,7 @@ common::TizenResult IotconUtils::OptionsToJson(iotcon_options_h options, return TizenSuccess(); } -common::TizenResult IotconUtils::QueryToJson(iotcon_query_h query, - picojson::object* out) { +common::TizenResult IotconUtils::QueryToJson(iotcon_query_h query, picojson::object* out) { ScopeLogger(); if (query) { @@ -1058,14 +1098,17 @@ common::TizenResult IotconUtils::QueryToJson(iotcon_query_h query, { // filter picojson::value v{picojson::object{}}; - auto result = ConvertIotconError(iotcon_query_foreach(query, [](const char* key, const char* value, void* user_data) -> bool { - if (key && value) { - auto obj = static_cast(user_data); - obj->insert(std::make_pair(key, picojson::value{value})); - } - // always continue with iteration - return true; - }, &v.get())); + auto result = ConvertIotconError( + iotcon_query_foreach(query, + [](const char* key, const char* value, void* user_data) -> bool { + if (key && value) { + auto obj = static_cast(user_data); + obj->insert(std::make_pair(key, picojson::value{value})); + } + // always continue with iteration + return true; + }, + &v.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_query_foreach() failed")); } @@ -1077,15 +1120,16 @@ common::TizenResult IotconUtils::QueryToJson(iotcon_query_h query, return TizenSuccess(); } -common::TizenResult IotconUtils::QueryFromJson(const picojson::object& source, iotcon_query_h* res) { +common::TizenResult IotconUtils::QueryFromJson(const picojson::object& source, + iotcon_query_h* res) { ScopeLogger(); iotcon_query_h query = nullptr; auto result = ConvertIotconError(iotcon_query_create(&query)); if (!result) { LogAndReturnTizenError(result, ("iotcon_query_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_query_h)> - query_ptr(query, &iotcon_query_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(iotcon_query_h)> query_ptr( + query, &iotcon_query_destroy); // automatically release the memory { // resourceType auto it = source.find(kResourceType); @@ -1118,7 +1162,7 @@ common::TizenResult IotconUtils::QueryFromJson(const picojson::object& source, i if (filter.is()) { const auto& filter_obj = filter.get(); for (const auto it : filter_obj) { - if (it.second.is()){ + if (it.second.is()) { const std::string& key = it.first; const std::string& value = it.second.get(); LoggerD("key: %s ---- value: %s", key.c_str(), value.c_str()); @@ -1137,8 +1181,7 @@ common::TizenResult IotconUtils::QueryFromJson(const picojson::object& source, i return TizenSuccess(); } -common::TizenResult IotconUtils::ResponseToJson(iotcon_response_h handle, - picojson::object* res) { +common::TizenResult IotconUtils::ResponseToJson(iotcon_response_h handle, picojson::object* res) { ScopeLogger(); if (handle) { @@ -1206,15 +1249,19 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt LogAndReturnTizenError(result, ("iotcon_representation_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_representation_h)> ptr{representation, &iotcon_representation_destroy}; + std::unique_ptr::type, + int (*)(iotcon_representation_h)> + ptr{representation, &iotcon_representation_destroy}; { char* uri_path = nullptr; - result = IotconUtils::ConvertIotconError(iotcon_resource_get_uri_path(resource->handle, &uri_path)); + result = + IotconUtils::ConvertIotconError(iotcon_resource_get_uri_path(resource->handle, &uri_path)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_get_uri_path() failed")); } - result = IotconUtils::ConvertIotconError(iotcon_representation_set_uri_path(representation, uri_path)); + result = IotconUtils::ConvertIotconError( + iotcon_representation_set_uri_path(representation, uri_path)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_uri_path() failed")); } @@ -1226,7 +1273,8 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_get_types() failed")); } - result = IotconUtils::ConvertIotconError(iotcon_representation_set_resource_types(representation, types)); + result = IotconUtils::ConvertIotconError( + iotcon_representation_set_resource_types(representation, types)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_resource_types() failed")); } @@ -1234,11 +1282,13 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt { iotcon_resource_interfaces_h intrefaces = nullptr; - result = IotconUtils::ConvertIotconError(iotcon_resource_get_interfaces(resource->handle, &intrefaces)); + result = IotconUtils::ConvertIotconError( + iotcon_resource_get_interfaces(resource->handle, &intrefaces)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_get_interfaces() failed")); } - result = IotconUtils::ConvertIotconError(iotcon_representation_set_resource_interfaces(representation, intrefaces)); + result = IotconUtils::ConvertIotconError( + iotcon_representation_set_resource_interfaces(representation, intrefaces)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_resource_interfaces() failed")); } @@ -1255,7 +1305,8 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt SCOPE_EXIT { iotcon_attributes_destroy(attributes_handle); }; - result = IotconUtils::ConvertIotconError(iotcon_representation_set_attributes(representation, attributes_handle)); + result = IotconUtils::ConvertIotconError( + iotcon_representation_set_attributes(representation, attributes_handle)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_attributes() failed")); } @@ -1264,14 +1315,16 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt { unsigned int children = 0; - result = IotconUtils::ConvertIotconError(iotcon_resource_get_child_count(resource->handle, &children)); + result = IotconUtils::ConvertIotconError( + iotcon_resource_get_child_count(resource->handle, &children)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_get_child_count() failed")); } for (unsigned int i = 0; i < children; ++i) { iotcon_resource_h child = nullptr; - result = IotconUtils::ConvertIotconError(iotcon_resource_get_nth_child(resource->handle, i, &child)); + result = IotconUtils::ConvertIotconError( + iotcon_resource_get_nth_child(resource->handle, i, &child)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_get_nth_child() failed")); } @@ -1290,7 +1343,8 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt SCOPE_EXIT { iotcon_representation_destroy(child_representation); }; - result = IotconUtils::ConvertIotconError(iotcon_representation_add_child(representation, child_representation)); + result = IotconUtils::ConvertIotconError( + iotcon_representation_add_child(representation, child_representation)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_add_child() failed")); } @@ -1302,7 +1356,7 @@ common::TizenResult IotconUtils::RepresentationFromResource(const ResourceInfoPt } common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, - iotcon_attributes_h* out) { + iotcon_attributes_h* out) { ScopeLogger(); iotcon_attributes_h attributes = nullptr; @@ -1312,7 +1366,8 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, LogAndReturnTizenError(result, ("iotcon_attributes_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_attributes_h)> ptr{attributes, &iotcon_attributes_destroy}; + std::unique_ptr::type, int (*)(iotcon_attributes_h)> ptr{ + attributes, &iotcon_attributes_destroy}; for (const auto& property : s) { const auto& key = property.first; @@ -1323,12 +1378,14 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, LogAndReturnTizenError(result, ("iotcon_attributes_add_null() failed")); } } else if (property.second.is()) { - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_bool(attributes, key.c_str(), property.second.get())); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_bool(attributes, key.c_str(), property.second.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_add_bool() failed")); } } else if (property.second.is()) { - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_double(attributes, key.c_str(), property.second.get())); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_double(attributes, key.c_str(), property.second.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_attributes_double() failed")); } @@ -1336,17 +1393,19 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, const auto& value = property.second.get(); if (0 == value.find(kHexPrefix)) { - auto data = value.c_str() + kHexPrefix.length(); // skip prefix + auto data = value.c_str() + kHexPrefix.length(); // skip prefix auto size = value.length() - kHexPrefix.length(); auto length = size / 2; std::unique_ptr hex{new unsigned char[length]}; common::tools::HexToBin(data, size, hex.get(), length); - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_byte_str(attributes, key.c_str(), hex.get(), length)); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_byte_str(attributes, key.c_str(), hex.get(), length)); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_add_byte_str() failed")); } } else { - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_str(attributes, key.c_str(), const_cast(value.c_str()))); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_str(attributes, key.c_str(), const_cast(value.c_str()))); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_add_str() failed")); } @@ -1361,7 +1420,8 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, SCOPE_EXIT { iotcon_list_destroy(list); }; - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_list(attributes, key.c_str(), list)); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_list(attributes, key.c_str(), list)); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_add_list() failed")); } @@ -1375,7 +1435,8 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, SCOPE_EXIT { iotcon_attributes_destroy(sub_attributes); }; - result = IotconUtils::ConvertIotconError(iotcon_attributes_add_attributes(attributes, key.c_str(), sub_attributes)); + result = IotconUtils::ConvertIotconError( + iotcon_attributes_add_attributes(attributes, key.c_str(), sub_attributes)); if (!result) { LogAndReturnTizenError(result, ("iotcon_attributes_add_attributes() failed")); } @@ -1386,8 +1447,7 @@ common::TizenResult IotconUtils::AttributesFromJson(const picojson::object& s, return TizenSuccess(); } -common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, - iotcon_list_h* out) { +common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, iotcon_list_h* out) { ScopeLogger(); iotcon_list_h list = nullptr; @@ -1422,7 +1482,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, LogAndReturnTizenError(result, ("iotcon_list_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_list_h)> ptr{list, &iotcon_list_destroy}; + std::unique_ptr::type, int (*)(iotcon_list_h)> ptr{ + list, &iotcon_list_destroy}; int position = 0; @@ -1431,7 +1492,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, switch (type) { case IOTCON_TYPE_BOOL: if (v.is()) { - result = IotconUtils::ConvertIotconError(iotcon_list_add_bool(list, v.get(), position++)); + result = IotconUtils::ConvertIotconError( + iotcon_list_add_bool(list, v.get(), position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_bool() failed")); } @@ -1440,7 +1502,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, case IOTCON_TYPE_DOUBLE: if (v.is()) { - result = IotconUtils::ConvertIotconError(iotcon_list_add_double(list, v.get(), position++)); + result = IotconUtils::ConvertIotconError( + iotcon_list_add_double(list, v.get(), position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_double() failed")); } @@ -1451,12 +1514,13 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, if (v.is()) { const auto& str = v.get(); if (0 == str.find(kHexPrefix)) { - auto data = str.c_str() + kHexPrefix.length(); // skip prefix + auto data = str.c_str() + kHexPrefix.length(); // skip prefix auto size = str.length() - kHexPrefix.length(); auto length = size / 2; std::unique_ptr hex{new unsigned char[length]}; common::tools::HexToBin(data, size, hex.get(), length); - result = IotconUtils::ConvertIotconError(iotcon_list_add_byte_str(list, hex.get(), length, position++)); + result = IotconUtils::ConvertIotconError( + iotcon_list_add_byte_str(list, hex.get(), length, position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_byte_str() failed")); } @@ -1466,7 +1530,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, case IOTCON_TYPE_STR: if (v.is()) { - result = IotconUtils::ConvertIotconError(iotcon_list_add_str(list, const_cast(v.get().c_str()), position++)); + result = IotconUtils::ConvertIotconError(iotcon_list_add_str( + list, const_cast(v.get().c_str()), position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_str() failed")); } @@ -1483,7 +1548,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, SCOPE_EXIT { iotcon_list_destroy(sub_list); }; - result = IotconUtils::ConvertIotconError(iotcon_list_add_list(list, sub_list, position++)); + result = + IotconUtils::ConvertIotconError(iotcon_list_add_list(list, sub_list, position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_list() failed")); } @@ -1500,7 +1566,8 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, SCOPE_EXIT { iotcon_attributes_destroy(attributes); }; - result = IotconUtils::ConvertIotconError(iotcon_list_add_attributes(list, attributes, position++)); + result = IotconUtils::ConvertIotconError( + iotcon_list_add_attributes(list, attributes, position++)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_add_attributes() failed")); } @@ -1518,16 +1585,15 @@ common::TizenResult IotconUtils::StateListFromJson(const picojson::array& l, return TizenSuccess(); } -common::TizenResult IotconUtils::PresenceResponseToJson( - iotcon_presence_response_h presence, picojson::object* out) { +common::TizenResult IotconUtils::PresenceResponseToJson(iotcon_presence_response_h presence, + picojson::object* out) { ScopeLogger(); if (presence) { { // hostAddress char* host = nullptr; - auto result = ConvertIotconError(iotcon_presence_response_get_host_address(presence, - &host)); + auto result = ConvertIotconError(iotcon_presence_response_get_host_address(presence, &host)); if (!result || !host) { LogAndReturnTizenError(result, ("iotcon_presence_response_get_host_address() failed")); } @@ -1537,20 +1603,20 @@ common::TizenResult IotconUtils::PresenceResponseToJson( { // connectivityType iotcon_connectivity_type_e con_type; - auto result = ConvertIotconError(iotcon_presence_response_get_connectivity_type(presence, - &con_type)); + auto result = + ConvertIotconError(iotcon_presence_response_get_connectivity_type(presence, &con_type)); if (!result) { LogAndReturnTizenError(result, ("iotcon_presence_response_get_connectivity_type() failed")); } - out->insert(std::make_pair(kConnectivityType, picojson::value{ - FromConnectivityType(con_type)})); + out->insert( + std::make_pair(kConnectivityType, picojson::value{FromConnectivityType(con_type)})); } { // resourceType char* resource_type = nullptr; - auto result = ConvertIotconError(iotcon_presence_response_get_resource_type(presence, - &resource_type)); + auto result = + ConvertIotconError(iotcon_presence_response_get_resource_type(presence, &resource_type)); if (!result || !resource_type) { LoggerE("iotcon_presence_response_get_resource_type() failed"); out->insert(std::make_pair(kResourceType, picojson::value())); @@ -1562,28 +1628,27 @@ common::TizenResult IotconUtils::PresenceResponseToJson( // resultType iotcon_presence_result_e result_type = IOTCON_PRESENCE_OK; { - auto result = ConvertIotconError(iotcon_presence_response_get_result(presence, - &result_type)); + auto result = ConvertIotconError(iotcon_presence_response_get_result(presence, &result_type)); if (!result) { LogAndReturnTizenError(result, ("iotcon_presence_response_get_result() failed")); } - out->insert(std::make_pair(kResultType, picojson::value{ - FromPresenceResponseResultType(result_type)})); + out->insert(std::make_pair(kResultType, + picojson::value{FromPresenceResponseResultType(result_type)})); } { // triggerType iotcon_presence_trigger_e trigger_type = IOTCON_PRESENCE_RESOURCE_CREATED; if (IOTCON_PRESENCE_OK == result_type) { - auto result = ConvertIotconError(iotcon_presence_response_get_trigger(presence, - &trigger_type)); + auto result = + ConvertIotconError(iotcon_presence_response_get_trigger(presence, &trigger_type)); if (!result) { LoggerE("iotcon_presence_response_get_trigger() failed"); out->insert(std::make_pair(kTriggerType, picojson::value())); } else { - out->insert(std::make_pair(kTriggerType, picojson::value{FromPresenceTriggerType( - trigger_type)})); + out->insert( + std::make_pair(kTriggerType, picojson::value{FromPresenceTriggerType(trigger_type)})); } } else { out->insert(std::make_pair(kTriggerType, picojson::value())); @@ -1602,29 +1667,25 @@ common::TizenResult IotconUtils::ExtractFromPresenceEvent(const PresenceEventPtr char** resource_type) { ScopeLogger(); - auto result = ConvertIotconError(iotcon_presence_get_host_address(pointer->handle, - host)); + auto result = ConvertIotconError(iotcon_presence_get_host_address(pointer->handle, host)); if (!result) { - LogAndReturnTizenError(result, ("Gathering presence host address failed")); + LogAndReturnTizenError(result, ("Gathering presence host address failed")); } - result = ConvertIotconError(iotcon_presence_get_connectivity_type(pointer->handle, - con_type)); + result = ConvertIotconError(iotcon_presence_get_connectivity_type(pointer->handle, con_type)); if (!result) { - LogAndReturnTizenError(result, ("Gathering presence connectivity type failed")); + LogAndReturnTizenError(result, ("Gathering presence connectivity type failed")); } - result = ConvertIotconError(iotcon_presence_get_resource_type(pointer->handle, - resource_type)); + result = ConvertIotconError(iotcon_presence_get_resource_type(pointer->handle, resource_type)); if (!result) { - LogAndReturnTizenError(result, ("Gathering presence resource type failed")); + LogAndReturnTizenError(result, ("Gathering presence resource type failed")); } return TizenSuccess(); } -common::TizenResult IotconUtils::OptionsFromJson(const picojson::array& o, - iotcon_options_h* out) { +common::TizenResult IotconUtils::OptionsFromJson(const picojson::array& o, iotcon_options_h* out) { ScopeLogger(); iotcon_options_h options = nullptr; @@ -1634,7 +1695,8 @@ common::TizenResult IotconUtils::OptionsFromJson(const picojson::array& o, LogAndReturnTizenError(result, ("iotcon_options_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_options_h)> ptr{options, &iotcon_options_destroy}; + std::unique_ptr::type, int (*)(iotcon_options_h)> ptr{ + options, &iotcon_options_destroy}; // we ignore values with incorrect types // TODO: should we convert them in JS? @@ -1644,7 +1706,8 @@ common::TizenResult IotconUtils::OptionsFromJson(const picojson::array& o, const auto& js_data = option.get(kOptionsData); if (js_id.is() && js_data.is()) { - result = ConvertIotconError(iotcon_options_add(options, js_id.get(), js_data.get().c_str())); + result = ConvertIotconError( + iotcon_options_add(options, js_id.get(), js_data.get().c_str())); if (!result) { LogAndReturnTizenError(result, ("iotcon_options_add() failed")); } @@ -1667,17 +1730,22 @@ common::TizenResult IotconUtils::RepresentationFromJson(const picojson::object& LogAndReturnTizenError(result, ("iotcon_representation_create() failed")); } - std::unique_ptr::type, int(*)(iotcon_representation_h)> ptr{representation, &iotcon_representation_destroy}; + std::unique_ptr::type, + int (*)(iotcon_representation_h)> + ptr{representation, &iotcon_representation_destroy}; { const auto& uri_path = r.find(kUriPath); if (r.end() != uri_path && uri_path->second.is()) { - result = ConvertIotconError(iotcon_representation_set_uri_path(representation, uri_path->second.get().c_str())); + result = ConvertIotconError(iotcon_representation_set_uri_path( + representation, uri_path->second.get().c_str())); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_uri_path() failed")); } } else { - return LogAndCreateTizenError(TypeMismatchError, "Representation object needs to have an uriPath attribute which is a string."); + return LogAndCreateTizenError( + TypeMismatchError, + "Representation object needs to have an uriPath attribute which is a string."); } } @@ -1699,7 +1767,9 @@ common::TizenResult IotconUtils::RepresentationFromJson(const picojson::object& LogAndReturnTizenError(result, ("iotcon_representation_set_resource_types() failed")); } } else { - return LogAndCreateTizenError(TypeMismatchError, "Representation object needs to have a resourceTypes attribute which is an array."); + return LogAndCreateTizenError( + TypeMismatchError, + "Representation object needs to have a resourceTypes attribute which is an array."); } } @@ -1715,12 +1785,15 @@ common::TizenResult IotconUtils::RepresentationFromJson(const picojson::object& SCOPE_EXIT { iotcon_resource_interfaces_destroy(interfaces); }; - result = ConvertIotconError(iotcon_representation_set_resource_interfaces(representation, interfaces)); + result = ConvertIotconError( + iotcon_representation_set_resource_interfaces(representation, interfaces)); if (!result) { LogAndReturnTizenError(result, ("iotcon_representation_set_resource_interfaces() failed")); } } else { - return LogAndCreateTizenError(TypeMismatchError, "Representation object needs to have a resourceInterfaces attribute which is an array."); + return LogAndCreateTizenError( + TypeMismatchError, + "Representation object needs to have a resourceInterfaces attribute which is an array."); } } @@ -1764,7 +1837,9 @@ common::TizenResult IotconUtils::RepresentationFromJson(const picojson::object& LogAndReturnTizenError(result, ("iotcon_representation_add_child() failed")); } } else { - return LogAndCreateTizenError(TypeMismatchError, "The Representation.children attribute needs to be an array of Representation objects."); + return LogAndCreateTizenError(TypeMismatchError, + "The Representation.children attribute needs to be an " + "array of Representation objects."); } } } @@ -1781,18 +1856,17 @@ common::TizenResult IotconUtils::PlatformInfoGetProperty(iotcon_platform_info_h ScopeLogger(); char* property = nullptr; - auto result = ConvertIotconError(iotcon_platform_info_get_property(platform, - property_e, - &property)); + auto result = + ConvertIotconError(iotcon_platform_info_get_property(platform, property_e, &property)); if (!result) { LogAndReturnTizenError(result, ("iotcon_platform_info_get_property() failed")); } if (!property) { out->insert(std::make_pair(name, picojson::value{""})); - }else{ + } else { out->insert(std::make_pair(name, picojson::value{property})); - } + } return TizenSuccess(); } @@ -1803,8 +1877,7 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // platformId - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_ID, - kPlatformId, out); + auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_ID, kPlatformId, out); if (!result) { return result; } @@ -1812,8 +1885,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // manufacturerName - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MANUF_NAME, - kManufacturerName, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MANUF_NAME, kManufacturerName, out); if (!result) { return result; } @@ -1821,8 +1894,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // manufacturerUrl - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MANUF_URL, - kManufacturerUrl, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MANUF_URL, kManufacturerUrl, out); if (!result) { return result; } @@ -1830,8 +1903,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // modelNumber - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MODEL_NUMBER, - kModelNumber, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_MODEL_NUMBER, kModelNumber, out); if (!result) { return result; } @@ -1848,8 +1921,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // platformVersion - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_PLATFORM_VER, - kPlatformVersion, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_PLATFORM_VER, kPlatformVersion, out); if (!result) { return result; } @@ -1866,8 +1939,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // hardwareVersion - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_HARDWARE_VER, - kHardwareVersion, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_HARDWARE_VER, kHardwareVersion, out); if (!result) { return result; } @@ -1875,8 +1948,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // firmwareVersion - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_FIRMWARE_VER, - kFirmwareVersion, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_FIRMWARE_VER, kFirmwareVersion, out); if (!result) { return result; } @@ -1884,8 +1957,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // supportUrl - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_SUPPORT_URL, - kSupportUrl, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_SUPPORT_URL, kSupportUrl, out); if (!result) { return result; } @@ -1893,8 +1966,8 @@ common::TizenResult IotconUtils::PlatformInfoToJson(iotcon_platform_info_h platf { // systemTime - auto result = PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_SYSTEM_TIME, - kSystemTime, out); + auto result = + PlatformInfoGetProperty(platform, IOTCON_PLATFORM_INFO_SYSTEM_TIME, kSystemTime, out); if (!result) { return result; } @@ -1909,16 +1982,14 @@ common::TizenResult IotconUtils::DeviceInfoGetProperty(iotcon_device_info_h devi ScopeLogger(); char* property = nullptr; - auto result = ConvertIotconError(iotcon_device_info_get_property(device, - property_e, - &property)); - if (!result ) { + auto result = ConvertIotconError(iotcon_device_info_get_property(device, property_e, &property)); + if (!result) { LogAndReturnTizenError(result, ("iotcon_device_info_get_property() failed")); } if (!property) { out->insert(std::make_pair(name, picojson::value{""})); - }else{ + } else { out->insert(std::make_pair(name, picojson::value{property})); } @@ -1931,8 +2002,7 @@ common::TizenResult IotconUtils::DeviceInfoToJson(iotcon_device_info_h device, { // deviceName - auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_NAME, - kDeviceName, out); + auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_NAME, kDeviceName, out); if (!result) { return result; } @@ -1940,8 +2010,7 @@ common::TizenResult IotconUtils::DeviceInfoToJson(iotcon_device_info_h device, { // specVersion - auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_SPEC_VER, - kSpecVersion, out); + auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_SPEC_VER, kSpecVersion, out); if (!result) { return result; } @@ -1949,8 +2018,7 @@ common::TizenResult IotconUtils::DeviceInfoToJson(iotcon_device_info_h device, { // oicDeviceId - auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_ID, - kOicDeviceId, out); + auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_ID, kOicDeviceId, out); if (!result) { return result; } @@ -1958,8 +2026,8 @@ common::TizenResult IotconUtils::DeviceInfoToJson(iotcon_device_info_h device, { // dataModelVersion - auto result = DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_DATA_MODEL_VER, - kDataModelVersion, out); + auto result = + DeviceInfoGetProperty(device, IOTCON_DEVICE_INFO_DATA_MODEL_VER, kDataModelVersion, out); if (!result) { return result; } @@ -2004,65 +2072,56 @@ common::TizenResult IotconUtils::ConvertIotconError(int error) { } } -#define X(v, s) case v: return s; -#define XD(v, s) \ - default: \ +#define X(v, s) \ + case v: \ + return s; +#define XD(v, s) \ + default: \ LoggerE("Unknown value: %d, returning default: %s", e, s); \ return s; std::string IotconUtils::FromConnectivityType(iotcon_connectivity_type_e e) { ScopeLogger(); - switch (e) { - IOTCON_CONNECTIVITY_TYPE_E - } + switch (e) { IOTCON_CONNECTIVITY_TYPE_E } } std::string IotconUtils::FromRequestType(iotcon_request_type_e e) { ScopeLogger(); - switch (e) { - IOTCON_REQUEST_TYPE_E - } + switch (e) { IOTCON_REQUEST_TYPE_E } } std::string IotconUtils::FromObserveType(iotcon_observe_type_e e) { ScopeLogger(); - switch (e) { - IOTCON_OBSERVE_TYPE_E - } + switch (e) { IOTCON_OBSERVE_TYPE_E } } std::string IotconUtils::FromPresenceResponseResultType(iotcon_presence_result_e e) { ScopeLogger(); - switch (e) { - IOTCON_PRESENCE_RESULT_E - } + switch (e) { IOTCON_PRESENCE_RESULT_E } } std::string IotconUtils::FromPresenceTriggerType(iotcon_presence_trigger_e e) { ScopeLogger(); - switch (e) { - IOTCON_PRESENCE_TRIGGER_E - } + switch (e) { IOTCON_PRESENCE_TRIGGER_E } } std::string IotconUtils::FromResponseResultType(iotcon_response_result_e e) { ScopeLogger(); - switch (e) { - IOTCON_RESPONSE_RESULT_E - } + switch (e) { IOTCON_RESPONSE_RESULT_E } } #undef X #undef XD -#define X(v, s) if (e == s) return v; -#define XD(v, s) \ +#define X(v, s) \ + if (e == s) return v; +#define XD(v, s) \ LoggerE("Unknown value: %s, returning default: %d", e.c_str(), v); \ return v; @@ -2084,19 +2143,19 @@ int IotconUtils::ToConnectivityType2(const std::string& connectivity_type) { if (connectivity_type == "IP") { ret = IOTCON_CONNECTIVITY_IP; } else if (connectivity_type == "PREFER_UDP") { - ret = IOTCON_CONNECTIVITY_IP|IOTCON_CONNECTIVITY_PREFER_UDP; + ret = IOTCON_CONNECTIVITY_IP | IOTCON_CONNECTIVITY_PREFER_UDP; } else if (connectivity_type == "PREFER_TCP") { - ret = IOTCON_CONNECTIVITY_IP|IOTCON_CONNECTIVITY_PREFER_TCP; + ret = IOTCON_CONNECTIVITY_IP | IOTCON_CONNECTIVITY_PREFER_TCP; } else if (connectivity_type == "IPV4_ONLY") { - ret = IOTCON_CONNECTIVITY_IP|IOTCON_CONNECTIVITY_IPV4_ONLY|IOTCON_CONNECTIVITY_PREFER_UDP; + ret = IOTCON_CONNECTIVITY_IP | IOTCON_CONNECTIVITY_IPV4_ONLY | IOTCON_CONNECTIVITY_PREFER_UDP; } else if (connectivity_type == "IPV6_ONLY") { - ret = IOTCON_CONNECTIVITY_IP|IOTCON_CONNECTIVITY_IPV6_ONLY|IOTCON_CONNECTIVITY_PREFER_UDP; + ret = IOTCON_CONNECTIVITY_IP | IOTCON_CONNECTIVITY_IPV6_ONLY | IOTCON_CONNECTIVITY_PREFER_UDP; } else { ret = IOTCON_CONNECTIVITY_ALL; } - LoggerD("ToConnectivityType2: %s ,%d", connectivity_type.c_str(), ret); - return ret; + LoggerD("ToConnectivityType2: %s ,%d", connectivity_type.c_str(), ret); + return ret; } iotcon_observe_policy_e IotconUtils::ToObservePolicy(const std::string& e) { @@ -2112,5 +2171,5 @@ iotcon_response_result_e IotconUtils::ToResponseResult(const std::string& e) { #undef X #undef XD -} // namespace iotcon -} // namespace extension +} // namespace iotcon +} // namespace extension diff --git a/src/iotcon/iotcon_utils.h b/src/iotcon/iotcon_utils.h index 9252e9a..aa37b5d 100644 --- a/src/iotcon/iotcon_utils.h +++ b/src/iotcon/iotcon_utils.h @@ -17,10 +17,10 @@ #ifndef WEBAPI_PLUGINS_IOTCON_IOTCON_UTILS_H__ #define WEBAPI_PLUGINS_IOTCON_IOTCON_UTILS_H__ +#include #include #include #include -#include #include #include #include @@ -33,8 +33,8 @@ namespace extension { namespace iotcon { -#define CHECK_EXIST(args, name) \ - if (args.end() == args.find(name)) { \ +#define CHECK_EXIST(args, name) \ + if (args.end() == args.find(name)) { \ return common::TypeMismatchError(std::string(name) + " is required argument"); \ } @@ -90,8 +90,8 @@ struct ResourceInfo { std::set children; std::set parents; - ResourceInfo() : - id(0), handle(nullptr) {} + ResourceInfo() : id(0), handle(nullptr) { + } ~ResourceInfo() { iotcon_resource_destroy(handle); } @@ -109,27 +109,35 @@ struct RemoteResourceInfo { uint8_t properties; // to check if observable iotcon_options_h options; iotcon_representation_h representation; - RemoteResourceInfo() : - resource(nullptr), uri_path(nullptr), - connectivity_type(IOTCON_CONNECTIVITY_ALL), host_address(nullptr), - device_id(nullptr), device_name(nullptr), types(nullptr), ifaces(0), - properties(0), options(nullptr), representation(nullptr) {} + RemoteResourceInfo() + : resource(nullptr), + uri_path(nullptr), + connectivity_type(IOTCON_CONNECTIVITY_ALL), + host_address(nullptr), + device_id(nullptr), + device_name(nullptr), + types(nullptr), + ifaces(0), + properties(0), + options(nullptr), + representation(nullptr) { + } ~RemoteResourceInfo() { - //according to native description, must not release any handles + // according to native description, must not release any handles } }; struct FoundRemoteInfo { long long id; iotcon_remote_resource_h handle; - short ref_count; // counter for registered listeners for this handle - //TODO add listeners for each type + short ref_count; // counter for registered listeners for this handle + // TODO add listeners for each type common::PostCallback state_listener; common::PostCallback observe_listener; common::PostCallback cache_change_listener; - FoundRemoteInfo() : - id(0), handle(nullptr), ref_count(1) {} //initialize with 1 (struct is created, so it - //mean that some listener would be created) + FoundRemoteInfo() : id(0), handle(nullptr), ref_count(1) { + } // initialize with 1 (struct is created, so it + // mean that some listener would be created) ~FoundRemoteInfo() { iotcon_remote_resource_destroy(handle); } @@ -146,66 +154,57 @@ class IotconUtils { static const picojson::value& GetArg(const picojson::object& args, const std::string& name); static int GetProperties(const picojson::object& args); static void PropertiesToJson(int properties, picojson::object* res); - static common::TizenResult ArrayToInterfaces(const picojson::array& interfaces, iotcon_resource_interfaces_h* res); - static common::TizenResult InterfacesToArray(iotcon_resource_interfaces_h interfaces, picojson::array* arr); - static common::TizenResult ArrayToTypes(const picojson::array& types, iotcon_resource_types_h* res); - static common::TizenResult ExtractFromResource(const ResourceInfoPtr& pointer, - char** uri_path, + static common::TizenResult ArrayToInterfaces(const picojson::array& interfaces, + iotcon_resource_interfaces_h* res); + static common::TizenResult InterfacesToArray(iotcon_resource_interfaces_h interfaces, + picojson::array* arr); + static common::TizenResult ArrayToTypes(const picojson::array& types, + iotcon_resource_types_h* res); + static common::TizenResult ExtractFromResource(const ResourceInfoPtr& pointer, char** uri_path, iotcon_resource_types_h* res_types, iotcon_resource_interfaces_h* ifaces, uint8_t* properties); - static common::TizenResult ResourceToJson(ResourceInfoPtr pointer, - picojson::object* res); + static common::TizenResult ResourceToJson(ResourceInfoPtr pointer, picojson::object* res); static common::TizenResult ExtractFromRemoteResource(RemoteResourceInfo* resource); static common::TizenResult RemoteResourceToJson(iotcon_remote_resource_h handle, picojson::object* res); static common::TizenResult RemoteResourceFromJson(const picojson::object& source, FoundRemoteInfoPtr* ptr); - static common::TizenResult RequestToJson(iotcon_request_h request, - picojson::object* out); + static common::TizenResult RequestToJson(iotcon_request_h request, picojson::object* out); static common::TizenResult RepresentationToJson(iotcon_representation_h representation, picojson::object* out); static common::TizenResult AttributesToJson(iotcon_attributes_h attributes, - picojson::object* out); - static common::TizenResult StateListToJson(iotcon_list_h list, - picojson::array* out); - static common::TizenResult OptionsToJson(iotcon_options_h options, - picojson::array* out); - static common::TizenResult QueryToJson(iotcon_query_h query, - picojson::object* out); + picojson::object* out); + static common::TizenResult StateListToJson(iotcon_list_h list, picojson::array* out); + static common::TizenResult OptionsToJson(iotcon_options_h options, picojson::array* out); + static common::TizenResult QueryToJson(iotcon_query_h query, picojson::object* out); static common::TizenResult QueryFromJson(const picojson::object& source, iotcon_query_h* res); - static common::TizenResult ResponseToJson(iotcon_response_h handle, - picojson::object* res); + static common::TizenResult ResponseToJson(iotcon_response_h handle, picojson::object* res); static common::TizenResult PresenceResponseToJson(iotcon_presence_response_h presence, - picojson::object* out); - static common::TizenResult ExtractFromPresenceEvent(const PresenceEventPtr& pointer, - char** host, - iotcon_connectivity_type_e* con_type, - char** resource_type); + picojson::object* out); + static common::TizenResult ExtractFromPresenceEvent(const PresenceEventPtr& pointer, char** host, + iotcon_connectivity_type_e* con_type, + char** resource_type); static common::TizenResult PlatformInfoToJson(iotcon_platform_info_h platform, picojson::object* out); static common::TizenResult PlatformInfoGetProperty(iotcon_platform_info_h platform, iotcon_platform_info_e property, const std::string& name, picojson::object* out); - static common::TizenResult DeviceInfoToJson(iotcon_device_info_h device, - picojson::object* out); + static common::TizenResult DeviceInfoToJson(iotcon_device_info_h device, picojson::object* out); static common::TizenResult DeviceInfoGetProperty(iotcon_device_info_h platform, - iotcon_device_info_e property, - const std::string& name, - picojson::object* out); + iotcon_device_info_e property, + const std::string& name, picojson::object* out); static common::TizenResult RepresentationFromResource(const ResourceInfoPtr& resource, const picojson::value& states, iotcon_representation_h* representation); static common::TizenResult AttributesFromJson(const picojson::object& state, - iotcon_attributes_h* out); - static common::TizenResult StateListFromJson(const picojson::array& list, - iotcon_list_h* out); - static common::TizenResult OptionsFromJson(const picojson::array& options, - iotcon_options_h* out); + iotcon_attributes_h* out); + static common::TizenResult StateListFromJson(const picojson::array& list, iotcon_list_h* out); + static common::TizenResult OptionsFromJson(const picojson::array& options, iotcon_options_h* out); static common::TizenResult RepresentationFromJson(const picojson::object& representation, iotcon_representation_h* out); @@ -224,7 +223,7 @@ class IotconUtils { static iotcon_response_result_e ToResponseResult(const std::string& e); }; -} // namespace iotcon -} // namespace extension +} // namespace iotcon +} // namespace extension -#endif // WEBAPI_PLUGINS_IOTCON_IOTCON_UTILS_H__ +#endif // WEBAPI_PLUGINS_IOTCON_IOTCON_UTILS_H__ diff --git a/src/keymanager/keymanager_extension.cc b/src/keymanager/keymanager_extension.cc old mode 100755 new mode 100644 index 972c55e..7d0f37f --- a/src/keymanager/keymanager_extension.cc +++ b/src/keymanager/keymanager_extension.cc @@ -34,16 +34,12 @@ common::Extension* CreateExtension() { KeyManagerExtension::KeyManagerExtension() { SetExtensionName("tizen.keymanager"); SetJavaScriptAPI(kSource_keymanager_api); - const char* entry_points[] = { - kKey, - kData, - kCertificate, - NULL - }; + const char* entry_points[] = {kKey, kData, kCertificate, NULL}; SetExtraJSEntryPoints(entry_points); } -KeyManagerExtension::~KeyManagerExtension() {} +KeyManagerExtension::~KeyManagerExtension() { +} common::Instance* KeyManagerExtension::CreateInstance() { return new extension::keymanager::KeyManagerInstance; diff --git a/src/keymanager/keymanager_extension.h b/src/keymanager/keymanager_extension.h old mode 100755 new mode 100644 index 16abbf2..86a8169 --- a/src/keymanager/keymanager_extension.h +++ b/src/keymanager/keymanager_extension.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef KEYMANAGER_KEYMANAGER_EXTENSION_H_ #define KEYMANAGER_KEYMANAGER_EXTENSION_H_ diff --git a/src/keymanager/keymanager_instance.cc b/src/keymanager/keymanager_instance.cc index cc3d3f7..2f0def1 100644 --- a/src/keymanager/keymanager_instance.cc +++ b/src/keymanager/keymanager_instance.cc @@ -20,13 +20,13 @@ #include #include +#include "common/current_application.h" #include "common/logger.h" #include "common/optional.h" #include "common/platform_result.h" #include "common/scope_exit.h" #include "common/task-queue.h" #include "common/tools.h" -#include "common/current_application.h" namespace extension { namespace keymanager { @@ -60,8 +60,8 @@ void GetGenericAliasList(AliasListFunction func, picojson::object* out) { ckmc_alias_list_s* head = alias_list; while (head) { - //aliases.push_back(picojson::value(head->alias ? head->alias : "")); - if(head->alias) { + // aliases.push_back(picojson::value(head->alias ? head->alias : "")); + if (head->alias) { char* saveptr = nullptr; char* tokenized = strtok_r(head->alias, kSpace.c_str(), &saveptr); obj["packageId"] = picojson::value(tokenized); @@ -89,23 +89,21 @@ KeyManagerInstance::KeyManagerInstance() { using std::placeholders::_2; RegisterSyncHandler("KeyManager_getDataAliasList", - std::bind(&KeyManagerInstance::GetDataAliasList, this, _1, _2)); + std::bind(&KeyManagerInstance::GetDataAliasList, this, _1, _2)); RegisterSyncHandler("KeyManager_saveData", - std::bind(&KeyManagerInstance::SaveData, this, _1, _2)); + std::bind(&KeyManagerInstance::SaveData, this, _1, _2)); - RegisterSyncHandler("KeyManager_getData", - std::bind(&KeyManagerInstance::GetData, this, _1, _2)); + RegisterSyncHandler("KeyManager_getData", std::bind(&KeyManagerInstance::GetData, this, _1, _2)); RegisterSyncHandler("KeyManager_removeAlias", - std::bind(&KeyManagerInstance::RemoveAlias, this, _1, _2)); + std::bind(&KeyManagerInstance::RemoveAlias, this, _1, _2)); RegisterSyncHandler("KeyManager_setPermissions", - std::bind(&KeyManagerInstance::SetPermission, this, _1, _2)); + std::bind(&KeyManagerInstance::SetPermission, this, _1, _2)); } -void KeyManagerInstance::GetDataAliasList(const picojson::value& args, - picojson::object& out) { +void KeyManagerInstance::GetDataAliasList(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); GetGenericAliasList(ckmc_get_data_alias_list, &out); @@ -113,29 +111,24 @@ void KeyManagerInstance::GetDataAliasList(const picojson::value& args, PlatformResult KeyManagerInstance::GetError(int ret) { char* error = get_error_message(ret); - if(CKMC_ERROR_NONE == ret) { + if (CKMC_ERROR_NONE == ret) { return PlatformResult(ErrorCode::NO_ERROR); - } - else if(CKMC_ERROR_INVALID_PARAMETER == ret) { + } else if (CKMC_ERROR_INVALID_PARAMETER == ret) { LoggerD("%s", error); return PlatformResult(ErrorCode::INVALID_VALUES_ERR, error); - } - else if(CKMC_ERROR_DB_ALIAS_UNKNOWN == ret) { - LoggerD("%s",error); + } else if (CKMC_ERROR_DB_ALIAS_UNKNOWN == ret) { + LoggerD("%s", error); return PlatformResult(ErrorCode::NOT_FOUND_ERR, error); - } - else if(CKMC_ERROR_AUTHENTICATION_FAILED == ret) { - LoggerD("%s",error); + } else if (CKMC_ERROR_AUTHENTICATION_FAILED == ret) { + LoggerD("%s", error); return PlatformResult(ErrorCode::VERIFICATION_ERR, error); - } - else { + } else { LoggerD("%s", error); return PlatformResult(ErrorCode::UNKNOWN_ERR, error); } } -void KeyManagerInstance::SaveData(const picojson::value& args, - picojson::object& out) { +void KeyManagerInstance::SaveData(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); std::string data_raw = args.get("rawData").get(); @@ -152,12 +145,11 @@ void KeyManagerInstance::SaveData(const picojson::value& args, } auto save_data = [data_raw, password, alias](const std::shared_ptr& result) { - unsigned char* data = new unsigned char[data_raw.size()]; std::copy(data_raw.begin(), data_raw.end(), data); - ckmc_raw_buffer_s raw_data { data, data_raw.size() }; - ckmc_policy_s policy { const_cast(password.c_str()), true }; + ckmc_raw_buffer_s raw_data{data, data_raw.size()}; + ckmc_policy_s policy{const_cast(password.c_str()), true}; int ret = ckmc_save_data(alias.c_str(), raw_data, policy); @@ -180,16 +172,12 @@ void KeyManagerInstance::SaveData(const picojson::value& args, auto queue_data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - save_data, - save_data_result, - queue_data); + TaskQueue::GetInstance().Queue(save_data, save_data_result, queue_data); ReportSuccess(out); } -void KeyManagerInstance::GetData(const picojson::value& args, - picojson::object& out) { +void KeyManagerInstance::GetData(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const auto& data_alias = args.get("name").get(); @@ -209,7 +197,7 @@ void KeyManagerInstance::GetData(const picojson::value& args, if (CKMC_ERROR_NONE == ret && data) { picojson::object result; - result["rawData"] = picojson::value(std::string (data->data, data->data + data->size)); + result["rawData"] = picojson::value(std::string(data->data, data->data + data->size)); ckmc_buffer_free(data); ReportSuccess(picojson::value{result}, out); @@ -226,8 +214,7 @@ KeyManagerInstance::~KeyManagerInstance() { LoggerD("Enter"); } -void KeyManagerInstance::RemoveAlias(const picojson::value& args, - picojson::object& out) { +void KeyManagerInstance::RemoveAlias(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const std::string& alias = args.get("aliasName").get(); @@ -242,8 +229,7 @@ void KeyManagerInstance::RemoveAlias(const picojson::value& args, } } -void KeyManagerInstance::SetPermission(const picojson::value& args, - picojson::object& out) { +void KeyManagerInstance::SetPermission(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const std::string& data_name = args.get("aliasName").get(); @@ -252,20 +238,18 @@ void KeyManagerInstance::SetPermission(const picojson::value& args, const std::string& access = args.get("permissionType").get(); int permissions = CKMC_PERMISSION_NONE; - if( "NONE" == access) { + if ("NONE" == access) { permissions = CKMC_PERMISSION_NONE; - } - else if ("READ" == access) { + } else if ("READ" == access) { permissions = CKMC_PERMISSION_READ; - } - else if ("REMOVE" == access) { + } else if ("REMOVE" == access) { permissions = CKMC_PERMISSION_REMOVE; - } - else if("READ_REMOVE" == access) { + } else if ("READ_REMOVE" == access) { permissions = CKMC_PERMISSION_READ | CKMC_PERMISSION_REMOVE; } - auto set_permissions = [data_name, id, permissions](const std::shared_ptr& response) -> void { + auto set_permissions = [data_name, id, + permissions](const std::shared_ptr& response) -> void { int ret = ckmc_set_permission(data_name.c_str(), id.c_str(), permissions); if (CKMC_ERROR_NONE != ret) { @@ -276,7 +260,8 @@ void KeyManagerInstance::SetPermission(const picojson::value& args, } }; - auto set_permissions_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto set_permissions_response = + [this, callback_id](const std::shared_ptr& response) -> void { picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); @@ -284,11 +269,8 @@ void KeyManagerInstance::SetPermission(const picojson::value& args, auto data = std::shared_ptr(new picojson::value(picojson::object())); - TaskQueue::GetInstance().Queue( - set_permissions, - set_permissions_response, - data); + TaskQueue::GetInstance().Queue(set_permissions, set_permissions_response, data); } -} // namespace keymanager -} // namespace extension +} // namespace keymanager +} // namespace extension diff --git a/src/keymanager/keymanager_instance.h b/src/keymanager/keymanager_instance.h old mode 100755 new mode 100644 index 1d433bf..7d32934 --- a/src/keymanager/keymanager_instance.h +++ b/src/keymanager/keymanager_instance.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef KEYMANAGER_KEYMANAGER_INSTANCE_H_ #define KEYMANAGER_KEYMANAGER_INSTANCE_H_ @@ -28,7 +28,6 @@ class KeyManagerInstance : public common::ParsedInstance { virtual ~KeyManagerInstance(); private: - void GetDataAliasList(picojson::value const& args, picojson::object& out); void SaveData(const picojson::value& args, picojson::object& out); @@ -40,7 +39,7 @@ class KeyManagerInstance : public common::ParsedInstance { static common::PlatformResult GetError(int ret); }; -} // namespace keymanager -} // namespace extension +} // namespace keymanager +} // namespace extension -#endif // KEYMANAGER_KEYMANAGER_INSTANCE_H_ +#endif // KEYMANAGER_KEYMANAGER_INSTANCE_H_ diff --git a/src/mediacontroller/mediacontroller_client.cc b/src/mediacontroller/mediacontroller_client.cc index 8cb9cdd..59df5aa 100644 --- a/src/mediacontroller/mediacontroller_client.cc +++ b/src/mediacontroller/mediacontroller_client.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "mediacontroller/mediacontroller_client.h" #include @@ -49,24 +49,23 @@ PlatformResult MediaControllerClient::Init() { LoggerD("Enter"); int ret = mc_client_create(&handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to create media controller client", - ("mc_client_create() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to create media controller client", + ("mc_client_create() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MediaControllerClient::FindServers(picojson::array* servers) { - LoggerD("Enter"); int ret; ret = mc_client_foreach_server(handle_, FindServersCallback, servers); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to fetch active servers, error", - ("mc_client_foreach_server() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to fetch active servers, error", + ("mc_client_foreach_server() error: %d, message: %s", ret, get_error_message(ret))); } // check latest server state - if exist @@ -96,9 +95,7 @@ PlatformResult MediaControllerClient::FindServers(picojson::array* servers) { return PlatformResult(ErrorCode::NO_ERROR); } -bool MediaControllerClient::FindServersCallback(const char* server_name, - void* user_data) { - +bool MediaControllerClient::FindServersCallback(const char* server_name, void* user_data) { LoggerD("Enter"); picojson::array* servers = static_cast(user_data); @@ -113,9 +110,7 @@ bool MediaControllerClient::FindServersCallback(const char* server_name, return true; } -PlatformResult MediaControllerClient::GetLatestServerInfo( - picojson::value* server_info) { - +PlatformResult MediaControllerClient::GetLatestServerInfo(picojson::value* server_info) { LoggerD("Enter"); int ret; @@ -126,9 +121,9 @@ PlatformResult MediaControllerClient::GetLatestServerInfo( mc_server_state_e state; ret = mc_client_get_latest_server_info(handle_, &name, &state); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting latest server info", - ("mc_client_get_latest_server_info() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error getting latest server info", + ("mc_client_get_latest_server_info() error: %d, message: %s", ret, get_error_message(ret))); } if (!name) { @@ -137,8 +132,8 @@ PlatformResult MediaControllerClient::GetLatestServerInfo( } std::string state_str; - PlatformResult result = Types::PlatformEnumToString( - Types::kMediaControllerServerState, static_cast(state), &state_str); + PlatformResult result = Types::PlatformEnumToString(Types::kMediaControllerServerState, + static_cast(state), &state_str); if (!result) { LOGGER(ERROR) << "PlatformEnumToString failed, error: " << result.message(); return result; @@ -152,21 +147,17 @@ PlatformResult MediaControllerClient::GetLatestServerInfo( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerClient::GetPlaybackInfo( - const std::string& server_name, - picojson::object* playback_info) { - +PlatformResult MediaControllerClient::GetPlaybackInfo(const std::string& server_name, + picojson::object* playback_info) { LoggerD("Enter"); int ret; mc_playback_h playback_h; - ret = mc_client_get_server_playback_info(handle_, - server_name.c_str(), - &playback_h); + ret = mc_client_get_server_playback_info(handle_, server_name.c_str(), &playback_h); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting playback info", - ("mc_client_get_server_playback_info() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error getting playback info", + ("mc_client_get_server_playback_info() error: %d, message: %s", ret, + get_error_message(ret))); } SCOPE_EXIT { @@ -191,22 +182,20 @@ PlatformResult MediaControllerClient::GetPlaybackInfo( // shuffle mode mc_shuffle_mode_e shuffle; - ret = mc_client_get_server_shuffle_mode( - handle_, server_name.c_str(), &shuffle); + ret = mc_client_get_server_shuffle_mode(handle_, server_name.c_str(), &shuffle); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting shuffle mode", - ("mc_client_get_server_shuffle_mode() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error getting shuffle mode", + ("mc_client_get_server_shuffle_mode() error: %d, message: %s", ret, + get_error_message(ret))); } // repeat mode mc_repeat_mode_e repeat; - ret = mc_client_get_server_repeat_mode( - handle_, server_name.c_str(), &repeat); + ret = mc_client_get_server_repeat_mode(handle_, server_name.c_str(), &repeat); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting repeat mode", - ("mc_client_get_server_repeat_mode() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error getting repeat mode", + ("mc_client_get_server_repeat_mode() error: %d, message: %s", ret, get_error_message(ret))); } // metadata @@ -226,20 +215,17 @@ PlatformResult MediaControllerClient::GetPlaybackInfo( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerClient::GetMetadata( - const std::string& server_name, - picojson::object* metadata) { - +PlatformResult MediaControllerClient::GetMetadata(const std::string& server_name, + picojson::object* metadata) { LoggerD("Enter"); int ret; mc_metadata_h metadata_h; - ret = mc_client_get_server_metadata(handle_, server_name.c_str(), - &metadata_h); + ret = mc_client_get_server_metadata(handle_, server_name.c_str(), &metadata_h); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting server metadata", - ("mc_client_get_server_metadata() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error getting server metadata", + ("mc_client_get_server_metadata() error: %d, message: %s", ret, get_error_message(ret))); } SCOPE_EXIT { @@ -254,45 +240,37 @@ PlatformResult MediaControllerClient::GetMetadata( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerClient::SetServerStatusChangeListener( - JsonCallback callback) { - +PlatformResult MediaControllerClient::SetServerStatusChangeListener(JsonCallback callback) { LoggerD("Enter"); if (callback && server_status_listener_) { - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, - "Listener already registered"); + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); } server_status_listener_ = callback; int ret; - if (callback) { // set platform callbacks - + if (callback) { // set platform callbacks ret = mc_client_set_server_update_cb(handle_, OnServerStatusUpdate, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to set server status listener", - ("mc_client_set_server_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to set server status listener", + ("mc_client_set_server_update_cb() error: %d, message: %s", ret, get_error_message(ret))); } - } else { // unset platform callbacks - + } else { // unset platform callbacks ret = mc_client_unset_server_update_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to unset server status listener", - ("mc_client_unset_server_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to unset server status listener", + ("mc_client_unset_server_update_cb() error: %d, message: %s", ret, + get_error_message(ret))); } - } return PlatformResult(ErrorCode::NO_ERROR); } -void MediaControllerClient::OnServerStatusUpdate(const char* server_name, - mc_server_state_e state, +void MediaControllerClient::OnServerStatusUpdate(const char* server_name, mc_server_state_e state, void* user_data) { - LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -303,8 +281,8 @@ void MediaControllerClient::OnServerStatusUpdate(const char* server_name, // server state std::string state_str; - PlatformResult result = Types::PlatformEnumToString( - Types::kMediaControllerServerState, static_cast(state), &state_str); + PlatformResult result = Types::PlatformEnumToString(Types::kMediaControllerServerState, + static_cast(state), &state_str); if (!result) { LOGGER(ERROR) << "PlatformEnumToString failed, error: " << result.message(); return; @@ -319,87 +297,81 @@ void MediaControllerClient::OnServerStatusUpdate(const char* server_name, client->server_status_listener_(&data); } -PlatformResult MediaControllerClient::SetPlaybackInfoListener( - JsonCallback callback) { - +PlatformResult MediaControllerClient::SetPlaybackInfoListener(JsonCallback callback) { LoggerD("Enter"); if (callback && playback_info_listener_) { - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, - "Listener already registered"); + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); } playback_info_listener_ = callback; int ret; - if (callback) { // set platform callbacks - + if (callback) { // set platform callbacks ret = mc_client_set_playback_update_cb(handle_, OnPlaybackUpdate, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to register playback listener", - ("mc_client_set_playback_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to register playback listener", + ("mc_client_set_playback_update_cb() error: %d, message: %s", ret, + get_error_message(ret))); } ret = mc_client_set_shuffle_mode_update_cb(handle_, OnShuffleModeUpdate, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to register shuffle mode listener", - ("mc_client_set_shuffle_mode_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to register shuffle mode listener", + ("mc_client_set_shuffle_mode_update_cb() error: %d, message: %s", + ret, get_error_message(ret))); } ret = mc_client_set_repeat_mode_update_cb(handle_, OnRepeatModeUpdate, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to register repeat mode listener", - ("mc_client_set_repeat_mode_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to register repeat mode listener", + ("mc_client_set_repeat_mode_update_cb() error: %d, message: %s", + ret, get_error_message(ret))); } ret = mc_client_set_metadata_update_cb(handle_, OnMetadataUpdate, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to register metadata listener", - ("mc_client_set_metadata_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to register metadata listener", + ("mc_client_set_metadata_update_cb() error: %d, message: %s", ret, + get_error_message(ret))); } - } else { // unset platform callbacks - + } else { // unset platform callbacks ret = mc_client_unset_playback_update_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to unregister playback listener", - ("mc_client_unset_playback_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to unregister playback listener", + ("mc_client_unset_playback_update_cb() error: %d, message: %s", ret, + get_error_message(ret))); } ret = mc_client_unset_shuffle_mode_update_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to unregister shuffle mode listener", - ("mc_client_unset_shuffle_mode_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + ("mc_client_unset_shuffle_mode_update_cb() error: %d, message: %s", + ret, get_error_message(ret))); } ret = mc_client_unset_repeat_mode_update_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to unregister repeat mode listener", - ("mc_client_unset_repeat_mode_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to unregister repeat mode listener", + ("mc_client_unset_repeat_mode_update_cb() error: %d, message: %s", + ret, get_error_message(ret))); } ret = mc_client_unset_metadata_update_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { LOGGER(ERROR) << "Unable to unregister metadata listener, error: " << ret; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to unregister metadata listener", - ("mc_client_unset_metadata_update_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to unregister metadata listener", + ("mc_client_unset_metadata_update_cb() error: %d, message: %s", ret, + get_error_message(ret))); } } return PlatformResult(ErrorCode::NO_ERROR); }; -void MediaControllerClient::OnPlaybackUpdate(const char *server_name, - mc_playback_h playback, - void *user_data) { - +void MediaControllerClient::OnPlaybackUpdate(const char* server_name, mc_playback_h playback, + void* user_data) { LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -435,10 +407,8 @@ void MediaControllerClient::OnPlaybackUpdate(const char *server_name, client->playback_info_listener_(&data); } -void MediaControllerClient::OnShuffleModeUpdate(const char *server_name, - mc_shuffle_mode_e mode, - void *user_data) { - +void MediaControllerClient::OnShuffleModeUpdate(const char* server_name, mc_shuffle_mode_e mode, + void* user_data) { LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -457,10 +427,8 @@ void MediaControllerClient::OnShuffleModeUpdate(const char *server_name, client->playback_info_listener_(&data); } -void MediaControllerClient::OnRepeatModeUpdate(const char *server_name, - mc_repeat_mode_e mode, - void *user_data) { - +void MediaControllerClient::OnRepeatModeUpdate(const char* server_name, mc_repeat_mode_e mode, + void* user_data) { LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -479,10 +447,8 @@ void MediaControllerClient::OnRepeatModeUpdate(const char *server_name, client->playback_info_listener_(&data); } -void MediaControllerClient::OnMetadataUpdate(const char* server_name, - mc_metadata_h metadata_h, +void MediaControllerClient::OnMetadataUpdate(const char* server_name, mc_metadata_h metadata_h, void* user_data) { - LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -495,8 +461,7 @@ void MediaControllerClient::OnMetadataUpdate(const char* server_name, picojson::object& data_o = data.get(); picojson::value metadata = picojson::value(picojson::object()); - PlatformResult result = Types::ConvertMetadata( - metadata_h, &metadata.get()); + PlatformResult result = Types::ConvertMetadata(metadata_h, &metadata.get()); if (!result) { LOGGER(ERROR) << "ConvertMetadata failed, error: " << result.message(); return; @@ -509,13 +474,11 @@ void MediaControllerClient::OnMetadataUpdate(const char* server_name, client->playback_info_listener_(&data); } -PlatformResult MediaControllerClient::SendCommand( - const std::string& server_name, - const std::string& command, - const picojson::value& data, - const std::string& reply_id, - const JsonCallback& reply_cb) { - +PlatformResult MediaControllerClient::SendCommand(const std::string& server_name, + const std::string& command, + const picojson::value& data, + const std::string& reply_id, + const JsonCallback& reply_cb) { LoggerD("Enter"); bundle* bundle = bundle_create(); SCOPE_EXIT { @@ -525,28 +488,24 @@ PlatformResult MediaControllerClient::SendCommand( int ret; ret = bundle_add(bundle, "replyId", reply_id.c_str()); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to add replyId to bundle", - ("bundle_add(replyId) error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to add replyId to bundle", + ("bundle_add(replyId) error: %d, message: %s", ret, get_error_message(ret))); } ret = bundle_add(bundle, "data", data.serialize().c_str()); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to add data to bundle", - ("bundle_add(data) error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to add data to bundle", + ("bundle_add(data) error: %d, message: %s", ret, get_error_message(ret))); } - ret = mc_client_send_custom_command(handle_, - server_name.c_str(), - command.c_str(), - bundle, - OnCommandReply, - this); + ret = mc_client_send_custom_command(handle_, server_name.c_str(), command.c_str(), bundle, + OnCommandReply, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error sending custom command", - ("mc_client_send_custom_command() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error sending custom command", + ("mc_client_send_custom_command() error: %d, message: %s", ret, get_error_message(ret))); } command_reply_callback_ = reply_cb; @@ -554,11 +513,8 @@ PlatformResult MediaControllerClient::SendCommand( return PlatformResult(ErrorCode::NO_ERROR); } -void MediaControllerClient::OnCommandReply(const char* server_name, - int result_code, - bundle* bundle, +void MediaControllerClient::OnCommandReply(const char* server_name, int result_code, bundle* bundle, void* user_data) { - LoggerD("Enter"); MediaControllerClient* client = static_cast(user_data); @@ -600,56 +556,46 @@ void MediaControllerClient::OnCommandReply(const char* server_name, client->command_reply_callback_(&reply); } -PlatformResult MediaControllerClient::SendPlaybackState( - const std::string& server_name, - const std::string& state) { - +PlatformResult MediaControllerClient::SendPlaybackState(const std::string& server_name, + const std::string& state) { LoggerD("Enter"); int state_e; - PlatformResult result = Types::StringToPlatformEnum( - Types::kMediaControllerPlaybackState, state, &state_e); + PlatformResult result = + Types::StringToPlatformEnum(Types::kMediaControllerPlaybackState, state, &state_e); if (!result) { return result; } int ret; - ret = mc_client_send_playback_state_command( - handle_, server_name.c_str(), static_cast(state_e)); + ret = mc_client_send_playback_state_command(handle_, server_name.c_str(), + static_cast(state_e)); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error sending playback state", - ("mc_client_send_playback_state_command() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error sending playback state", + ("mc_client_send_playback_state_command() error: %d, message: %s", + ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerClient::SendPlaybackPosition( - const std::string& server_name, - double position) { - +PlatformResult MediaControllerClient::SendPlaybackPosition(const std::string& server_name, + double position) { // TODO(r.galka) implement when dedicated method will be available in CAPI return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Not supported"); } -PlatformResult MediaControllerClient::SendShuffleMode( - const std::string& server_name, - bool mode) { - +PlatformResult MediaControllerClient::SendShuffleMode(const std::string& server_name, bool mode) { // TODO(r.galka) implement when dedicated method will be available in CAPI return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Not supported"); } -PlatformResult MediaControllerClient::SendRepeatMode( - const std::string& server_name, - bool mode) { - +PlatformResult MediaControllerClient::SendRepeatMode(const std::string& server_name, bool mode) { // TODO(r.galka) implement when dedicated method will be available in CAPI return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Not supported"); } -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension diff --git a/src/mediacontroller/mediacontroller_client.h b/src/mediacontroller/mediacontroller_client.h old mode 100755 new mode 100644 index 9d7b193..f359dc5 --- a/src/mediacontroller/mediacontroller_client.h +++ b/src/mediacontroller/mediacontroller_client.h @@ -37,22 +37,16 @@ class MediaControllerClient { common::PlatformResult GetLatestServerInfo(picojson::value* server_info); common::PlatformResult GetPlaybackInfo(const std::string& server_name, picojson::object* playback_info); - common::PlatformResult GetMetadata(const std::string& server_name, - picojson::object* metadata); + common::PlatformResult GetMetadata(const std::string& server_name, picojson::object* metadata); common::PlatformResult SendPlaybackState(const std::string& server_name, const std::string& state); - common::PlatformResult SendPlaybackPosition(const std::string& server_name, - double position); - common::PlatformResult SendShuffleMode(const std::string& server_name, - bool mode); - common::PlatformResult SendRepeatMode(const std::string& server_name, - bool mode); - - common::PlatformResult SendCommand(const std::string& server_name, - const std::string& command, - const picojson::value& data, - const std::string& reply_id, + common::PlatformResult SendPlaybackPosition(const std::string& server_name, double position); + common::PlatformResult SendShuffleMode(const std::string& server_name, bool mode); + common::PlatformResult SendRepeatMode(const std::string& server_name, bool mode); + + common::PlatformResult SendCommand(const std::string& server_name, const std::string& command, + const picojson::value& data, const std::string& reply_id, const JsonCallback& reply_cb); common::PlatformResult SetServerStatusChangeListener(JsonCallback callback); @@ -67,28 +61,17 @@ class MediaControllerClient { static bool FindServersCallback(const char* server_name, void* user_data); - static void OnServerStatusUpdate(const char *server_name, - mc_server_state_e state, - void *user_data); - static void OnCommandReply(const char* server_name, - int result_code, - bundle* bundle, + static void OnServerStatusUpdate(const char* server_name, mc_server_state_e state, + void* user_data); + static void OnCommandReply(const char* server_name, int result_code, bundle* bundle, void* user_data); - static void OnPlaybackUpdate(const char *server_name, - mc_playback_h playback, - void *user_data); - static void OnShuffleModeUpdate(const char *server_name, - mc_shuffle_mode_e mode, - void *user_data); - static void OnRepeatModeUpdate(const char *server_name, - mc_repeat_mode_e mode, - void *user_data); - static void OnMetadataUpdate(const char* server_name, - mc_metadata_h metadata_h, - void* user_data); + static void OnPlaybackUpdate(const char* server_name, mc_playback_h playback, void* user_data); + static void OnShuffleModeUpdate(const char* server_name, mc_shuffle_mode_e mode, void* user_data); + static void OnRepeatModeUpdate(const char* server_name, mc_repeat_mode_e mode, void* user_data); + static void OnMetadataUpdate(const char* server_name, mc_metadata_h metadata_h, void* user_data); }; -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension #endif // MEDIACONTROLLER_MEDIACONTROLLER_CLIENT_H_ diff --git a/src/mediacontroller/mediacontroller_extension.cc b/src/mediacontroller/mediacontroller_extension.cc old mode 100755 new mode 100644 index 4485e13..3c02144 --- a/src/mediacontroller/mediacontroller_extension.cc +++ b/src/mediacontroller/mediacontroller_extension.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "mediacontroller/mediacontroller_extension.h" #include "mediacontroller/mediacontroller_instance.h" @@ -30,7 +30,8 @@ MediaControllerExtension::MediaControllerExtension() { SetJavaScriptAPI(kSource_mediacontroller_api); } -MediaControllerExtension::~MediaControllerExtension() {} +MediaControllerExtension::~MediaControllerExtension() { +} common::Instance* MediaControllerExtension::CreateInstance() { return new extension::mediacontroller::MediaControllerInstance; diff --git a/src/mediacontroller/mediacontroller_extension.h b/src/mediacontroller/mediacontroller_extension.h old mode 100755 new mode 100644 index 94e0391..7442ccb --- a/src/mediacontroller/mediacontroller_extension.h +++ b/src/mediacontroller/mediacontroller_extension.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MEDIACONTROLLER_MEDIACONTROLLER_EXTENSION_H_ #define MEDIACONTROLLER_MEDIACONTROLLER_EXTENSION_H_ diff --git a/src/mediacontroller/mediacontroller_instance.cc b/src/mediacontroller/mediacontroller_instance.cc old mode 100755 new mode 100644 index 3c8ebcb..a714734 --- a/src/mediacontroller/mediacontroller_instance.cc +++ b/src/mediacontroller/mediacontroller_instance.cc @@ -29,8 +29,10 @@ namespace mediacontroller { namespace { -const std::string kPrivilegeMediaControllerClient = "http://tizen.org/privilege/mediacontroller.client"; -const std::string kPrivilegeMediaControllerServer = "http://tizen.org/privilege/mediacontroller.server"; +const std::string kPrivilegeMediaControllerClient = + "http://tizen.org/privilege/mediacontroller.client"; +const std::string kPrivilegeMediaControllerServer = + "http://tizen.org/privilege/mediacontroller.server"; } // namespace @@ -43,61 +45,52 @@ MediaControllerInstance::MediaControllerInstance() { using namespace std::placeholders; #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&MediaControllerInstance::x, this, _1, _2)); + RegisterSyncHandler(c, std::bind(&MediaControllerInstance::x, this, _1, _2)); #define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&MediaControllerInstance::x, this, _1, _2)); + RegisterSyncHandler(c, std::bind(&MediaControllerInstance::x, this, _1, _2)); // server - REGISTER_SYNC("MediaControllerManager_createServer", - MediaControllerManagerCreateServer); + REGISTER_SYNC("MediaControllerManager_createServer", MediaControllerManagerCreateServer); REGISTER_SYNC("MediaControllerServer_updatePlaybackState", - MediaControllerServerUpdatePlaybackState); + MediaControllerServerUpdatePlaybackState); REGISTER_SYNC("MediaControllerServer_updatePlaybackPosition", - MediaControllerServerUpdatePlaybackPosition); - REGISTER_SYNC("MediaControllerServer_updateRepeatMode", - MediaControllerServerUpdateRepeatMode); - REGISTER_SYNC("MediaControllerServer_updateShuffleMode", - MediaControllerServerUpdateShuffleMode); - REGISTER_SYNC("MediaControllerServer_updateMetadata", - MediaControllerServerUpdateMetadata); + MediaControllerServerUpdatePlaybackPosition); + REGISTER_SYNC("MediaControllerServer_updateRepeatMode", MediaControllerServerUpdateRepeatMode); + REGISTER_SYNC("MediaControllerServer_updateShuffleMode", MediaControllerServerUpdateShuffleMode); + REGISTER_SYNC("MediaControllerServer_updateMetadata", MediaControllerServerUpdateMetadata); REGISTER_SYNC("MediaControllerServer_addChangeRequestPlaybackInfoListener", - MediaControllerServerAddChangeRequestPlaybackInfoListener); + MediaControllerServerAddChangeRequestPlaybackInfoListener); REGISTER_SYNC("MediaControllerServer_removeChangeRequestPlaybackInfoListener", - MediaControllerServerRemoveChangeRequestPlaybackInfoListener); + MediaControllerServerRemoveChangeRequestPlaybackInfoListener); REGISTER_SYNC("MediaControllerServer_addCommandListener", - MediaControllerServerAddCommandListener); - REGISTER_SYNC("MediaControllerServer_replyCommand", - MediaControllerServerReplyCommand); + MediaControllerServerAddCommandListener); + REGISTER_SYNC("MediaControllerServer_replyCommand", MediaControllerServerReplyCommand); REGISTER_SYNC("MediaControllerServer_removeCommandListener", - MediaControllerServerRemoveCommandListener); + MediaControllerServerRemoveCommandListener); // client - REGISTER_SYNC("MediaControllerManager_getClient", - MediaControllerManagerGetClient); - REGISTER_ASYNC("MediaControllerClient_findServers", - MediaControllerClientFindServers); + REGISTER_SYNC("MediaControllerManager_getClient", MediaControllerManagerGetClient); + REGISTER_ASYNC("MediaControllerClient_findServers", MediaControllerClientFindServers); REGISTER_SYNC("MediaControllerClient_getLatestServerInfo", - MediaControllerClientGetLatestServerInfo); - REGISTER_SYNC("MediaControllerClient_getPlaybackInfo", - MediaControllerClientGetPlaybackInfo); + MediaControllerClientGetLatestServerInfo); + REGISTER_SYNC("MediaControllerClient_getPlaybackInfo", MediaControllerClientGetPlaybackInfo); REGISTER_SYNC("MediaControllerServerInfo_sendPlaybackState", - MediaControllerServerInfoSendPlaybackState); + MediaControllerServerInfoSendPlaybackState); REGISTER_ASYNC("MediaControllerServerInfo_sendPlaybackPosition", - MediaControllerServerInfoSendPlaybackPosition); + MediaControllerServerInfoSendPlaybackPosition); REGISTER_ASYNC("MediaControllerServerInfo_sendRepeatMode", - MediaControllerServerInfoSendRepeatMode); + MediaControllerServerInfoSendRepeatMode); REGISTER_ASYNC("MediaControllerServerInfo_sendShuffleMode", - MediaControllerServerInfoSendShuffleMode); - REGISTER_ASYNC("MediaControllerServerInfo_sendCommand", - MediaControllerServerInfoSendCommand); + MediaControllerServerInfoSendShuffleMode); + REGISTER_ASYNC("MediaControllerServerInfo_sendCommand", MediaControllerServerInfoSendCommand); REGISTER_SYNC("MediaControllerServerInfo_addServerStatusChangeListener", - MediaControllerServerInfoAddServerStatusChangeListener); + MediaControllerServerInfoAddServerStatusChangeListener); REGISTER_SYNC("MediaControllerServerInfo_removeServerStatusChangeListener", - MediaControllerServerInfoRemoveServerStatusChangeListener); + MediaControllerServerInfoRemoveServerStatusChangeListener); REGISTER_SYNC("MediaControllerServerInfo_addPlaybackInfoChangeListener", - MediaControllerServerInfoAddPlaybackInfoChangeListener); + MediaControllerServerInfoAddPlaybackInfoChangeListener); REGISTER_SYNC("MediaControllerServerInfo_removePlaybackInfoChangeListener", - MediaControllerServerInfoRemovePlaybackInfoChangeListener); + MediaControllerServerInfoRemovePlaybackInfoChangeListener); #undef REGISTER_SYNC #undef REGISTER_ASYNC @@ -107,17 +100,15 @@ MediaControllerInstance::~MediaControllerInstance() { LoggerD("Enter"); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) { \ - LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, \ - name" is required argument"), &out); \ - return; \ - } - +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, name " is required argument"), \ + &out); \ + return; \ + } -void MediaControllerInstance::MediaControllerManagerCreateServer( - const picojson::value& args, - picojson::object& out) { +void MediaControllerInstance::MediaControllerManagerCreateServer(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeMediaControllerServer, &out); @@ -137,15 +128,14 @@ void MediaControllerInstance::MediaControllerManagerCreateServer( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerUpdatePlaybackState( - const picojson::value& args, - picojson::object& out) { +void MediaControllerInstance::MediaControllerServerUpdatePlaybackState(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "state", out) if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -160,13 +150,11 @@ void MediaControllerInstance::MediaControllerServerUpdatePlaybackState( } void MediaControllerInstance::MediaControllerServerUpdatePlaybackPosition( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -182,14 +170,12 @@ void MediaControllerInstance::MediaControllerServerUpdatePlaybackPosition( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerUpdateShuffleMode( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerUpdateShuffleMode(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -206,15 +192,13 @@ void MediaControllerInstance::MediaControllerServerUpdateShuffleMode( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerUpdateRepeatMode( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerUpdateRepeatMode(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -231,21 +215,18 @@ void MediaControllerInstance::MediaControllerServerUpdateRepeatMode( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerUpdateMetadata( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerUpdateMetadata(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } CHECK_EXIST(args, "metadata", out) - const picojson::object& metadata = - args.get("metadata").get(); + const picojson::object& metadata = args.get("metadata").get(); const PlatformResult& result = server_->SetMetadata(metadata); if (!result) { @@ -257,20 +238,17 @@ void MediaControllerInstance::MediaControllerServerUpdateMetadata( } void MediaControllerInstance::MediaControllerServerAddChangeRequestPlaybackInfoListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } CHECK_EXIST(args, "listenerId", out) JsonCallback callback = [this, args](picojson::value* data) -> void { - if (!data) { LOGGER(ERROR) << "No data passed to json callback"; return; @@ -288,32 +266,27 @@ void MediaControllerInstance::MediaControllerServerAddChangeRequestPlaybackInfoL } void MediaControllerInstance::MediaControllerServerRemoveChangeRequestPlaybackInfoListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } server_->SetChangeRequestPlaybackInfoListener(nullptr); } -void MediaControllerInstance::MediaControllerServerAddCommandListener( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerAddCommandListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } JsonCallback on_command = [this, args](picojson::value* request) -> void { - picojson::object& request_o = request->get(); request_o["listenerId"] = args.get("listenerId"); @@ -325,14 +298,12 @@ void MediaControllerInstance::MediaControllerServerAddCommandListener( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerReplyCommand( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerReplyCommand(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -340,21 +311,18 @@ void MediaControllerInstance::MediaControllerServerReplyCommand( CHECK_EXIST(args, "replyId", out) CHECK_EXIST(args, "data", out) - server_->CommandReply(args.get("clientName").get(), - args.get("replyId").to_str(), + server_->CommandReply(args.get("clientName").get(), args.get("replyId").to_str(), args.get("data")); ReportSuccess(out); } void MediaControllerInstance::MediaControllerServerRemoveCommandListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!server_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Server not initialized."), &out, ("Failed: server_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, + ("Failed: server_")); return; } @@ -363,9 +331,8 @@ void MediaControllerInstance::MediaControllerServerRemoveCommandListener( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerManagerGetClient( - const picojson::value& args, - picojson::object& out) { +void MediaControllerInstance::MediaControllerManagerGetClient(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeMediaControllerClient, &out); @@ -385,27 +352,23 @@ void MediaControllerInstance::MediaControllerManagerGetClient( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerClientFindServers( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerClientFindServers(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } CHECK_EXIST(args, "callbackId", out) auto search = [this, args]() -> void { - picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); picojson::value servers = picojson::value(picojson::array()); - PlatformResult result = client_->FindServers( - &servers.get()); + PlatformResult result = client_->FindServers(&servers.get()); response_obj["callbackId"] = args.get("callbackId"); if (result) { @@ -422,14 +385,12 @@ void MediaControllerInstance::MediaControllerClientFindServers( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerClientGetLatestServerInfo( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerClientGetLatestServerInfo(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -443,23 +404,20 @@ void MediaControllerInstance::MediaControllerClientGetLatestServerInfo( ReportSuccess(server_info, out); } -void MediaControllerInstance::MediaControllerClientGetPlaybackInfo( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerClientGetPlaybackInfo(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } CHECK_EXIST(args, "name", out) picojson::value playback_info = picojson::value(picojson::object()); - PlatformResult result = client_->GetPlaybackInfo( - args.get("name").get(), - &playback_info.get()); + PlatformResult result = client_->GetPlaybackInfo(args.get("name").get(), + &playback_info.get()); if (!result) { LogAndReportError(result, &out, ("Failed: client_->GetPlaybackInfo")); @@ -470,13 +428,11 @@ void MediaControllerInstance::MediaControllerClientGetPlaybackInfo( } void MediaControllerInstance::MediaControllerServerInfoSendPlaybackState( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -489,9 +445,8 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackState( picojson::object& response_obj = response.get(); response_obj["callbackId"] = args.get("callbackId"); - PlatformResult result = client_->SendPlaybackState( - args.get("name").get(), - args.get("state").get()); + PlatformResult result = client_->SendPlaybackState(args.get("name").get(), + args.get("state").get()); if (result) { ReportSuccess(response_obj); @@ -508,13 +463,11 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackState( } void MediaControllerInstance::MediaControllerServerInfoSendPlaybackPosition( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -527,9 +480,8 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackPosition( picojson::object& response_obj = response.get(); response_obj["callbackId"] = args.get("callbackId"); - PlatformResult result = client_->SendPlaybackPosition( - args.get("name").get(), - args.get("position").get()); + PlatformResult result = client_->SendPlaybackPosition(args.get("name").get(), + args.get("position").get()); if (result) { ReportSuccess(response_obj); @@ -545,15 +497,13 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackPosition( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -566,9 +516,8 @@ void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode( picojson::object& response_obj = response.get(); response_obj["callbackId"] = args.get("callbackId"); - PlatformResult result = client_->SendShuffleMode( - args.get("name").get(), - args.get("mode").get()); + PlatformResult result = + client_->SendShuffleMode(args.get("name").get(), args.get("mode").get()); if (result) { ReportSuccess(response_obj); @@ -584,14 +533,12 @@ void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -604,9 +551,8 @@ void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode( picojson::object& response_obj = response.get(); response_obj["callbackId"] = args.get("callbackId"); - PlatformResult result = client_->SendRepeatMode( - args.get("name").get(), - args.get("mode").get()); + PlatformResult result = + client_->SendRepeatMode(args.get("name").get(), args.get("mode").get()); if (result) { ReportSuccess(response_obj); @@ -622,14 +568,12 @@ void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode( ReportSuccess(out); } -void MediaControllerInstance::MediaControllerServerInfoSendCommand( - const picojson::value& args, - picojson::object& out) { - +void MediaControllerInstance::MediaControllerServerInfoSendCommand(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -640,7 +584,6 @@ void MediaControllerInstance::MediaControllerServerInfoSendCommand( CHECK_EXIST(args, "data", out) JsonCallback reply_cb = [this, args](picojson::value* reply) -> void { - picojson::object& reply_obj = reply->get(); reply_obj["listenerId"] = args.get("listenerId"); @@ -649,11 +592,8 @@ void MediaControllerInstance::MediaControllerServerInfoSendCommand( }; PlatformResult result = client_->SendCommand( - args.get("name").get(), - args.get("command").get(), - args.get("data"), - args.get("replyId").to_str(), - reply_cb); + args.get("name").get(), args.get("command").get(), args.get("data"), + args.get("replyId").to_str(), reply_cb); if (result) { ReportSuccess(out); @@ -663,20 +603,17 @@ void MediaControllerInstance::MediaControllerServerInfoSendCommand( } void MediaControllerInstance::MediaControllerServerInfoAddServerStatusChangeListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } CHECK_EXIST(args, "listenerId", out) JsonCallback callback = [this, args](picojson::value* data) -> void { - if (nullptr == data) { LOGGER(ERROR) << "No data passed to json callback"; return; @@ -694,13 +631,11 @@ void MediaControllerInstance::MediaControllerServerInfoAddServerStatusChangeList } void MediaControllerInstance::MediaControllerServerInfoRemoveServerStatusChangeListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -708,20 +643,17 @@ void MediaControllerInstance::MediaControllerServerInfoRemoveServerStatusChangeL } void MediaControllerInstance::MediaControllerServerInfoAddPlaybackInfoChangeListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } CHECK_EXIST(args, "listenerId", out) JsonCallback callback = [this, args](picojson::value* data) -> void { - if (!data) { LOGGER(ERROR) << "No data passed to json callback"; return; @@ -739,12 +671,10 @@ void MediaControllerInstance::MediaControllerServerInfoAddPlaybackInfoChangeList } void MediaControllerInstance::MediaControllerServerInfoRemovePlaybackInfoChangeListener( - const picojson::value& args, - picojson::object& out) { - + const picojson::value& args, picojson::object& out) { if (!client_) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, - "Client not initialized."), &out, ("Failed: client_")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, + ("Failed: client_")); return; } @@ -753,5 +683,5 @@ void MediaControllerInstance::MediaControllerServerInfoRemovePlaybackInfoChangeL #undef CHECK_EXIST -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension diff --git a/src/mediacontroller/mediacontroller_instance.h b/src/mediacontroller/mediacontroller_instance.h old mode 100755 new mode 100644 index cc13ad3..981e9e4 --- a/src/mediacontroller/mediacontroller_instance.h +++ b/src/mediacontroller/mediacontroller_instance.h @@ -35,36 +35,46 @@ class MediaControllerInstance : public common::ParsedInstance { // server void MediaControllerManagerCreateServer(const picojson::value& args, picojson::object& out); void MediaControllerServerUpdatePlaybackState(const picojson::value& args, picojson::object& out); - void MediaControllerServerUpdatePlaybackPosition(const picojson::value& args, picojson::object& out); + void MediaControllerServerUpdatePlaybackPosition(const picojson::value& args, + picojson::object& out); void MediaControllerServerUpdateRepeatMode(const picojson::value& args, picojson::object& out); void MediaControllerServerUpdateShuffleMode(const picojson::value& args, picojson::object& out); void MediaControllerServerUpdateMetadata(const picojson::value& args, picojson::object& out); - void MediaControllerServerAddChangeRequestPlaybackInfoListener(const picojson::value& args, picojson::object& out); - void MediaControllerServerRemoveChangeRequestPlaybackInfoListener(const picojson::value& args, picojson::object& out); + void MediaControllerServerAddChangeRequestPlaybackInfoListener(const picojson::value& args, + picojson::object& out); + void MediaControllerServerRemoveChangeRequestPlaybackInfoListener(const picojson::value& args, + picojson::object& out); void MediaControllerServerAddCommandListener(const picojson::value& args, picojson::object& out); void MediaControllerServerReplyCommand(const picojson::value& args, picojson::object& out); - void MediaControllerServerRemoveCommandListener(const picojson::value& args, picojson::object& out); + void MediaControllerServerRemoveCommandListener(const picojson::value& args, + picojson::object& out); // client void MediaControllerManagerGetClient(const picojson::value& args, picojson::object& out); void MediaControllerClientFindServers(const picojson::value& args, picojson::object& out); void MediaControllerClientGetLatestServerInfo(const picojson::value& args, picojson::object& out); void MediaControllerClientGetPlaybackInfo(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoSendPlaybackState(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoSendPlaybackPosition(const picojson::value& args, picojson::object& out); + void MediaControllerServerInfoSendPlaybackState(const picojson::value& args, + picojson::object& out); + void MediaControllerServerInfoSendPlaybackPosition(const picojson::value& args, + picojson::object& out); void MediaControllerServerInfoSendRepeatMode(const picojson::value& args, picojson::object& out); void MediaControllerServerInfoSendShuffleMode(const picojson::value& args, picojson::object& out); void MediaControllerServerInfoSendCommand(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoAddServerStatusChangeListener(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoRemoveServerStatusChangeListener(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoAddPlaybackInfoChangeListener(const picojson::value& args, picojson::object& out); - void MediaControllerServerInfoRemovePlaybackInfoChangeListener(const picojson::value& args, picojson::object& out); + void MediaControllerServerInfoAddServerStatusChangeListener(const picojson::value& args, + picojson::object& out); + void MediaControllerServerInfoRemoveServerStatusChangeListener(const picojson::value& args, + picojson::object& out); + void MediaControllerServerInfoAddPlaybackInfoChangeListener(const picojson::value& args, + picojson::object& out); + void MediaControllerServerInfoRemovePlaybackInfoChangeListener(const picojson::value& args, + picojson::object& out); std::shared_ptr client_; std::shared_ptr server_; }; -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension -#endif // MEDIACONTROLLER_MEDIACONTROLLER_INSTANCE_H_ +#endif // MEDIACONTROLLER_MEDIACONTROLLER_INSTANCE_H_ diff --git a/src/mediacontroller/mediacontroller_server.cc b/src/mediacontroller/mediacontroller_server.cc index 8e03479..62416ea 100644 --- a/src/mediacontroller/mediacontroller_server.cc +++ b/src/mediacontroller/mediacontroller_server.cc @@ -29,12 +29,9 @@ namespace mediacontroller { namespace { // The privileges that are required in Application API -const std::string kInternalCommandSendPlaybackPosition - = "__internal_sendPlaybackPosition"; -const std::string kInternalCommandSendShuffleMode - = "__internal_sendShuffleMode"; -const std::string kInternalCommandSendRepeatMode - = "__internal_sendRepeatMode"; +const std::string kInternalCommandSendPlaybackPosition = "__internal_sendPlaybackPosition"; +const std::string kInternalCommandSendShuffleMode = "__internal_sendShuffleMode"; +const std::string kInternalCommandSendRepeatMode = "__internal_sendRepeatMode"; } // namespace using common::PlatformResult; @@ -45,7 +42,6 @@ MediaControllerServer::MediaControllerServer() : handle_(nullptr) { } MediaControllerServer::~MediaControllerServer() { - LoggerD("Enter"); if (handle_) { @@ -63,125 +59,106 @@ MediaControllerServer::~MediaControllerServer() { } PlatformResult MediaControllerServer::Init() { - LoggerD("Enter"); int ret = mc_server_create(&handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to create media controller server", - ("mc_server_create() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to create media controller server", + ("mc_server_create() error: %d, message: %s", ret, get_error_message(ret))); } - ret = mc_server_set_custom_command_received_cb(handle_, - OnCommandReceived, - this); + ret = mc_server_set_custom_command_received_cb(handle_, OnCommandReceived, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to set command callback", - ("mc_server_set_custom_command_received_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to set command callback", + ("mc_server_set_custom_command_received_cb() error: %d, message: %s", + ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerServer::SetPlaybackState( - const std::string& state) { - +PlatformResult MediaControllerServer::SetPlaybackState(const std::string& state) { LoggerD("Enter"); int state_int; - PlatformResult result = Types::StringToPlatformEnum( - Types::kMediaControllerPlaybackState, state, &state_int); + PlatformResult result = + Types::StringToPlatformEnum(Types::kMediaControllerPlaybackState, state, &state_int); if (!result) { return result; } - int ret = mc_server_set_playback_state( - handle_, static_cast(state_int)); + int ret = mc_server_set_playback_state(handle_, static_cast(state_int)); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error setting playback state", - ("mc_server_set_playback_state() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error setting playback state", + ("mc_server_set_playback_state() error: %d, message: %s", ret, get_error_message(ret))); } ret = mc_server_update_playback_info(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error updating playback info", - ("mc_server_update_playback_info() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error updating playback info", + ("mc_server_update_playback_info() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MediaControllerServer::SetPlaybackPosition(double position) { - LoggerD("Enter"); - int ret = mc_server_set_playback_position( - handle_, static_cast(position)); + int ret = mc_server_set_playback_position(handle_, static_cast(position)); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error setting playback position", - ("mc_server_set_playback_position() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error setting playback position", + ("mc_server_set_playback_position() error: %d, message: %s", ret, get_error_message(ret))); } ret = mc_server_update_playback_info(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error updating playback info", - ("mc_server_update_playback_info() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error updating playback info", + ("mc_server_update_playback_info() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MediaControllerServer::SetShuffleMode(bool mode) { - LoggerD("Enter"); - int ret = mc_server_update_shuffle_mode(handle_, - mode ? MC_SHUFFLE_MODE_ON - : MC_SHUFFLE_MODE_OFF); + int ret = mc_server_update_shuffle_mode(handle_, mode ? MC_SHUFFLE_MODE_ON : MC_SHUFFLE_MODE_OFF); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error updating shuffle mode", - ("mc_server_update_shuffle_mode() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error updating shuffle mode", + ("mc_server_update_shuffle_mode() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MediaControllerServer::SetRepeatMode(bool mode) { - LoggerD("Enter"); - int ret = mc_server_update_repeat_mode(handle_, - mode ? MC_REPEAT_MODE_ON - : MC_REPEAT_MODE_OFF); + int ret = mc_server_update_repeat_mode(handle_, mode ? MC_REPEAT_MODE_ON : MC_REPEAT_MODE_OFF); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error updating repeat mode", - ("mc_server_update_repeat_mode() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error updating repeat mode", + ("mc_server_update_repeat_mode() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerServer::SetMetadata( - const picojson::object& metadata) { - +PlatformResult MediaControllerServer::SetMetadata(const picojson::object& metadata) { LoggerD("Enter"); int attribute_int, ret; - for (picojson::object::const_iterator i = metadata.begin(); - i != metadata.end(); - ++i) { - - PlatformResult result = Types::StringToPlatformEnum( - Types::kMediaControllerMetadataAttribute, i->first, &attribute_int); + for (picojson::object::const_iterator i = metadata.begin(); i != metadata.end(); ++i) { + PlatformResult result = Types::StringToPlatformEnum(Types::kMediaControllerMetadataAttribute, + i->first, &attribute_int); if (!result) { return result; } @@ -189,27 +166,24 @@ PlatformResult MediaControllerServer::SetMetadata( ret = mc_server_set_metadata(handle_, static_cast(attribute_int), i->second.to_str().c_str()); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error setting metadata", - ("mc_server_set_metadata(%s) error: %d, message: %s", i->first.c_str(), ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error setting metadata", + ("mc_server_set_metadata(%s) error: %d, message: %s", + i->first.c_str(), ret, get_error_message(ret))); } } ret = mc_server_update_metadata(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error updating metadata", - ("mc_server_update_metadata() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error updating metadata", + ("mc_server_update_metadata() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -void MediaControllerServer::OnCommandReceived(const char* client_name, - const char* command, - bundle* bundle, - void* user_data) { - +void MediaControllerServer::OnCommandReceived(const char* client_name, const char* command, + bundle* bundle, void* user_data) { LoggerD("Enter"); MediaControllerServer* server = static_cast(user_data); @@ -248,8 +222,7 @@ void MediaControllerServer::OnCommandReceived(const char* client_name, if (command == kInternalCommandSendPlaybackPosition) { double position = data.get("position").get(); server->SetPlaybackPosition(position); - server->OnPlaybackPositionCommand(client_name, - static_cast(position), + server->OnPlaybackPositionCommand(client_name, static_cast(position), server); server->CommandReply(client_name, reply_id_str, data); return; @@ -257,8 +230,7 @@ void MediaControllerServer::OnCommandReceived(const char* client_name, if (command == kInternalCommandSendShuffleMode) { bool mode = data.get("mode").get(); server->SetShuffleMode(mode); - server->OnShuffleModeCommand(client_name, - mode ? MC_SHUFFLE_MODE_ON : MC_SHUFFLE_MODE_OFF, + server->OnShuffleModeCommand(client_name, mode ? MC_SHUFFLE_MODE_ON : MC_SHUFFLE_MODE_OFF, server); server->CommandReply(client_name, reply_id_str, data); return; @@ -266,9 +238,7 @@ void MediaControllerServer::OnCommandReceived(const char* client_name, if (command == kInternalCommandSendRepeatMode) { bool mode = data.get("mode").get(); server->SetRepeatMode(mode); - server->OnRepeatModeCommand(client_name, - mode ? MC_REPEAT_MODE_ON : MC_REPEAT_MODE_OFF, - server); + server->OnRepeatModeCommand(client_name, mode ? MC_REPEAT_MODE_ON : MC_REPEAT_MODE_OFF, server); server->CommandReply(client_name, reply_id_str, data); return; } @@ -286,11 +256,9 @@ void MediaControllerServer::OnCommandReceived(const char* client_name, } } -PlatformResult MediaControllerServer::CommandReply( - const std::string& client_name, - const std::string& reply_id, - const picojson::value& data) { - +PlatformResult MediaControllerServer::CommandReply(const std::string& client_name, + const std::string& reply_id, + const picojson::value& data) { LoggerD("Enter"); int ret; @@ -302,55 +270,53 @@ PlatformResult MediaControllerServer::CommandReply( ret = bundle_add(bundle, "replyId", reply_id.c_str()); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to add replyId to bundle", - ("bundle_add(replyId) error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to add replyId to bundle", + ("bundle_add(replyId) error: %d, message: %s", ret, get_error_message(ret))); } ret = bundle_add(bundle, "data", data.serialize().c_str()); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to add data to bundle", - ("bundle_add(data) error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to add data to bundle", + ("bundle_add(data) error: %d, message: %s", ret, get_error_message(ret))); } ret = mc_server_send_command_reply(handle_, client_name.c_str(), 0, bundle); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error sending command reply", - ("mc_server_send_command_reply() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error sending command reply", + ("mc_server_send_command_reply() error: %d, message: %s", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MediaControllerServer::SetChangeRequestPlaybackInfoListener( - JsonCallback callback) { - +PlatformResult MediaControllerServer::SetChangeRequestPlaybackInfoListener(JsonCallback callback) { LoggerD("Enter"); if (callback && change_request_playback_info_listener_) { - return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, - "Listener already registered"); + return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); } change_request_playback_info_listener_ = callback; int ret; - if (callback) { // set platform callbacks - ret = mc_server_set_playback_state_command_received_cb( - handle_, OnPlaybackStateCommand, this); + if (callback) { // set platform callbacks + ret = mc_server_set_playback_state_command_received_cb(handle_, OnPlaybackStateCommand, this); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to set playback state command listener", - ("mc_server_set_playback_state_command_received_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to set playback state command listener", + ("mc_server_set_playback_state_command_received_cb() error: %d, message: %s", ret, + get_error_message(ret))); } - } else { // unset platform callbacks + } else { // unset platform callbacks ret = mc_server_unset_playback_state_command_received_cb(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unable to unset playback state command listener", - ("mc_server_unset_playback_state_command_received_cb() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Unable to unset playback state command listener", + ("mc_server_unset_playback_state_command_received_cb() error: %d, message: %s", ret, + get_error_message(ret))); } } @@ -358,9 +324,7 @@ PlatformResult MediaControllerServer::SetChangeRequestPlaybackInfoListener( } void MediaControllerServer::OnPlaybackStateCommand(const char* client_name, - mc_playback_states_e state_e, - void *user_data) { - + mc_playback_states_e state_e, void* user_data) { LoggerD("Enter"); MediaControllerServer* server = static_cast(user_data); @@ -371,9 +335,8 @@ void MediaControllerServer::OnPlaybackStateCommand(const char* client_name, } std::string state; - PlatformResult result = Types::PlatformEnumToString( - Types::kMediaControllerPlaybackState, - static_cast(state_e), &state); + PlatformResult result = Types::PlatformEnumToString(Types::kMediaControllerPlaybackState, + static_cast(state_e), &state); if (!result) { LOGGER(ERROR) << "PlatformEnumToString failed, error: " << result.message(); return; @@ -388,11 +351,9 @@ void MediaControllerServer::OnPlaybackStateCommand(const char* client_name, server->change_request_playback_info_listener_(&data); } -void MediaControllerServer::OnPlaybackPositionCommand( - const char* client_name, - unsigned long long position, - void* user_data) { - +void MediaControllerServer::OnPlaybackPositionCommand(const char* client_name, + unsigned long long position, + void* user_data) { LoggerD("Enter"); MediaControllerServer* server = static_cast(user_data); @@ -411,10 +372,8 @@ void MediaControllerServer::OnPlaybackPositionCommand( server->change_request_playback_info_listener_(&data); } -void MediaControllerServer::OnShuffleModeCommand(const char* client_name, - mc_shuffle_mode_e mode, +void MediaControllerServer::OnShuffleModeCommand(const char* client_name, mc_shuffle_mode_e mode, void* user_data) { - LoggerD("Enter"); MediaControllerServer* server = static_cast(user_data); @@ -433,10 +392,8 @@ void MediaControllerServer::OnShuffleModeCommand(const char* client_name, server->change_request_playback_info_listener_(&data); } -void MediaControllerServer::OnRepeatModeCommand(const char* client_name, - mc_repeat_mode_e mode, +void MediaControllerServer::OnRepeatModeCommand(const char* client_name, mc_repeat_mode_e mode, void* user_data) { - LoggerD("Enter"); MediaControllerServer* server = static_cast(user_data); @@ -455,5 +412,5 @@ void MediaControllerServer::OnRepeatModeCommand(const char* client_name, server->change_request_playback_info_listener_(&data); } -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension diff --git a/src/mediacontroller/mediacontroller_server.h b/src/mediacontroller/mediacontroller_server.h old mode 100755 new mode 100644 index 1536ca9..8654a69 --- a/src/mediacontroller/mediacontroller_server.h +++ b/src/mediacontroller/mediacontroller_server.h @@ -38,11 +38,9 @@ class MediaControllerServer { common::PlatformResult SetRepeatMode(bool mode); common::PlatformResult SetMetadata(const picojson::object& metadata); - common::PlatformResult SetChangeRequestPlaybackInfoListener( - JsonCallback callback); + common::PlatformResult SetChangeRequestPlaybackInfoListener(JsonCallback callback); - common::PlatformResult CommandReply(const std::string& client_name, - const std::string& reply_id, + common::PlatformResult CommandReply(const std::string& client_name, const std::string& reply_id, const picojson::value& data); void set_command_listener(const JsonCallback& func) { @@ -55,26 +53,19 @@ class MediaControllerServer { JsonCallback change_request_playback_info_listener_; JsonCallback command_listener_; - static void OnPlaybackStateCommand(const char* client_name, - mc_playback_states_e state_e, - void *user_data); - static void OnPlaybackPositionCommand(const char* client_name, - unsigned long long position, + static void OnPlaybackStateCommand(const char* client_name, mc_playback_states_e state_e, + void* user_data); + static void OnPlaybackPositionCommand(const char* client_name, unsigned long long position, void* user_data); - static void OnShuffleModeCommand(const char* client_name, - mc_shuffle_mode_e mode, + static void OnShuffleModeCommand(const char* client_name, mc_shuffle_mode_e mode, void* user_data); - static void OnRepeatModeCommand(const char* client_name, - mc_repeat_mode_e mode, - void* user_data); + static void OnRepeatModeCommand(const char* client_name, mc_repeat_mode_e mode, void* user_data); - static void OnCommandReceived(const char* client_name, - const char* command, - bundle* data, + static void OnCommandReceived(const char* client_name, const char* command, bundle* data, void* user_data); }; -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension #endif // MEDIACONTROLLER_MEDIACONTROLLER_SERVER_H_ diff --git a/src/mediacontroller/mediacontroller_types.cc b/src/mediacontroller/mediacontroller_types.cc index f426976..f54907c 100644 --- a/src/mediacontroller/mediacontroller_types.cc +++ b/src/mediacontroller/mediacontroller_types.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "mediacontroller/mediacontroller_types.h" #include @@ -28,46 +28,39 @@ namespace mediacontroller { using common::PlatformResult; using common::ErrorCode; -const std::string Types::kMediaControllerServerState - = "MediaControllerServerState"; -const std::string Types::kMediaControllerPlaybackState - = "MediaControllerPlaybackState"; -const std::string Types::kMediaControllerMetadataAttribute - = "MediaControllerMetadataAttribute"; - -const PlatformEnumMap Types::platform_enum_map_ = { - {kMediaControllerServerState, { - {"NONE", MC_SERVER_STATE_NONE}, - {"ACTIVE", MC_SERVER_STATE_ACTIVATE}, - {"INACTIVE", MC_SERVER_STATE_DEACTIVATE}}}, - {kMediaControllerPlaybackState, { - {"PLAY", MC_PLAYBACK_STATE_PLAYING}, - {"PAUSE", MC_PLAYBACK_STATE_PAUSED}, - {"STOP", MC_PLAYBACK_STATE_STOPPED}, - {"NEXT", MC_PLAYBACK_STATE_NEXT_FILE}, - {"PREV", MC_PLAYBACK_STATE_PREV_FILE}, - {"FORWARD", MC_PLAYBACK_STATE_FAST_FORWARD}, - {"REWIND", MC_PLAYBACK_STATE_REWIND}}}, - {kMediaControllerMetadataAttribute, { - {"title", MC_META_MEDIA_TITLE}, - {"artist", MC_META_MEDIA_ARTIST}, - {"album", MC_META_MEDIA_ALBUM}, - {"author", MC_META_MEDIA_AUTHOR}, - {"genre", MC_META_MEDIA_GENRE}, - {"duration", MC_META_MEDIA_DURATION}, - {"date", MC_META_MEDIA_DATE}, - {"copyright", MC_META_MEDIA_COPYRIGHT}, - {"description", MC_META_MEDIA_DESCRIPTION}, - {"trackNum", MC_META_MEDIA_TRACK_NUM}, - {"picture", MC_META_MEDIA_PICTURE} - }} -}; +const std::string Types::kMediaControllerServerState = "MediaControllerServerState"; +const std::string Types::kMediaControllerPlaybackState = "MediaControllerPlaybackState"; +const std::string Types::kMediaControllerMetadataAttribute = "MediaControllerMetadataAttribute"; + +const PlatformEnumMap Types::platform_enum_map_ = {{kMediaControllerServerState, + {{"NONE", MC_SERVER_STATE_NONE}, + {"ACTIVE", MC_SERVER_STATE_ACTIVATE}, + {"INACTIVE", MC_SERVER_STATE_DEACTIVATE}}}, + {kMediaControllerPlaybackState, + {{"PLAY", MC_PLAYBACK_STATE_PLAYING}, + {"PAUSE", MC_PLAYBACK_STATE_PAUSED}, + {"STOP", MC_PLAYBACK_STATE_STOPPED}, + {"NEXT", MC_PLAYBACK_STATE_NEXT_FILE}, + {"PREV", MC_PLAYBACK_STATE_PREV_FILE}, + {"FORWARD", MC_PLAYBACK_STATE_FAST_FORWARD}, + {"REWIND", MC_PLAYBACK_STATE_REWIND}}}, + {kMediaControllerMetadataAttribute, + {{"title", MC_META_MEDIA_TITLE}, + {"artist", MC_META_MEDIA_ARTIST}, + {"album", MC_META_MEDIA_ALBUM}, + {"author", MC_META_MEDIA_AUTHOR}, + {"genre", MC_META_MEDIA_GENRE}, + {"duration", MC_META_MEDIA_DURATION}, + {"date", MC_META_MEDIA_DATE}, + {"copyright", MC_META_MEDIA_COPYRIGHT}, + {"description", MC_META_MEDIA_DESCRIPTION}, + {"trackNum", MC_META_MEDIA_TRACK_NUM}, + {"picture", MC_META_MEDIA_PICTURE}}}}; PlatformEnumReverseMap Types::platform_enum_reverse_map_ = {}; PlatformResult Types::GetPlatformEnumMap(const std::string& type, - std::map* enum_map) { - + std::map* enum_map) { LoggerD("Enter"); auto iter = platform_enum_map_.find(type); @@ -81,10 +74,8 @@ PlatformResult Types::GetPlatformEnumMap(const std::string& type, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Types::StringToPlatformEnum(const std::string& type, - const std::string& value, +PlatformResult Types::StringToPlatformEnum(const std::string& type, const std::string& value, int* platform_enum) { - LoggerD("Enter"); std::map def; @@ -99,13 +90,11 @@ PlatformResult Types::StringToPlatformEnum(const std::string& type, return PlatformResult(ErrorCode::NO_ERROR); } - std::string message = - "Platform enum value " + value + " not found for " + type; + std::string message = "Platform enum value " + value + " not found for " + type; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } -PlatformResult Types::PlatformEnumToString(const std::string& type, - int value, +PlatformResult Types::PlatformEnumToString(const std::string& type, int value, std::string* platform_str) { LoggerD("Enter"); @@ -122,7 +111,7 @@ PlatformResult Types::PlatformEnumToString(const std::string& type, auto it = platform_enum_reverse_map_.find(type); if (it == platform_enum_reverse_map_.end()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - std::string("Undefined platform enum type ") + type); + std::string("Undefined platform enum type ") + type); } auto def = platform_enum_reverse_map_.at(type); @@ -132,30 +121,27 @@ PlatformResult Types::PlatformEnumToString(const std::string& type, return PlatformResult(ErrorCode::NO_ERROR); } - std::string message = "Platform enum value " + std::to_string(value) + - " not found for " + type; + std::string message = "Platform enum value " + std::to_string(value) + " not found for " + type; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } -PlatformResult Types::ConvertPlaybackState(mc_playback_h playback_h, - std::string* state) { +PlatformResult Types::ConvertPlaybackState(mc_playback_h playback_h, std::string* state) { LoggerD("Enter"); int ret; mc_playback_states_e state_e; ret = mc_client_get_playback_state(playback_h, &state_e); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting playback state", - ("mc_client_get_playback_state() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error getting playback state", + ("mc_client_get_playback_state() error: %d, message: %s", ret, get_error_message(ret))); } if (state_e == MC_PLAYBACK_STATE_NONE) { state_e = MC_PLAYBACK_STATE_STOPPED; } - PlatformResult result = Types::PlatformEnumToString( - Types::kMediaControllerPlaybackState, - static_cast(state_e), state); + PlatformResult result = Types::PlatformEnumToString(Types::kMediaControllerPlaybackState, + static_cast(state_e), state); if (!result) { LOGGER(ERROR) << "PlatformEnumToString failed, error: " << result.message(); return result; @@ -164,8 +150,7 @@ PlatformResult Types::ConvertPlaybackState(mc_playback_h playback_h, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, - double* position) { +PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, double* position) { LoggerD("Enter"); int ret; @@ -173,9 +158,9 @@ PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, unsigned long long pos; ret = mc_client_get_playback_position(playback_h, &pos); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting playback position", - ("mc_client_get_playback_position() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error getting playback position", + ("mc_client_get_playback_position() error: %d, message: %s", ret, get_error_message(ret))); } *position = static_cast(pos); @@ -183,13 +168,12 @@ PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Types::ConvertMetadata(mc_metadata_h metadata_h, - picojson::object* metadata) { +PlatformResult Types::ConvertMetadata(mc_metadata_h metadata_h, picojson::object* metadata) { LoggerD("Enter"); std::map metadata_fields; - PlatformResult result = GetPlatformEnumMap( - Types::kMediaControllerMetadataAttribute, &metadata_fields); + PlatformResult result = + GetPlatformEnumMap(Types::kMediaControllerMetadataAttribute, &metadata_fields); if (!result) { LOGGER(ERROR) << "GetPlatformEnumMap failed, error: " << result.message(); return result; @@ -201,13 +185,11 @@ PlatformResult Types::ConvertMetadata(mc_metadata_h metadata_h, }; for (auto& field : metadata_fields) { - int ret = mc_client_get_metadata(metadata_h, - static_cast(field.second), - &value); + int ret = mc_client_get_metadata(metadata_h, static_cast(field.second), &value); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Error getting metadata", - ("mc_client_get_metadata(%s) error: %d, message: %s", field.first.c_str(), ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error getting metadata", + ("mc_client_get_metadata(%s) error: %d, message: %s", + field.first.c_str(), ret, get_error_message(ret))); } (*metadata)[field.first] = picojson::value(std::string(value ? value : "")); @@ -216,5 +198,5 @@ PlatformResult Types::ConvertMetadata(mc_metadata_h metadata_h, return PlatformResult(ErrorCode::NO_ERROR); } -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension diff --git a/src/mediacontroller/mediacontroller_types.h b/src/mediacontroller/mediacontroller_types.h old mode 100755 new mode 100644 index 1e0a138..20966aa --- a/src/mediacontroller/mediacontroller_types.h +++ b/src/mediacontroller/mediacontroller_types.h @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MEDIACONTROLLER_MEDIACONTROLLER_TYPES_H_ #define MEDIACONTROLLER_MEDIACONTROLLER_TYPES_H_ +#include #include #include -#include #include #include "common/platform_result.h" @@ -37,21 +37,17 @@ class Types { static const std::string kMediaControllerPlaybackState; static const std::string kMediaControllerMetadataAttribute; - static common::PlatformResult GetPlatformEnumMap( - const std::string& type, std::map* platform_str); + static common::PlatformResult GetPlatformEnumMap(const std::string& type, + std::map* platform_str); static common::PlatformResult StringToPlatformEnum(const std::string& type, - const std::string& value, - int* platform_enum); + const std::string& value, int* platform_enum); - static common::PlatformResult PlatformEnumToString(const std::string& type, - int value, + static common::PlatformResult PlatformEnumToString(const std::string& type, int value, std::string* platform_str); - static common::PlatformResult ConvertPlaybackState(mc_playback_h playback_h, - std::string* state); - static common::PlatformResult ConvertPlaybackPosition(mc_playback_h playback_h, - double* position); + static common::PlatformResult ConvertPlaybackState(mc_playback_h playback_h, std::string* state); + static common::PlatformResult ConvertPlaybackPosition(mc_playback_h playback_h, double* position); static common::PlatformResult ConvertMetadata(mc_metadata_h metadata_h, picojson::object* metadata); @@ -60,7 +56,7 @@ class Types { static PlatformEnumReverseMap platform_enum_reverse_map_; }; -} // namespace mediacontroller -} // namespace extension +} // namespace mediacontroller +} // namespace extension #endif // MEDIACONTROLLER_MEDIACONTROLLER_TYPES_H_ diff --git a/src/mediakey/mediakey_extension.cc b/src/mediakey/mediakey_extension.cc old mode 100755 new mode 100644 index b10658c..7da7eae --- a/src/mediakey/mediakey_extension.cc +++ b/src/mediakey/mediakey_extension.cc @@ -43,4 +43,3 @@ common::Instance* MediaKeyExtension::CreateInstance() { common::Extension* CreateExtension() { return new extension::mediakey::MediaKeyExtension(); } - diff --git a/src/mediakey/mediakey_extension.h b/src/mediakey/mediakey_extension.h old mode 100755 new mode 100644 index 7fa4b95..6942efc --- a/src/mediakey/mediakey_extension.h +++ b/src/mediakey/mediakey_extension.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef SRC_MEDIAKEY_MEDIAKEY_EXTENSION_H_ #define SRC_MEDIAKEY_MEDIAKEY_EXTENSION_H_ diff --git a/src/mediakey/mediakey_instance.cc b/src/mediakey/mediakey_instance.cc old mode 100755 new mode 100644 index 892ba07..4a31a1e --- a/src/mediakey/mediakey_instance.cc +++ b/src/mediakey/mediakey_instance.cc @@ -13,36 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + +#include "mediakey/mediakey_instance.h" #include #include #include "common/logger.h" -#include "mediakey/mediakey_instance.h" #include "mediakey/mediakey_manager.h" namespace extension { namespace mediakey { const std::map kMediaKeyTypeMap = { - { MEDIA_KEY_PLAY, "MEDIA_PLAY" }, - { MEDIA_KEY_STOP, "MEDIA_STOP" }, - { MEDIA_KEY_PAUSE, "MEDIA_PAUSE" }, - { MEDIA_KEY_PREVIOUS, "MEDIA_PREVIOUS" }, - { MEDIA_KEY_NEXT, "MEDIA_NEXT" }, - { MEDIA_KEY_FASTFORWARD, "MEDIA_FAST_FORWARD" }, - { MEDIA_KEY_REWIND, "MEDIA_REWIND" }, - { MEDIA_KEY_PLAYPAUSE, "MEDIA_PLAY_PAUSE" } }; + {MEDIA_KEY_PLAY, "MEDIA_PLAY"}, {MEDIA_KEY_STOP, "MEDIA_STOP"}, + {MEDIA_KEY_PAUSE, "MEDIA_PAUSE"}, {MEDIA_KEY_PREVIOUS, "MEDIA_PREVIOUS"}, + {MEDIA_KEY_NEXT, "MEDIA_NEXT"}, {MEDIA_KEY_FASTFORWARD, "MEDIA_FAST_FORWARD"}, + {MEDIA_KEY_REWIND, "MEDIA_REWIND"}, {MEDIA_KEY_PLAYPAUSE, "MEDIA_PLAY_PAUSE"}}; MediaKeyInstance::MediaKeyInstance() { LoggerD("Entered"); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&MediaKeyInstance::x, this, _1, _2)); - REGISTER_SYNC("MediaKeyManager_setMediaKeyEventListener", - SetMediaKeyEventListener); - REGISTER_SYNC("MediaKeyManager_unsetMediaKeyEventListener", - UnsetMediaKeyEventListener); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&MediaKeyInstance::x, this, _1, _2)); + REGISTER_SYNC("MediaKeyManager_setMediaKeyEventListener", SetMediaKeyEventListener); + REGISTER_SYNC("MediaKeyManager_unsetMediaKeyEventListener", UnsetMediaKeyEventListener); #undef REGISTER_SYNC } @@ -53,11 +46,10 @@ MediaKeyInstance::~MediaKeyInstance() { void MediaKeyInstance::SetMediaKeyEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); - common::PlatformResult result = MediaKeyManager::GetInstance() - .RegisterMediaKeyEventListener(this); + common::PlatformResult result = + MediaKeyManager::GetInstance().RegisterMediaKeyEventListener(this); if (result.IsError()) { LogAndReportError(result, &out, ("Failed to set media key event listener")); } else { @@ -68,8 +60,7 @@ void MediaKeyInstance::SetMediaKeyEventListener(const picojson::value& args, void MediaKeyInstance::UnsetMediaKeyEventListener(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); - common::PlatformResult result = MediaKeyManager::GetInstance() - .UnregisterMediaKeyEventListener(); + common::PlatformResult result = MediaKeyManager::GetInstance().UnregisterMediaKeyEventListener(); if (result.IsError()) { LogAndReportError(result, &out, ("Failed to remove media key event listener")); } else { @@ -87,8 +78,7 @@ void MediaKeyInstance::OnReleasedMediaKeyEventCallback(media_key_e type) { PostEvent("onReleasedMediaKeyEventCallback", type); } -void MediaKeyInstance::PostEvent(const std::string& eventCallback, - media_key_e type) { +void MediaKeyInstance::PostEvent(const std::string& eventCallback, media_key_e type) { LoggerD("Enter"); auto k = kMediaKeyTypeMap.find(type); if (k != kMediaKeyTypeMap.end()) { @@ -97,8 +87,7 @@ void MediaKeyInstance::PostEvent(const std::string& eventCallback, obj["listenerId"] = picojson::value(eventCallback); obj["type"] = picojson::value((k->second).c_str()); Instance::PostMessage(this, event.serialize().c_str()); - } - else { + } else { LoggerD("Unsupported key"); } } diff --git a/src/mediakey/mediakey_instance.h b/src/mediakey/mediakey_instance.h old mode 100755 new mode 100644 index 63c0239..328ca91 --- a/src/mediakey/mediakey_instance.h +++ b/src/mediakey/mediakey_instance.h @@ -33,10 +33,8 @@ class MediaKeyInstance : public common::ParsedInstance, public MediaKeyListener virtual ~MediaKeyInstance(); private: - void SetMediaKeyEventListener(const picojson::value& args, - picojson::object& out); - void UnsetMediaKeyEventListener(const picojson::value& args, - picojson::object& out); + void SetMediaKeyEventListener(const picojson::value& args, picojson::object& out); + void UnsetMediaKeyEventListener(const picojson::value& args, picojson::object& out); virtual void OnPressedMediaKeyEventCallback(media_key_e type); virtual void OnReleasedMediaKeyEventCallback(media_key_e type); void PostEvent(const std::string& event, media_key_e type); diff --git a/src/mediakey/mediakey_manager.cc b/src/mediakey/mediakey_manager.cc old mode 100755 new mode 100644 index 71a1cf3..0518214 --- a/src/mediakey/mediakey_manager.cc +++ b/src/mediakey/mediakey_manager.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "mediakey/mediakey_manager.h" #include "common/logger.h" #include "common/platform_exception.h" @@ -33,13 +33,11 @@ MediaKeyManager& MediaKeyManager::GetInstance() { } MediaKeyManager::MediaKeyManager() - : m_media_key_listener(nullptr), - m_media_key_listener_registered(false) { + : m_media_key_listener(nullptr), m_media_key_listener_registered(false) { LoggerD("Enter"); } -common::PlatformResult MediaKeyManager::RegisterMediaKeyEventListener( - MediaKeyListener* listener) { +common::PlatformResult MediaKeyManager::RegisterMediaKeyEventListener(MediaKeyListener* listener) { LoggerD("Enter"); if (!m_media_key_listener_registered) { LoggerD("before calling media_key_reserve"); @@ -47,8 +45,7 @@ common::PlatformResult MediaKeyManager::RegisterMediaKeyEventListener( LoggerD("after calling media_key_reserve - result = %d", ret); if (MEDIA_KEY_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Failed to register a media keys change event callback", + ErrorCode::UNKNOWN_ERR, "Failed to register a media keys change event callback", ("media_key_reserve() error: %d, message: %s", ret, get_error_message(ret))); } m_media_key_listener = listener; @@ -63,8 +60,7 @@ common::PlatformResult MediaKeyManager::UnregisterMediaKeyEventListener() { int ret = media_key_release(); if (MEDIA_KEY_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Failed to unregister the change event callback function", + ErrorCode::UNKNOWN_ERR, "Failed to unregister the change event callback function", ("media_key_release() error: %d, message: %s", ret, get_error_message(ret))); } } @@ -73,8 +69,7 @@ common::PlatformResult MediaKeyManager::UnregisterMediaKeyEventListener() { return common::PlatformResult(ErrorCode::NO_ERROR); } -void MediaKeyManager::MediaKeyEventCallback(media_key_e key, - media_key_event_e status, +void MediaKeyManager::MediaKeyEventCallback(media_key_e key, media_key_event_e status, void* user_data) { LoggerD("Enter"); if (!GetInstance().m_media_key_listener) { diff --git a/src/mediakey/mediakey_manager.h b/src/mediakey/mediakey_manager.h old mode 100755 new mode 100644 index 7b95a23..081f528 --- a/src/mediakey/mediakey_manager.h +++ b/src/mediakey/mediakey_manager.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include #include "common/platform_result.h" @@ -25,25 +25,23 @@ namespace mediakey { class MediaKeyListener { public: - virtual void OnPressedMediaKeyEventCallback(media_key_e type)= 0; - virtual void OnReleasedMediaKeyEventCallback(media_key_e type)= 0; + virtual void OnPressedMediaKeyEventCallback(media_key_e type) = 0; + virtual void OnReleasedMediaKeyEventCallback(media_key_e type) = 0; virtual ~MediaKeyListener(); }; class MediaKeyManager { public: - common::PlatformResult RegisterMediaKeyEventListener( - MediaKeyListener* listener); + common::PlatformResult RegisterMediaKeyEventListener(MediaKeyListener* listener); common::PlatformResult UnregisterMediaKeyEventListener(); static MediaKeyManager& GetInstance(); - static void MediaKeyEventCallback(media_key_e key, media_key_event_e status, - void* user_data); + static void MediaKeyEventCallback(media_key_e key, media_key_event_e status, void* user_data); private: // Not copyable, assignable, movable MediaKeyManager(MediaKeyManager const&) = delete; void operator=(MediaKeyManager const&) = delete; - MediaKeyManager(MediaKeyManager &&) = delete; + MediaKeyManager(MediaKeyManager&&) = delete; MediaKeyManager(); MediaKeyListener* m_media_key_listener; diff --git a/src/messageport/messageport_extension.cc b/src/messageport/messageport_extension.cc old mode 100755 new mode 100644 index d77a194..5439469 --- a/src/messageport/messageport_extension.cc +++ b/src/messageport/messageport_extension.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "messageport/messageport_extension.h" #include "messageport/messageport_instance.h" @@ -30,7 +30,8 @@ MessageportExtension::MessageportExtension() { SetJavaScriptAPI(kSource_messageport_api); } -MessageportExtension::~MessageportExtension() {} +MessageportExtension::~MessageportExtension() { +} common::Instance* MessageportExtension::CreateInstance() { return new extension::messageport::MessageportInstance; diff --git a/src/messageport/messageport_instance.cc b/src/messageport/messageport_instance.cc old mode 100755 new mode 100644 index 36aa678..e6d63cd --- a/src/messageport/messageport_instance.cc +++ b/src/messageport/messageport_instance.cc @@ -16,13 +16,13 @@ #include "messageport/messageport_instance.h" +#include #include -#include #include -#include +#include -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" namespace extension { @@ -38,8 +38,8 @@ MessageportInstance::MessageportInstance() { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&MessageportInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) \ + RegisterSyncHandler(c, std::bind(&MessageportInstance::x, this, _1, _2)); REGISTER_SYNC("MessagePortManager_requestTrustedRemoteMessagePort", MessagePortManagerRequesttrustedremotemessageport); REGISTER_SYNC("MessagePortManager_requestLocalMessagePort", @@ -49,14 +49,13 @@ MessageportInstance::MessageportInstance() { REGISTER_SYNC("MessagePortManager_requestRemoteMessagePort", MessagePortManagerRequestremotemessageport); REGISTER_SYNC("RemoteMessagePort_sendMessage", RemoteMessagePortSendmessage); - #undef REGISTER_SYNC +#undef REGISTER_SYNC } MessageportInstance::~MessageportInstance() { LoggerD("Enter"); } - enum MessageportCallbacks { MessagePortManagerRequesttrustedremotemessageportCallback, MessagePortManagerRequestlocalmessageportCallback, @@ -67,13 +66,14 @@ enum MessageportCallbacks { LocalMessagePortAddmessageportlistenerCallback }; -static void BundleJsonIterator(const char *key, const int type, const bundle_keyval_t *kv, void *d) { +static void BundleJsonIterator(const char* key, const int type, const bundle_keyval_t* kv, + void* d) { LoggerD("Enter"); - void *basic_val = nullptr; + void* basic_val = nullptr; size_t basic_size = 0; - picojson::value::array *array = static_cast(d); + picojson::value::array* array = static_cast(d); picojson::value::object o; switch (bundle_keyval_get_type(const_cast(kv))) { @@ -85,17 +85,15 @@ static void BundleJsonIterator(const char *key, const int type, const bundle_key case BUNDLE_TYPE_STR_ARRAY: { picojson::value::array tab; - void **array_val = nullptr; + void** array_val = nullptr; unsigned int array_len = 0; - size_t *array_elem_size = nullptr; + size_t* array_elem_size = nullptr; - bundle_keyval_get_array_val(const_cast(kv), - &array_val, - &array_len, + bundle_keyval_get_array_val(const_cast(kv), &array_val, &array_len, &array_elem_size); for (unsigned int i = 0; i < array_len; i++) { - tab.push_back(picojson::value(((char**) array_val)[i])); + tab.push_back(picojson::value(((char**)array_val)[i])); } o["key"] = picojson::value(key); @@ -107,14 +105,14 @@ static void BundleJsonIterator(const char *key, const int type, const bundle_key case BUNDLE_TYPE_BYTE: { picojson::value::array tab; - unsigned char *basic_val = nullptr; + unsigned char* basic_val = nullptr; size_t basic_size = 0; - bundle_keyval_get_basic_val(const_cast(kv), - (void **)&basic_val, &basic_size); + bundle_keyval_get_basic_val(const_cast(kv), (void**)&basic_val, + &basic_size); for (unsigned int i = 0; i < basic_size; i++) { - tab.push_back(picojson::value(static_cast (basic_val[i]))); + tab.push_back(picojson::value(static_cast(basic_val[i]))); } o["key"] = picojson::value(key); @@ -124,18 +122,17 @@ static void BundleJsonIterator(const char *key, const int type, const bundle_key case BUNDLE_TYPE_BYTE_ARRAY: { picojson::value::array tab; - unsigned char **array_value=nullptr; - size_t *array_ele_size=nullptr; - unsigned int ele_nos=0; + unsigned char** array_value = nullptr; + size_t* array_ele_size = nullptr; + unsigned int ele_nos = 0; - bundle_keyval_get_array_val(const_cast(kv), - (void ***)&array_value, &ele_nos, &array_ele_size); + bundle_keyval_get_array_val(const_cast(kv), (void***)&array_value, &ele_nos, + &array_ele_size); - for (unsigned int i=0;i (array_value[i][j]))); + tab2.push_back(picojson::value(static_cast(array_value[i][j]))); } tab.push_back(picojson::value(tab2)); } @@ -152,16 +149,15 @@ static void BundleJsonIterator(const char *key, const int type, const bundle_key array->push_back(picojson::value(o)); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } - -static void OnReceiveLocalMessage(int local_port_id, - const char* remote_app_id, const char* remote_port, - bool trusted_remote_port, bundle* message, void* user_data) { +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } +static void OnReceiveLocalMessage(int local_port_id, const char* remote_app_id, + const char* remote_port, bool trusted_remote_port, + bundle* message, void* user_data) { LoggerD("Enter"); MessageportInstance* object = static_cast(user_data); picojson::value::object o; @@ -185,22 +181,19 @@ static void OnReceiveLocalMessage(int local_port_id, common::Instance::PostMessage(object, picojson::value(o).serialize().c_str()); } - -void MessageportInstance::MessagePortManagerRequestlocalmessageport - (const picojson::value& args, picojson::object& out) { +void MessageportInstance::MessagePortManagerRequestlocalmessageport(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "localMessagePortName", out) int portId; - const std::string& localMessagePortName = - args.get("localMessagePortName").get(); + const std::string& localMessagePortName = args.get("localMessagePortName").get(); - portId = message_port_register_local_port - (localMessagePortName.c_str(), OnReceiveLocalMessage, this); + portId = + message_port_register_local_port(localMessagePortName.c_str(), OnReceiveLocalMessage, this); LoggerD("Registering local port %s : %s", localMessagePortName.c_str(), - portId < 0 ? "false" : "true"); - + portId < 0 ? "false" : "true"); if (portId < 0) { switch (portId) { @@ -224,133 +217,124 @@ void MessageportInstance::MessagePortManagerRequestlocalmessageport UnknownException("Unknown Exception"), out, ("message_port_register_local_port error: %d (%s)", portId, get_error_message(portId))); break; - } + } } else { ReportSuccess(picojson::value(static_cast(portId)), out); } } -void MessageportInstance:: - MessagePortManagerRequesttrustedlocalmessageport - (const picojson::value& args, picojson::object& out) { - +void MessageportInstance::MessagePortManagerRequesttrustedlocalmessageport( + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "localMessagePortName", out) int portId; - const std::string& localMessagePortName = - args.get("localMessagePortName").get(); + const std::string& localMessagePortName = args.get("localMessagePortName").get(); - portId = message_port_register_trusted_local_port - (localMessagePortName.c_str(), OnReceiveLocalMessage, this); + portId = message_port_register_trusted_local_port(localMessagePortName.c_str(), + OnReceiveLocalMessage, this); LoggerD("Registering trusted local port %s:%s", localMessagePortName.c_str(), - portId < 0 ? "false" : "true"); + portId < 0 ? "false" : "true"); if (portId < 0) { switch (portId) { case MESSAGE_PORT_ERROR_INVALID_PARAMETER: - LogAndReportError( - InvalidValuesException("The input parameter contains an invalid value."), out, - ("message_port_register_trusted_local_port error: %d (%s)", portId, get_error_message(portId))); + LogAndReportError(InvalidValuesException("The input parameter contains an invalid value."), + out, ("message_port_register_trusted_local_port error: %d (%s)", portId, + get_error_message(portId))); break; case MESSAGE_PORT_ERROR_OUT_OF_MEMORY: - LogAndReportError( - UnknownException("Out of memory."), out, - ("message_port_register_trusted_local_port error: %d (%s)", portId, get_error_message(portId))); + LogAndReportError(UnknownException("Out of memory."), out, + ("message_port_register_trusted_local_port error: %d (%s)", portId, + get_error_message(portId))); break; case MESSAGE_PORT_ERROR_IO_ERROR: - LogAndReportError( - UnknownException("Internal I/O error ocurred."), out, - ("message_port_register_trusted_local_port error: %d (%s)", portId, get_error_message(portId))); + LogAndReportError(UnknownException("Internal I/O error ocurred."), out, + ("message_port_register_trusted_local_port error: %d (%s)", portId, + get_error_message(portId))); break; default: - LogAndReportError( - UnknownException("Unknown Exception"), out, - ("message_port_register_trusted_local_port error: %d (%s)", portId, get_error_message(portId))); + LogAndReportError(UnknownException("Unknown Exception"), out, + ("message_port_register_trusted_local_port error: %d (%s)", portId, + get_error_message(portId))); break; - } + } } else { ReportSuccess(picojson::value(static_cast(portId)), out); } } -void MessageportInstance:: - MessagePortManagerRequestremotemessageport - (const picojson::value& args, picojson::object& out) { +void MessageportInstance::MessagePortManagerRequestremotemessageport(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "remoteMessagePortName", out) - const std::string& remoteMessagePortName = - args.get("remoteMessagePortName").get(); + const std::string& remoteMessagePortName = args.get("remoteMessagePortName").get(); const std::string& appId = args.get("appId").get(); int ret; bool portCheck; - ret = message_port_check_remote_port(appId.c_str(), - remoteMessagePortName.c_str(), &portCheck); + ret = message_port_check_remote_port(appId.c_str(), remoteMessagePortName.c_str(), &portCheck); LoggerD("Checking remote port of %s: %s", remoteMessagePortName.c_str(), - portCheck ? "true" : "false"); + portCheck ? "true" : "false"); LoggerD("Error code: %d (%s)", ret, get_error_message(ret)); if (ret == MESSAGE_PORT_ERROR_NONE) { - if (portCheck) { + if (portCheck) { ReportSuccess(out); } else { LogAndReportError(NotFoundException("The port of the target application is not found"), out); } } else if (ret == MESSAGE_PORT_ERROR_INVALID_PARAMETER) { LogAndReportError( - InvalidValuesException("An input parameter contains an invalid value."), out, - ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); + InvalidValuesException("An input parameter contains an invalid value."), out, + ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); } else if (ret == MESSAGE_PORT_ERROR_OUT_OF_MEMORY) { LogAndReportError( - UnknownException("Out of memory."), out, - ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); + UnknownException("Out of memory."), out, + ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); } else if (ret == MESSAGE_PORT_ERROR_IO_ERROR) { // IO error means that remote port does not exist LogAndReportError( - NotFoundException("The port of the target application is not found"), out, - ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); + NotFoundException("The port of the target application is not found"), out, + ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); } else if (ret == MESSAGE_PORT_ERROR_PORT_NOT_FOUND) { LogAndReportError( - NotFoundException("The port of the target application is not found"), out, - ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); + NotFoundException("The port of the target application is not found"), out, + ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); } else { LogAndReportError( - UnknownException("Unknown Error"), out, - ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); + UnknownException("Unknown Error"), out, + ("message_port_check_remote_port error: %d (%s)", ret, get_error_message(ret))); } } -void MessageportInstance:: - MessagePortManagerRequesttrustedremotemessageport - (const picojson::value& args, picojson::object& out) { +void MessageportInstance::MessagePortManagerRequesttrustedremotemessageport( + const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_EXIST(args, "remoteMessagePortName", out) - const std::string& remoteMessagePortName = - args.get("remoteMessagePortName").get(); + const std::string& remoteMessagePortName = args.get("remoteMessagePortName").get(); const std::string& appId = args.get("appId").get(); bool portCheck; int ret; - ret = message_port_check_trusted_remote_port - (appId.c_str(), remoteMessagePortName.c_str(), &portCheck); + ret = message_port_check_trusted_remote_port(appId.c_str(), remoteMessagePortName.c_str(), + &portCheck); - LoggerD("Checking trusted remote port of %s: %s", - remoteMessagePortName.c_str(), portCheck ? "true":"false"); + LoggerD("Checking trusted remote port of %s: %s", remoteMessagePortName.c_str(), + portCheck ? "true" : "false"); LoggerD("Error code: %d (%s)", ret, get_error_message(ret)); if (ret == MESSAGE_PORT_ERROR_NONE) { if (portCheck) { ReportSuccess(out); } else { - LogAndReportError( - NotFoundException("The port of the target application is not found"), out); + LogAndReportError(NotFoundException("The port of the target application is not found"), out); } } else if (ret == MESSAGE_PORT_ERROR_INVALID_PARAMETER) { LogAndReportError( @@ -380,28 +364,24 @@ void MessageportInstance:: } } -void MessageportInstance::RemoteMessagePortSendmessage - (const picojson::value& args, picojson::object& out) { +void MessageportInstance::RemoteMessagePortSendmessage(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); const std::string& appId = args.get("appId").get(); - const std::string& message_port_name = - args.get("messagePortName").get(); + const std::string& message_port_name = args.get("messagePortName").get(); std::vector data = args.get("data").get(); - long local_port_id = - static_cast(args.get("local_port_id").get()); + long local_port_id = static_cast(args.get("local_port_id").get()); bool trusted = args.get("trusted").get(); int result; bundle* bundle = bundle_create(); - for (picojson::value::array::iterator it = data.begin(); - it != data.end(); ++it) { + for (picojson::value::array::iterator it = data.begin(); it != data.end(); ++it) { const std::string& valueType = (*it).get("valueType").get(); if ("stringValueType" == valueType) { LoggerD("value is string"); - bundle_add(bundle, (*it).get("key").to_str().c_str(), - (*it).get("value").to_str().c_str()); + bundle_add(bundle, (*it).get("key").to_str().c_str(), (*it).get("value").to_str().c_str()); } else if ("stringArrayValueType" == valueType) { LoggerD("value is string array"); std::vector value_array = (*it).get("value").get(); @@ -444,33 +424,30 @@ void MessageportInstance::RemoteMessagePortSendmessage arr[j] = static_cast((*byteIter).get()); } - bundle_set_byte_array_element(bundle, (*it).get("key").to_str().c_str(), i, arr, streamSize); + bundle_set_byte_array_element(bundle, (*it).get("key").to_str().c_str(), i, arr, + streamSize); delete[] arr; } } } - LoggerD("%s to %s", trusted ? - "Sending trusted messages" : "Sending normal messages", - message_port_name.c_str()); + LoggerD("%s to %s", trusted ? "Sending trusted messages" : "Sending normal messages", + message_port_name.c_str()); if (trusted) { if (local_port_id < 0) { - result = message_port_send_trusted_message - (appId.c_str(), message_port_name.c_str(), bundle); - } else { - result = message_port_send_trusted_message_with_local_port - (appId.c_str(), message_port_name.c_str(), bundle, local_port_id); - } + result = message_port_send_trusted_message(appId.c_str(), message_port_name.c_str(), bundle); + } else { + result = message_port_send_trusted_message_with_local_port( + appId.c_str(), message_port_name.c_str(), bundle, local_port_id); + } } else { if (local_port_id < 0) { - result = message_port_send_message - (appId.c_str(), message_port_name.c_str(), bundle); - LoggerD("-----------%s & %s---------------", - appId.c_str(), message_port_name.c_str()); + result = message_port_send_message(appId.c_str(), message_port_name.c_str(), bundle); + LoggerD("-----------%s & %s---------------", appId.c_str(), message_port_name.c_str()); } else { - result = message_port_send_message_with_local_port - (appId.c_str(), message_port_name.c_str(), bundle, local_port_id); + result = message_port_send_message_with_local_port(appId.c_str(), message_port_name.c_str(), + bundle, local_port_id); } } @@ -479,47 +456,38 @@ void MessageportInstance::RemoteMessagePortSendmessage if (result == MESSAGE_PORT_ERROR_NONE) { ReportSuccess(out); } else if (result == MESSAGE_PORT_ERROR_INVALID_PARAMETER) { - LogAndReportError( - InvalidValuesException("An input parameter contains an invalid value."), out, - ("An input parameter contains an invalid value %d (%s)", - result, get_error_message(result))); + LogAndReportError(InvalidValuesException("An input parameter contains an invalid value."), out, + ("An input parameter contains an invalid value %d (%s)", result, + get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_PORT_NOT_FOUND) { - LogAndReportError( - NotFoundException("The port of the target application is not found"), out, - ("The port of the target application is not found: %d (%s)", - result, get_error_message(result))); + LogAndReportError(NotFoundException("The port of the target application is not found"), out, + ("The port of the target application is not found: %d (%s)", result, + get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_MAX_EXCEEDED) { - LogAndReportError( - QuotaExceededException("The size of message has exceeded the maximum limit."), out, - ("The size of message has exceeded the maximum limit: %d (%s)", - result, get_error_message(result))); + LogAndReportError(QuotaExceededException("The size of message has exceeded the maximum limit."), + out, ("The size of message has exceeded the maximum limit: %d (%s)", result, + get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_RESOURCE_UNAVAILABLE) { LogAndReportError( UnknownException("A resource is temporarily unavailable"), out, - ("A resource is temporarily unavailable: %d (%s)", - result, get_error_message(result))); + ("A resource is temporarily unavailable: %d (%s)", result, get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_OUT_OF_MEMORY) { - LogAndReportError( - UnknownException("Out of memory."), out, - ("Out of memory: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException("Out of memory."), out, + ("Out of memory: %d (%s)", result, get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_IO_ERROR) { - LogAndReportError( - UnknownException("Internal I/O error ocurred."), out, - ("Internal I/O error ocurred: %d (%s)", - result, get_error_message(result))); + LogAndReportError(UnknownException("Internal I/O error ocurred."), out, + ("Internal I/O error ocurred: %d (%s)", result, get_error_message(result))); } else if (result == MESSAGE_PORT_ERROR_CERTIFICATE_NOT_MATCH) { LogAndReportError( - UnknownException("The remote application is not signed with the same certificate") , out, - ("The remote application is not signed with the same certificate: %d (%s)", - result, get_error_message(result))); + UnknownException("The remote application is not signed with the same certificate"), out, + ("The remote application is not signed with the same certificate: %d (%s)", result, + get_error_message(result))); } else { - LogAndReportError( - UnknownException("Unknown Exception"), out, - ("Unknown Exception: %d (%s)", result, get_error_message(result))); + LogAndReportError(UnknownException("Unknown Exception"), out, + ("Unknown Exception: %d (%s)", result, get_error_message(result))); } } - #undef CHECK_EXIST } // namespace messageport diff --git a/src/messageport/messageport_instance.h b/src/messageport/messageport_instance.h old mode 100755 new mode 100644 index c4458d2..9e711f6 --- a/src/messageport/messageport_instance.h +++ b/src/messageport/messageport_instance.h @@ -32,16 +32,15 @@ class MessageportInstance : public common::ParsedInstance { virtual ~MessageportInstance(); private: - void MessagePortManagerRequestlocalmessageport - (const picojson::value& args, picojson::object& out); - void MessagePortManagerRequesttrustedlocalmessageport - (const picojson::value& args, picojson::object& out); - void MessagePortManagerRequestremotemessageport - (const picojson::value& args, picojson::object& out); - void MessagePortManagerRequesttrustedremotemessageport - (const picojson::value& args, picojson::object& out); - void RemoteMessagePortSendmessage - (const picojson::value& args, picojson::object& out); + void MessagePortManagerRequestlocalmessageport(const picojson::value& args, + picojson::object& out); + void MessagePortManagerRequesttrustedlocalmessageport(const picojson::value& args, + picojson::object& out); + void MessagePortManagerRequestremotemessageport(const picojson::value& args, + picojson::object& out); + void MessagePortManagerRequesttrustedremotemessageport(const picojson::value& args, + picojson::object& out); + void RemoteMessagePortSendmessage(const picojson::value& args, picojson::object& out); }; } // namespace messageport diff --git a/src/messaging/DBus/DBusTypes.cpp b/src/messaging/DBus/DBusTypes.cpp index 1a6489d..5b7ec4e 100644 --- a/src/messaging/DBus/DBusTypes.cpp +++ b/src/messaging/DBus/DBusTypes.cpp @@ -27,6 +27,6 @@ const char* kDBusPathEmailStorageChange = "/User/Email/StorageChange"; const char* kDBusIfaceEmailStorageChange = "User.Email.StorageChange"; const char* kDBusNameSignalEmail = "email"; -} // namespace DBus -} // namespace messaging -} // namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension diff --git a/src/messaging/DBus/DBusTypes.h b/src/messaging/DBus/DBusTypes.h index 0c9c56f..6aade56 100644 --- a/src/messaging/DBus/DBusTypes.h +++ b/src/messaging/DBus/DBusTypes.h @@ -31,6 +31,6 @@ extern const char* kDBusIfaceEmailStorageChange; */ extern const char* kDBusNameSignalEmail; -} // namespace DBus -} // namespace messaging -} // namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension diff --git a/src/messaging/DBus/EmailSignalProxy.cpp b/src/messaging/DBus/EmailSignalProxy.cpp index f00a37d..9c6b216 100644 --- a/src/messaging/DBus/EmailSignalProxy.cpp +++ b/src/messaging/DBus/EmailSignalProxy.cpp @@ -20,58 +20,43 @@ */ #include "EmailSignalProxy.h" -#include "common/logger.h" #include +#include "common/logger.h" #include "messaging/DBus/DBusTypes.h" namespace extension { namespace messaging { namespace DBus { -EmailSignalProxy::EmailSignalProxy(const std::string& proxy_path, - const std::string& proxy_iface) : - common::dbus::Proxy (proxy_path, - proxy_iface, - kDBusNameSignalEmail, //specify email signal details - kDBusPathNetworkStatus, - kDBusIfaceNetworkStatus) -{ +EmailSignalProxy::EmailSignalProxy(const std::string& proxy_path, const std::string& proxy_iface) + : common::dbus::Proxy(proxy_path, proxy_iface, + kDBusNameSignalEmail, // specify email signal details + kDBusPathNetworkStatus, kDBusIfaceNetworkStatus) { } -EmailSignalProxy::~EmailSignalProxy() -{ - +EmailSignalProxy::~EmailSignalProxy() { } -void EmailSignalProxy::signalCallback(GDBusConnection* connection, - const gchar* sender_name, - const gchar* object_path, - const gchar* interface_name, - const gchar* signal_name, - GVariant* parameters) -{ - int status, mail_id, op_handle, error_code; - char* source = NULL; +void EmailSignalProxy::signalCallback(GDBusConnection* connection, const gchar* sender_name, + const gchar* object_path, const gchar* interface_name, + const gchar* signal_name, GVariant* parameters) { + int status, mail_id, op_handle, error_code; + char* source = NULL; - g_variant_get(parameters, "(iisii)", - &status, - &mail_id, - &source, - &op_handle, - &error_code); + g_variant_get(parameters, "(iisii)", &status, &mail_id, &source, &op_handle, &error_code); - //It is better to log this only when subclass is responsible of handling - //passed signal (usually determined by status value). - // - //LoggerD("email:\n status: %d\n mail_id: %d\n " - // "source: %s\n op_handle: %d\n error_code: %d", - // status, mail_id, source, op_handle, error_code); + // It is better to log this only when subclass is responsible of handling + // passed signal (usually determined by status value). + // + // LoggerD("email:\n status: %d\n mail_id: %d\n " + // "source: %s\n op_handle: %d\n error_code: %d", + // status, mail_id, source, op_handle, error_code); - handleEmailSignal(status, mail_id, source, op_handle, error_code); + handleEmailSignal(status, mail_id, source, op_handle, error_code); - g_free(source); + g_free(source); } -} //namespace DBus -} //namespace Messaging -} //namespace DeviceAPI +} // namespace DBus +} // namespace Messaging +} // namespace DeviceAPI diff --git a/src/messaging/DBus/EmailSignalProxy.h b/src/messaging/DBus/EmailSignalProxy.h index 01687a1..71dc91f 100644 --- a/src/messaging/DBus/EmailSignalProxy.h +++ b/src/messaging/DBus/EmailSignalProxy.h @@ -32,34 +32,27 @@ class EmailSignalProxy; typedef std::shared_ptr EmailSignalProxyPtr; class EmailSignalProxy : public common::dbus::Proxy { -public: - virtual ~EmailSignalProxy(); + public: + virtual ~EmailSignalProxy(); -protected: - EmailSignalProxy(const std::string& proxy_path, - const std::string& proxy_iface); + protected: + EmailSignalProxy(const std::string &proxy_path, const std::string &proxy_iface); - /** - * Override this method in subclass to handle email signal - */ - virtual void handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code) = 0; + /** + * Override this method in subclass to handle email signal + */ + virtual void handleEmailSignal(const int status, const int mail_id, const std::string &source, + const int op_handle, const int error_code) = 0; - virtual void signalCallback(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters); + virtual void signalCallback(GDBusConnection *connection, const gchar *sender_name, + const gchar *object_path, const gchar *interface_name, + const gchar *signal_name, GVariant *parameters); -private: + private: }; -} //namespace DBus -} //namespace Messaging -} //namespace DeviceAPI +} // namespace DBus +} // namespace Messaging +} // namespace DeviceAPI -#endif // __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__ +#endif // __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__ diff --git a/src/messaging/DBus/LoadAttachmentProxy.cpp b/src/messaging/DBus/LoadAttachmentProxy.cpp index e6fa2db..97dea32 100644 --- a/src/messaging/DBus/LoadAttachmentProxy.cpp +++ b/src/messaging/DBus/LoadAttachmentProxy.cpp @@ -24,12 +24,12 @@ #include "common/logger.h" #include "common/platform_result.h" -#include #include -#include "../message_service.h" +#include +#include "../email_manager.h" #include "../message.h" #include "../message_body.h" -#include "../email_manager.h" +#include "../message_service.h" #include @@ -44,190 +44,177 @@ using namespace common; * visible outside LoadAttachmentProxy class. */ PlatformResult updateAttachmentDataWithEmailGetAttachmentData( - std::shared_ptr attachment) -{ - struct ScopedEmailAttachmentData { - ScopedEmailAttachmentData() : data(NULL) { } - ~ScopedEmailAttachmentData() { - if(data) { - email_free_attachment_data(&data, 1); - } - } - email_attachment_data_t* operator->() { return data; } - email_attachment_data_t* data; - } attachment_data_holder; - - LoggerD("attachmentId = %d", attachment->getId()); - - /* - * WARNING: email_get_attachment_data seems to be getting NOT COMPLETE - * email_attachment_data_t object, observed that: - * mail_id is 0 - * account_id is 0 - * mailbox_id is 0 - * Thus currently only attachment_path and attachment_mime_type is used! - * - * To get COMPLETE data please use: Message::convertEmailToMessageAttachment - * mtehod which fetches all attachments from specified email. - */ - int err = email_get_attachment_data(attachment->getId(), &attachment_data_holder.data); - if (EMAIL_ERROR_NONE != err || - NULL == attachment_data_holder.data) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't get attachment.", - ("Couldn't get attachment data for attachmentId:%d", attachment->getId())); + std::shared_ptr attachment) { + struct ScopedEmailAttachmentData { + ScopedEmailAttachmentData() : data(NULL) { } - - LoggerD("attachment name : %s", attachment_data_holder->attachment_name); - - if(attachment_data_holder->attachment_mime_type) { - attachment->setMimeType(attachment_data_holder->attachment_mime_type); + ~ScopedEmailAttachmentData() { + if (data) { + email_free_attachment_data(&data, 1); + } } - - bool isSaved = false; - if (attachment_data_holder->attachment_path) { - LoggerD("set attachment path: %s", attachment_data_holder->attachment_path); - attachment->setFilePath(attachment_data_holder->attachment_path); - - LoggerD("save_status: %d", attachment_data_holder->save_status); - LoggerD("attachment_size : %d", attachment_data_holder->attachment_size); + email_attachment_data_t* operator->() { + return data; } - isSaved = attachment_data_holder->save_status; - attachment->setIsSaved(isSaved); - return PlatformResult(ErrorCode::NO_ERROR); + email_attachment_data_t* data; + } attachment_data_holder; + + LoggerD("attachmentId = %d", attachment->getId()); + + /* + * WARNING: email_get_attachment_data seems to be getting NOT COMPLETE + * email_attachment_data_t object, observed that: + * mail_id is 0 + * account_id is 0 + * mailbox_id is 0 + * Thus currently only attachment_path and attachment_mime_type is used! + * + * To get COMPLETE data please use: Message::convertEmailToMessageAttachment + * mtehod which fetches all attachments from specified email. + */ + int err = email_get_attachment_data(attachment->getId(), &attachment_data_holder.data); + if (EMAIL_ERROR_NONE != err || NULL == attachment_data_holder.data) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Couldn't get attachment.", + ("Couldn't get attachment data for attachmentId:%d", attachment->getId())); + } + + LoggerD("attachment name : %s", attachment_data_holder->attachment_name); + + if (attachment_data_holder->attachment_mime_type) { + attachment->setMimeType(attachment_data_holder->attachment_mime_type); + } + + bool isSaved = false; + if (attachment_data_holder->attachment_path) { + LoggerD("set attachment path: %s", attachment_data_holder->attachment_path); + attachment->setFilePath(attachment_data_holder->attachment_path); + + LoggerD("save_status: %d", attachment_data_holder->save_status); + LoggerD("attachment_size : %d", attachment_data_holder->attachment_size); + } + isSaved = attachment_data_holder->save_status; + attachment->setIsSaved(isSaved); + return PlatformResult(ErrorCode::NO_ERROR); } -LoadAttachmentProxy::LoadAttachmentProxy(const std::string& path, - const std::string& iface) : - EmailSignalProxy(path, iface) -{ +LoadAttachmentProxy::LoadAttachmentProxy(const std::string& path, const std::string& iface) + : EmailSignalProxy(path, iface) { } -LoadAttachmentProxy::~LoadAttachmentProxy() -{ +LoadAttachmentProxy::~LoadAttachmentProxy() { } -PlatformResult LoadAttachmentProxy::create(const std::string& path, - const std::string& iface, +PlatformResult LoadAttachmentProxy::create(const std::string& path, const std::string& iface, LoadAttachmentProxyPtr* load_attachment_proxy) { - load_attachment_proxy->reset(new LoadAttachmentProxy(path, iface)); - if ((*load_attachment_proxy)->isNotProxyGot()) { - load_attachment_proxy->reset(); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get load attachment proxy"); - } else { - return PlatformResult(ErrorCode::NO_ERROR); - } + load_attachment_proxy->reset(new LoadAttachmentProxy(path, iface)); + if ((*load_attachment_proxy)->isNotProxyGot()) { + load_attachment_proxy->reset(); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get load attachment proxy"); + } else { + return PlatformResult(ErrorCode::NO_ERROR); + } } -void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwned) -{ - if(callbackOwned->getMessageAttachment()) { - LoggerD("Registered callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", +void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwned) { + if (callbackOwned->getMessageAttachment()) { + LoggerD("Registered callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", callbackOwned->getMessageAttachment()->getId(), callbackOwned->getMessageAttachment()->getMessageId(), - callbackOwned->getOperationHandle(), - callbackOwned->getNth()); - } + callbackOwned->getOperationHandle(), callbackOwned->getNth()); + } - m_callback_set.insert(callbackOwned); + m_callback_set.insert(callbackOwned); } -void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback) -{ - if(callback->getMessageAttachment()) { - LoggerD("Removed callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", +void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback) { + if (callback->getMessageAttachment()) { + LoggerD("Removed callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", callback->getMessageAttachment()->getId(), - callback->getMessageAttachment()->getMessageId(), - callback->getOperationHandle(), + callback->getMessageAttachment()->getMessageId(), callback->getOperationHandle(), callback->getNth()); - } + } - m_callback_set.erase(callback); + m_callback_set.erase(callback); } -MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth, - const int mail_id) -{ - CallbackSet::iterator it = m_callback_set.begin(); - for (; it != m_callback_set.end(); ++it) { - MessageAttachmentCallbackData* callback = *it; - if (nth == callback->getNth() && - mail_id == callback->getMessageAttachment()->getMessageId()) { - return callback; - } +MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth, const int mail_id) { + CallbackSet::iterator it = m_callback_set.begin(); + for (; it != m_callback_set.end(); ++it) { + MessageAttachmentCallbackData* callback = *it; + if (nth == callback->getNth() && mail_id == callback->getMessageAttachment()->getMessageId()) { + return callback; } + } - LoggerW("Could not find callback with nth: %d and mail_id: %d", nth, mail_id); - return NULL; + LoggerW("Could not find callback with nth: %d and mail_id: %d", nth, mail_id); + return NULL; } -void LoadAttachmentProxy::handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code) -{ - if(NOTI_DOWNLOAD_ATTACH_FINISH != status && - NOTI_DOWNLOAD_ATTACH_FAIL != status) { - return; - } - - LoggerD("received email signal with:\n status: %d\n mail_id: %d\n " - "source: %s\n op_handle(nth): %d\n error_code: %d", - status, mail_id, source.c_str(), op_handle, error_code); - - MessageAttachmentCallbackData* callback = NULL; - - //It seems that D-Bus signal op_handle is equal to nth in: - // int email_download_attachment(int mail_id, int nth, int *handle) - // and not handle returned from above call!! - const int nth = op_handle; - - // From old implementation it looks that op_handle(nth) is is equal to - // index (1 based) of attachment inside email thus it is not globally unique! - // Therfore we need to test if mail_id match. - // For details see old implementation MailSync.cp line 461 - - callback = findCallback(nth, mail_id); - if(!callback) { - //We should not log not found pair since it could be requested by - //different application. - return; - } - - LoggerD("Found callback for pair mailId:%d nth:%d", mail_id, nth); - - PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - if (NOTI_DOWNLOAD_ATTACH_FINISH == status) { - LoggerD("Message attachment downloaded!"); - - std::shared_ptr att = callback->getMessageAttachment(); - ret = updateAttachmentDataWithEmailGetAttachmentData(att); - if (!ret.IsError()) { - LoggerD("Updated Message attachment object"); - - picojson::object args; - args[JSON_DATA_MESSAGE_ATTACHMENT] = MessagingUtil::messageAttachmentToJson( - callback->getMessageAttachment()); - - callback->SetSuccess(picojson::value(args)); - callback->Post(); - } - } else if (NOTI_DOWNLOAD_ATTACH_FAIL == status) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load message attachment failed!"); - } - if (ret.IsError()) { - LoggerE("Exception in signal callback"); - callback->SetError(ret); - callback->Post(); - } - - if(callback) { - removeCallback(callback); - delete callback; +void LoadAttachmentProxy::handleEmailSignal(const int status, const int mail_id, + const std::string& source, const int op_handle, + const int error_code) { + if (NOTI_DOWNLOAD_ATTACH_FINISH != status && NOTI_DOWNLOAD_ATTACH_FAIL != status) { + return; + } + + LoggerD( + "received email signal with:\n status: %d\n mail_id: %d\n " + "source: %s\n op_handle(nth): %d\n error_code: %d", + status, mail_id, source.c_str(), op_handle, error_code); + + MessageAttachmentCallbackData* callback = NULL; + + // It seems that D-Bus signal op_handle is equal to nth in: + // int email_download_attachment(int mail_id, int nth, int *handle) + // and not handle returned from above call!! + const int nth = op_handle; + + // From old implementation it looks that op_handle(nth) is is equal to + // index (1 based) of attachment inside email thus it is not globally unique! + // Therfore we need to test if mail_id match. + // For details see old implementation MailSync.cp line 461 + + callback = findCallback(nth, mail_id); + if (!callback) { + // We should not log not found pair since it could be requested by + // different application. + return; + } + + LoggerD("Found callback for pair mailId:%d nth:%d", mail_id, nth); + + PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); + if (NOTI_DOWNLOAD_ATTACH_FINISH == status) { + LoggerD("Message attachment downloaded!"); + + std::shared_ptr att = callback->getMessageAttachment(); + ret = updateAttachmentDataWithEmailGetAttachmentData(att); + if (!ret.IsError()) { + LoggerD("Updated Message attachment object"); + + picojson::object args; + args[JSON_DATA_MESSAGE_ATTACHMENT] = + MessagingUtil::messageAttachmentToJson(callback->getMessageAttachment()); + + callback->SetSuccess(picojson::value(args)); + callback->Post(); } + } else if (NOTI_DOWNLOAD_ATTACH_FAIL == status) { + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load message attachment failed!"); + } + if (ret.IsError()) { + LoggerE("Exception in signal callback"); + callback->SetError(ret); + callback->Post(); + } + + if (callback) { + removeCallback(callback); + delete callback; + } } -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension diff --git a/src/messaging/DBus/LoadAttachmentProxy.h b/src/messaging/DBus/LoadAttachmentProxy.h index 9a163c1..5b3e750 100644 --- a/src/messaging/DBus/LoadAttachmentProxy.h +++ b/src/messaging/DBus/LoadAttachmentProxy.h @@ -22,9 +22,9 @@ #ifndef __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__ #define __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__ -#include "common/platform_result.h" -#include "EmailSignalProxy.h" #include +#include "EmailSignalProxy.h" +#include "common/platform_result.h" namespace extension { namespace messaging { @@ -37,37 +37,31 @@ class LoadAttachmentProxy; typedef std::shared_ptr LoadAttachmentProxyPtr; class LoadAttachmentProxy : public EmailSignalProxy { -public: - - // Callback is owned by this set - typedef std::set CallbackSet; + public: + // Callback is owned by this set + typedef std::set CallbackSet; - virtual ~LoadAttachmentProxy(); - static common::PlatformResult create(const std::string& path, - const std::string& iface, - LoadAttachmentProxyPtr* load_attachment_proxy); + virtual ~LoadAttachmentProxy(); + static common::PlatformResult create(const std::string& path, const std::string& iface, + LoadAttachmentProxyPtr* load_attachment_proxy); - //Passed callback will be owned by this proxy - void addCallback(MessageAttachmentCallbackData* callbackOwned); - void removeCallback(MessageAttachmentCallbackData* callback); + // Passed callback will be owned by this proxy + void addCallback(MessageAttachmentCallbackData* callbackOwned); + void removeCallback(MessageAttachmentCallbackData* callback); -protected: - LoadAttachmentProxy(const std::string& path, - const std::string& iface); - virtual void handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code); + protected: + LoadAttachmentProxy(const std::string& path, const std::string& iface); + virtual void handleEmailSignal(const int status, const int mail_id, const std::string& source, + const int op_handle, const int error_code); -private: - MessageAttachmentCallbackData* findCallback(const int nth, const int mail_id); + private: + MessageAttachmentCallbackData* findCallback(const int nth, const int mail_id); - CallbackSet m_callback_set; + CallbackSet m_callback_set; }; -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension -#endif // __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__ +#endif // __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__ diff --git a/src/messaging/DBus/LoadBodyProxy.cpp b/src/messaging/DBus/LoadBodyProxy.cpp index 5b64e02..944614a 100644 --- a/src/messaging/DBus/LoadBodyProxy.cpp +++ b/src/messaging/DBus/LoadBodyProxy.cpp @@ -33,13 +33,13 @@ //#include "JSMessage.h" //#include -#include "common/logger.h" #include +#include "common/logger.h" #include "common/platform_result.h" +#include "../email_manager.h" #include "../message.h" #include "../message_body.h" -#include "../email_manager.h" namespace extension { namespace messaging { @@ -47,145 +47,133 @@ namespace DBus { using namespace common; -LoadBodyProxy::LoadBodyProxy(const std::string& path, - const std::string& iface) : - EmailSignalProxy(path, iface) -{ +LoadBodyProxy::LoadBodyProxy(const std::string& path, const std::string& iface) + : EmailSignalProxy(path, iface) { } -LoadBodyProxy::~LoadBodyProxy() -{ +LoadBodyProxy::~LoadBodyProxy() { } -PlatformResult LoadBodyProxy::create(const std::string& path, - const std::string& iface, +PlatformResult LoadBodyProxy::create(const std::string& path, const std::string& iface, LoadBodyProxyPtr* load_body_proxy) { - load_body_proxy->reset(new LoadBodyProxy(path, iface)); - if ((*load_body_proxy)->isNotProxyGot()) { - load_body_proxy->reset(); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get load body proxy"); - } else { - return PlatformResult(ErrorCode::NO_ERROR); - } + load_body_proxy->reset(new LoadBodyProxy(path, iface)); + if ((*load_body_proxy)->isNotProxyGot()) { + load_body_proxy->reset(); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get load body proxy"); + } else { + return PlatformResult(ErrorCode::NO_ERROR); + } } -void LoadBodyProxy::addCallback(MessageBodyCallbackData* callbackOwned) -{ - m_callback_set.insert(callbackOwned); +void LoadBodyProxy::addCallback(MessageBodyCallbackData* callbackOwned) { + m_callback_set.insert(callbackOwned); } -void LoadBodyProxy::removeCallback(MessageBodyCallbackData* callback) -{ - m_callback_set.erase(callback); +void LoadBodyProxy::removeCallback(MessageBodyCallbackData* callback) { + m_callback_set.erase(callback); } -MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_handle) -{ - CallbackSet::iterator it = m_callback_set.begin(); - for (; it != m_callback_set.end(); ++it) { - - MessageBodyCallbackData* callback = *it; - if (op_handle == callback->getOperationHandle()) { - return callback; - } +MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_handle) { + CallbackSet::iterator it = m_callback_set.begin(); + for (; it != m_callback_set.end(); ++it) { + MessageBodyCallbackData* callback = *it; + if (op_handle == callback->getOperationHandle()) { + return callback; } + } - LoggerW("Could not find callback with op_handle: %d", op_handle); - return NULL; + LoggerW("Could not find callback with op_handle: %d", op_handle); + return NULL; } -void LoadBodyProxy::handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code) -{ - switch(status) { - //We should handle this signal since it is DOWNLOAD_BODY_* - case NOTI_DOWNLOAD_BODY_START: - case NOTI_DOWNLOAD_BODY_FINISH: - case NOTI_DOWNLOAD_BODY_FAIL: { - } break; - - // This values have not been explicitly handled in old implementation - // NOTI_DOWNLOAD_BODY_CANCEL - // NOTI_DOWNLOAD_MULTIPART_BODY - // - // 1. I assume that NOTI_DOWNLOAD_MULTIPART_BODY is called several times - // before final NOTI_DOWNLOAD_BODY_FINISH is called, thus we should not - // remove nor delete callback. - // - // 2. I assume that NOTI_DOWNLOAD_BODY_CANCEL is called before - // NOTI_DOWNLOAD_BODY_FAIL so we should do the same as in point 1. - case NOTI_DOWNLOAD_BODY_CANCEL: - case NOTI_DOWNLOAD_MULTIPART_BODY: - default: { - // This signal is not related with load message body or there is nothing - // to do so we can return now. - return; - } break; - } - - LoggerD("received email signal with:\n status: %d\n mail_id: %d\n " - "source: %s\n op_handle: %d\n error_code: %d", - status, mail_id, source.c_str(), op_handle, error_code); +void LoadBodyProxy::handleEmailSignal(const int status, const int mail_id, + const std::string& source, const int op_handle, + const int error_code) { + switch (status) { + // We should handle this signal since it is DOWNLOAD_BODY_* + case NOTI_DOWNLOAD_BODY_START: + case NOTI_DOWNLOAD_BODY_FINISH: + case NOTI_DOWNLOAD_BODY_FAIL: { + } break; + + // This values have not been explicitly handled in old implementation + // NOTI_DOWNLOAD_BODY_CANCEL + // NOTI_DOWNLOAD_MULTIPART_BODY + // + // 1. I assume that NOTI_DOWNLOAD_MULTIPART_BODY is called several times + // before final NOTI_DOWNLOAD_BODY_FINISH is called, thus we should not + // remove nor delete callback. + // + // 2. I assume that NOTI_DOWNLOAD_BODY_CANCEL is called before + // NOTI_DOWNLOAD_BODY_FAIL so we should do the same as in point 1. + case NOTI_DOWNLOAD_BODY_CANCEL: + case NOTI_DOWNLOAD_MULTIPART_BODY: + default: { + // This signal is not related with load message body or there is nothing + // to do so we can return now. + return; + } break; + } + + LoggerD( + "received email signal with:\n status: %d\n mail_id: %d\n " + "source: %s\n op_handle: %d\n error_code: %d", + status, mail_id, source.c_str(), op_handle, error_code); + + if (NOTI_DOWNLOAD_BODY_START == status) { + LoggerD("Download message body started ..."); + // There is nothing more to do so we can return now. + return; + } + + MessageBodyCallbackData* callback = NULL; + + callback = findCallbackByOpHandle(op_handle); + if (!callback) { + LoggerE("Callback is null"); + } else { + PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); + if ((NOTI_DOWNLOAD_BODY_FINISH == status) || + (NOTI_DOWNLOAD_BODY_FAIL == status && + EMAIL_ERROR_MAIL_IS_ALREADY_DOWNLOADED == error_code)) { + // Old implementation is not verifying whether message update failed, + // it just calls success callback. + if (callback->getMessage()) { + email_mail_data_t* mail_data = EmailManager::loadMessage(callback->getMessage()->getId()); + if (mail_data) { + // attachments are updated indirectly by updateEmailMessage() + ret = callback->getMessage()->updateEmailMessage(*mail_data); + if (!ret.IsError()) { + EmailManager::freeMessage(mail_data); + mail_data = NULL; + } + } + } - if(NOTI_DOWNLOAD_BODY_START == status) { - LoggerD("Download message body started ..."); - // There is nothing more to do so we can return now. - return; - } + if (!ret.IsError()) { + LoggerD("Calling success callback"); - MessageBodyCallbackData* callback = NULL; - - callback = findCallbackByOpHandle(op_handle); - if (!callback) { - LoggerE("Callback is null"); - } else { - PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - if( (NOTI_DOWNLOAD_BODY_FINISH == status) || - (NOTI_DOWNLOAD_BODY_FAIL == status && - EMAIL_ERROR_MAIL_IS_ALREADY_DOWNLOADED == error_code)) { - - // Old implementation is not verifying whether message update failed, - // it just calls success callback. - if(callback->getMessage()) { - email_mail_data_t* mail_data = EmailManager::loadMessage( - callback->getMessage()->getId()); - if (mail_data) { - //attachments are updated indirectly by updateEmailMessage() - ret = callback->getMessage()->updateEmailMessage(*mail_data); - if (!ret.IsError()) { - EmailManager::freeMessage(mail_data); - mail_data = NULL; - } - } - } - - if (!ret.IsError()) { - LoggerD("Calling success callback"); - - picojson::object args; - args[JSON_DATA_MESSAGE_BODY] = MessagingUtil::messageBodyToJson( - callback->getMessage()->getBody()); - - callback->SetSuccess(picojson::value(args)); - callback->Post(); - } - } else if(NOTI_DOWNLOAD_BODY_FAIL == status) { - ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load message body failed!"); - } + picojson::object args; + args[JSON_DATA_MESSAGE_BODY] = + MessagingUtil::messageBodyToJson(callback->getMessage()->getBody()); - if (ret.IsError()) { - callback->SetError(ret); - callback->Post(); - } + callback->SetSuccess(picojson::value(args)); + callback->Post(); + } + } else if (NOTI_DOWNLOAD_BODY_FAIL == status) { + ret = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load message body failed!"); + } - removeCallback(callback); - delete callback; + if (ret.IsError()) { + callback->SetError(ret); + callback->Post(); } + + removeCallback(callback); + delete callback; + } } -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension diff --git a/src/messaging/DBus/LoadBodyProxy.h b/src/messaging/DBus/LoadBodyProxy.h index 69f29c3..4f6309d 100644 --- a/src/messaging/DBus/LoadBodyProxy.h +++ b/src/messaging/DBus/LoadBodyProxy.h @@ -22,9 +22,9 @@ #ifndef __TIZEN_DBUS_LOAD_BODY_PROXY_H__ #define __TIZEN_DBUS_LOAD_BODY_PROXY_H__ -#include "common/platform_result.h" -#include "EmailSignalProxy.h" #include +#include "EmailSignalProxy.h" +#include "common/platform_result.h" namespace extension { namespace messaging { @@ -37,41 +37,35 @@ class LoadBodyProxy; typedef std::shared_ptr LoadBodyProxyPtr; class LoadBodyProxy : public EmailSignalProxy { -public: - - // Callback is owned by this set - typedef std::set CallbackSet; - - virtual ~LoadBodyProxy(); - - static common::PlatformResult create(const std::string& path, - const std::string& iface, - LoadBodyProxyPtr* load_body_proxy); - //Passed callback will be owned by this proxy - void addCallback(MessageBodyCallbackData* callbackOwned); - void removeCallback(MessageBodyCallbackData* callback); - -protected: - LoadBodyProxy(const std::string& path, - const std::string& iface); - virtual void handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code); - -private: - /** - * Find callback by operation handle returned from: - * int email_download_body(..., int *handle); - */ - MessageBodyCallbackData* findCallbackByOpHandle(const int op_handle); - - CallbackSet m_callback_set; + public: + // Callback is owned by this set + typedef std::set CallbackSet; + + virtual ~LoadBodyProxy(); + + static common::PlatformResult create(const std::string& path, const std::string& iface, + LoadBodyProxyPtr* load_body_proxy); + // Passed callback will be owned by this proxy + void addCallback(MessageBodyCallbackData* callbackOwned); + void removeCallback(MessageBodyCallbackData* callback); + + protected: + LoadBodyProxy(const std::string& path, const std::string& iface); + virtual void handleEmailSignal(const int status, const int mail_id, const std::string& source, + const int op_handle, const int error_code); + + private: + /** + * Find callback by operation handle returned from: + * int email_download_body(..., int *handle); + */ + MessageBodyCallbackData* findCallbackByOpHandle(const int op_handle); + + CallbackSet m_callback_set; }; -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension -#endif // __TIZEN_DBUS_LOAD_BODY_PROXY_H__ +#endif // __TIZEN_DBUS_LOAD_BODY_PROXY_H__ diff --git a/src/messaging/DBus/MessageProxy.cpp b/src/messaging/DBus/MessageProxy.cpp index b71e712..cd3a7d1 100644 --- a/src/messaging/DBus/MessageProxy.cpp +++ b/src/messaging/DBus/MessageProxy.cpp @@ -16,10 +16,10 @@ // #include "MessageProxy.h" -#include "common/logger.h" #include "../message.h" -#include "../message_email.h" #include "../message_conversation.h" +#include "../message_email.h" +#include "common/logger.h" //#include #include "../change_listener_container.h" #include "../email_manager.h" @@ -31,287 +31,265 @@ namespace DBus { using namespace common; -MessageProxy::MessageProxy(): - common::dbus::Proxy(kDBusPathEmailStorageChange, - kDBusIfaceEmailStorageChange, - kDBusNameSignalEmail, - kDBusPathEmailStorageChange, - kDBusIfaceEmailStorageChange) -{ +MessageProxy::MessageProxy() + : common::dbus::Proxy(kDBusPathEmailStorageChange, kDBusIfaceEmailStorageChange, + kDBusNameSignalEmail, kDBusPathEmailStorageChange, + kDBusIfaceEmailStorageChange) { } -MessageProxy::~MessageProxy() -{ +MessageProxy::~MessageProxy() { } PlatformResult MessageProxy::create(MessageProxyPtr* message_proxy) { - message_proxy->reset(new MessageProxy()); - if ((*message_proxy)->isNotProxyGot()) { - message_proxy->reset(); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get proxy"); - } else { - return PlatformResult(ErrorCode::NO_ERROR); - } + message_proxy->reset(new MessageProxy()); + if ((*message_proxy)->isNotProxyGot()) { + message_proxy->reset(); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get proxy"); + } else { + return PlatformResult(ErrorCode::NO_ERROR); + } } -void MessageProxy::signalCallback(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters) -{ - LoggerD("Enter"); - int status, account_id, object_id, thread_id; - char* name; - g_variant_get(parameters, "(iiisi)", - &status, - &account_id, - &object_id, - &name, - &thread_id); - LoggerD("status: %d", status); - LoggerD("account_id: %d", account_id); - LoggerD("object_id: %d", object_id); - LoggerD("name: %s", name); - LoggerD("thread_id: %d", thread_id); +void MessageProxy::signalCallback(GDBusConnection* connection, const gchar* sender_name, + const gchar* object_path, const gchar* interface_name, + const gchar* signal_name, GVariant* parameters) { + LoggerD("Enter"); + int status, account_id, object_id, thread_id; + char* name; + g_variant_get(parameters, "(iiisi)", &status, &account_id, &object_id, &name, &thread_id); + LoggerD("status: %d", status); + LoggerD("account_id: %d", account_id); + LoggerD("object_id: %d", object_id); + LoggerD("name: %s", name); + LoggerD("thread_id: %d", thread_id); - PlatformResult ret(ErrorCode::NO_ERROR); - switch (status) { - case NOTI_MAIL_ADD: - case NOTI_MAIL_UPDATE: - ret = handleEmailEvent(account_id, object_id, thread_id, status); - break; - case NOTI_MAIL_DELETE: - //ids of removing messages are sent with name in format: - //id1,id2,id3, - handleEmailRemoveEvent(account_id, name); - break; - case NOTI_MAIL_DELETE_FINISH: - case NOTI_MAIL_DELETE_FAIL: - //notify EmailManager, maybe it tries to delete mail - notifyEmailManager(name, static_cast(status)); - break; - case NOTI_THREAD_DELETE: - handleThreadRemoveEvent(account_id, object_id); - break; - case NOTI_MAILBOX_ADD: - case NOTI_MAILBOX_UPDATE: - case NOTI_MAILBOX_FIELD_UPDATE: - case NOTI_MAILBOX_RENAME: - case NOTI_MAILBOX_DELETE: - ret = handleMailboxEvent(account_id, object_id, status); - break; - default: - LoggerD("Unrecognized status: %d", status); - } - if (ret.IsError()){ - LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); - } - g_free(name); + PlatformResult ret(ErrorCode::NO_ERROR); + switch (status) { + case NOTI_MAIL_ADD: + case NOTI_MAIL_UPDATE: + ret = handleEmailEvent(account_id, object_id, thread_id, status); + break; + case NOTI_MAIL_DELETE: + // ids of removing messages are sent with name in format: + // id1,id2,id3, + handleEmailRemoveEvent(account_id, name); + break; + case NOTI_MAIL_DELETE_FINISH: + case NOTI_MAIL_DELETE_FAIL: + // notify EmailManager, maybe it tries to delete mail + notifyEmailManager(name, static_cast(status)); + break; + case NOTI_THREAD_DELETE: + handleThreadRemoveEvent(account_id, object_id); + break; + case NOTI_MAILBOX_ADD: + case NOTI_MAILBOX_UPDATE: + case NOTI_MAILBOX_FIELD_UPDATE: + case NOTI_MAILBOX_RENAME: + case NOTI_MAILBOX_DELETE: + ret = handleMailboxEvent(account_id, object_id, status); + break; + default: + LoggerD("Unrecognized status: %d", status); + } + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + } + g_free(name); } -PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int thread_id, int event) -{ - LoggerD("Enter"); - - if (ChangeListenerContainer::getInstance().isEmailListenerRegistered()) { - LoggerD("Listener registered - perform action"); - if(NOTI_MAIL_UPDATE == event) { - //getting thread_id from message - email_mail_data_t *mail_data = NULL; - - int ntv_ret = email_get_mail_data(mail_id, &mail_data); - if(EMAIL_ERROR_NONE != ntv_ret) { - if (mail_data) email_free_mail_data(&mail_data, 1); - - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Failed to get mail data during setting" - " conversation id in MessageProxy.", - ("email_get_mail_data error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } +PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int thread_id, + int event) { + LoggerD("Enter"); - thread_id = mail_data->thread_id; + if (ChangeListenerContainer::getInstance().isEmailListenerRegistered()) { + LoggerD("Listener registered - perform action"); + if (NOTI_MAIL_UPDATE == event) { + // getting thread_id from message + email_mail_data_t* mail_data = NULL; - if(EMAIL_ERROR_NONE != email_free_mail_data(&mail_data,1)) { - LoggerE("Failed to free mail data memory"); - } - } + int ntv_ret = email_get_mail_data(mail_id, &mail_data); + if (EMAIL_ERROR_NONE != ntv_ret) { + if (mail_data) email_free_mail_data(&mail_data, 1); - email_mail_data_t* mail_data = EmailManager::getInstance().loadMessage(mail_id); - if (mail_data == NULL) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to load email"); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, + "Failed to get mail data during setting" + " conversation id in MessageProxy.", + ("email_get_mail_data error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - std::shared_ptr msg; - PlatformResult ret = Message::convertPlatformEmailToObject(*mail_data, &msg); - if (ret.IsError()) return ret; - ConversationPtr conv; - ret = MessageConversation::convertEmailConversationToObject( - thread_id, &conv); - if (ret.IsError()) return ret; - EventMessages* eventMsg = new EventMessages(); - eventMsg->service_type = MessageType::EMAIL; - eventMsg->service_id = account_id; - eventMsg->items.push_back(msg); - EventConversations* eventConv = new EventConversations(); - eventConv->service_type = MessageType::EMAIL; - eventConv->service_id = account_id; - eventConv->items.push_back(conv); - switch (event) { - case NOTI_MAIL_ADD: - ChangeListenerContainer::getInstance().callMessageAdded(eventMsg); - if (conv->getMessageCount() == 1) { - LoggerD("This thread is new, triggering conversationAdded"); - ChangeListenerContainer::getInstance().callConversationAdded(eventConv); - } else { - LoggerD("This thread is not new, but it's updated"); - ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); - } - break; - case NOTI_MAIL_UPDATE: - ChangeListenerContainer::getInstance().callMessageUpdated(eventMsg); - ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); - break; - default: - LoggerW("Unknown event type: %d", event); - break; + thread_id = mail_data->thread_id; + if (EMAIL_ERROR_NONE != email_free_mail_data(&mail_data, 1)) { + LoggerE("Failed to free mail data memory"); } - delete eventMsg; - delete eventConv; - - EmailManager::getInstance().freeMessage(mail_data); - } else { - LoggerD("Listener not registered just ignore"); } - return PlatformResult(ErrorCode::NO_ERROR); -} -std::vector getMailIds(const std::string& idsString) -{ - std::stringstream idsStream(idsString); - std::string item; - std::vector ids; - while (std::getline(idsStream, item, ',')) { - if (item.length() > 0) { - int id; - std::stringstream stream(item); - stream >> id; - if (stream) { - LoggerD("Mail delete id: %d", id); - ids.push_back(id); - } - } + email_mail_data_t* mail_data = EmailManager::getInstance().loadMessage(mail_id); + if (mail_data == NULL) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to load email"); } - return ids; -} + std::shared_ptr msg; + PlatformResult ret = Message::convertPlatformEmailToObject(*mail_data, &msg); + if (ret.IsError()) return ret; + ConversationPtr conv; + ret = MessageConversation::convertEmailConversationToObject(thread_id, &conv); + if (ret.IsError()) return ret; -void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& idsString) -{ - LoggerD("Enter"); - std::vector ids = getMailIds(idsString); - if (ids.empty()) { - LoggerD("Mail id list is empty."); - return; - } EventMessages* eventMsg = new EventMessages(); eventMsg->service_type = MessageType::EMAIL; eventMsg->service_id = account_id; - for (auto it = ids.begin(); it != ids.end(); ++it) { - //it turns out that this event is triggered after messages are removed - //so we just create empty messages with id and type - std::shared_ptr msg = std::make_shared(); - msg->setId(*it); - eventMsg->items.push_back(msg); + eventMsg->items.push_back(msg); + EventConversations* eventConv = new EventConversations(); + eventConv->service_type = MessageType::EMAIL; + eventConv->service_id = account_id; + eventConv->items.push_back(conv); + switch (event) { + case NOTI_MAIL_ADD: + ChangeListenerContainer::getInstance().callMessageAdded(eventMsg); + if (conv->getMessageCount() == 1) { + LoggerD("This thread is new, triggering conversationAdded"); + ChangeListenerContainer::getInstance().callConversationAdded(eventConv); + } else { + LoggerD("This thread is not new, but it's updated"); + ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); + } + break; + case NOTI_MAIL_UPDATE: + ChangeListenerContainer::getInstance().callMessageUpdated(eventMsg); + ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); + break; + default: + LoggerW("Unknown event type: %d", event); + break; } - ChangeListenerContainer::getInstance().callMessageRemoved(eventMsg); delete eventMsg; - eventMsg = NULL; + delete eventConv; + + EmailManager::getInstance().freeMessage(mail_data); + } else { + LoggerD("Listener not registered just ignore"); + } + return PlatformResult(ErrorCode::NO_ERROR); } -void MessageProxy::notifyEmailManager(const std::string& idsString, - email_noti_on_storage_event status) -{ - LoggerD("Enter"); - std::vector ids = getMailIds(idsString); - if (ids.empty()) { - LoggerD("Mail id list is empty."); - return; +std::vector getMailIds(const std::string& idsString) { + std::stringstream idsStream(idsString); + std::string item; + std::vector ids; + while (std::getline(idsStream, item, ',')) { + if (item.length() > 0) { + int id; + std::stringstream stream(item); + stream >> id; + if (stream) { + LoggerD("Mail delete id: %d", id); + ids.push_back(id); + } } - EmailManager::getInstance().removeStatusCallback(ids, status); + } + return ids; } -void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id) -{ - LoggerD("Enter"); - //event is called after thread is removed, so we just set thread id and type - ConversationPtr conv = std::make_shared(); - conv->setConversationId(thread_id); - conv->setType(MessageType::EMAIL); +void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& idsString) { + LoggerD("Enter"); + std::vector ids = getMailIds(idsString); + if (ids.empty()) { + LoggerD("Mail id list is empty."); + return; + } + EventMessages* eventMsg = new EventMessages(); + eventMsg->service_type = MessageType::EMAIL; + eventMsg->service_id = account_id; + for (auto it = ids.begin(); it != ids.end(); ++it) { + // it turns out that this event is triggered after messages are removed + // so we just create empty messages with id and type + std::shared_ptr msg = std::make_shared(); + msg->setId(*it); + eventMsg->items.push_back(msg); + } + ChangeListenerContainer::getInstance().callMessageRemoved(eventMsg); + delete eventMsg; + eventMsg = NULL; +} - EventConversations* eventConv = new EventConversations(); - eventConv->service_type = MessageType::EMAIL; - eventConv->service_id = account_id; - eventConv->items.push_back(conv); - ChangeListenerContainer::getInstance().callConversationRemoved(eventConv); - delete eventConv; - eventConv = NULL; +void MessageProxy::notifyEmailManager(const std::string& idsString, + email_noti_on_storage_event status) { + LoggerD("Enter"); + std::vector ids = getMailIds(idsString); + if (ids.empty()) { + LoggerD("Mail id list is empty."); + return; + } + EmailManager::getInstance().removeStatusCallback(ids, status); } -PlatformResult MessageProxy::handleMailboxEvent(int account_id, int mailbox_id, int event) -{ - LoggerD("Enter"); - EventFolders* eventFolder = new EventFolders(); - eventFolder->service_type = MessageType::EMAIL; - eventFolder->service_id = account_id; - FolderPtr folder; - if (event == NOTI_MAILBOX_DELETE) { - //this event is triggered after mailbox is removed - //so we just create folder with id - folder.reset(new MessageFolder(std::to_string(mailbox_id), - "", //parent_id - "", //service_id - "", //content_type - "", //name - "", //path - MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD, - false)); - } else { - email_mailbox_t* mail_box = NULL; - int ntv_ret = email_get_mailbox_by_mailbox_id(mailbox_id, &mail_box); - if (EMAIL_ERROR_NONE != ntv_ret) { - delete eventFolder; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to load mailbox", - ("email_get_mailbox_by_mailbox_id error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); - } - folder.reset(new MessageFolder(*mail_box)); - if (EMAIL_ERROR_NONE != email_free_mailbox(&mail_box, 1)) { - LoggerD("Failed to free email_free_mailbox"); - } +void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id) { + LoggerD("Enter"); + // event is called after thread is removed, so we just set thread id and type + ConversationPtr conv = std::make_shared(); + conv->setConversationId(thread_id); + conv->setType(MessageType::EMAIL); + + EventConversations* eventConv = new EventConversations(); + eventConv->service_type = MessageType::EMAIL; + eventConv->service_id = account_id; + eventConv->items.push_back(conv); + ChangeListenerContainer::getInstance().callConversationRemoved(eventConv); + delete eventConv; + eventConv = NULL; +} + +PlatformResult MessageProxy::handleMailboxEvent(int account_id, int mailbox_id, int event) { + LoggerD("Enter"); + EventFolders* eventFolder = new EventFolders(); + eventFolder->service_type = MessageType::EMAIL; + eventFolder->service_id = account_id; + FolderPtr folder; + if (event == NOTI_MAILBOX_DELETE) { + // this event is triggered after mailbox is removed + // so we just create folder with id + folder.reset(new MessageFolder(std::to_string(mailbox_id), + "", // parent_id + "", // service_id + "", // content_type + "", // name + "", // path + MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD, false)); + } else { + email_mailbox_t* mail_box = NULL; + int ntv_ret = email_get_mailbox_by_mailbox_id(mailbox_id, &mail_box); + if (EMAIL_ERROR_NONE != ntv_ret) { + delete eventFolder; + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to load mailbox", + ("email_get_mailbox_by_mailbox_id error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - eventFolder->items.push_back(folder); - switch (event) { - case NOTI_MAILBOX_ADD: - ChangeListenerContainer::getInstance().callFolderAdded(eventFolder); - break; - case NOTI_MAILBOX_UPDATE: - case NOTI_MAILBOX_FIELD_UPDATE: - ChangeListenerContainer::getInstance().callFolderUpdated(eventFolder); - break; - case NOTI_MAILBOX_DELETE: - ChangeListenerContainer::getInstance().callFolderRemoved(eventFolder); - break; - default: - LoggerW("Unknown event type: %d", event); + folder.reset(new MessageFolder(*mail_box)); + if (EMAIL_ERROR_NONE != email_free_mailbox(&mail_box, 1)) { + LoggerD("Failed to free email_free_mailbox"); } - delete eventFolder; - return PlatformResult(ErrorCode::NO_ERROR); + } + eventFolder->items.push_back(folder); + switch (event) { + case NOTI_MAILBOX_ADD: + ChangeListenerContainer::getInstance().callFolderAdded(eventFolder); + break; + case NOTI_MAILBOX_UPDATE: + case NOTI_MAILBOX_FIELD_UPDATE: + ChangeListenerContainer::getInstance().callFolderUpdated(eventFolder); + break; + case NOTI_MAILBOX_DELETE: + ChangeListenerContainer::getInstance().callFolderRemoved(eventFolder); + break; + default: + LoggerW("Unknown event type: %d", event); + } + delete eventFolder; + return PlatformResult(ErrorCode::NO_ERROR); } -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension diff --git a/src/messaging/DBus/MessageProxy.h b/src/messaging/DBus/MessageProxy.h index 04a8968..6006117 100644 --- a/src/messaging/DBus/MessageProxy.h +++ b/src/messaging/DBus/MessageProxy.h @@ -18,13 +18,13 @@ #ifndef __TIZEN_MESSAGE_PROXY_H #define __TIZEN_MESSAGE_PROXY_H -#include #include +#include +#include #include #include -#include #include -#include +#include #include "common/GDBus/proxy.h" #include "common/platform_result.h" @@ -35,35 +35,32 @@ namespace DBus { class MessageProxy; typedef std::shared_ptr MessageProxyPtr; -class MessageProxy: public common::dbus::Proxy { -public: - virtual ~MessageProxy(); - static common::PlatformResult create(MessageProxyPtr* message_proxy); -protected: - MessageProxy(); - virtual void signalCallback(GDBusConnection *connection, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters); - /** - * Handles e-mail add and update only. - * @param account_id - * @param mail_id - * @param thread_id - * @param event - */ - common::PlatformResult handleEmailEvent(int account_id, int mail_id, int thread_id, int event); - void handleEmailRemoveEvent(int account_id, const std::string& idsString); - void notifyEmailManager(const std::string& idsString, email_noti_on_storage_event status); - void handleThreadRemoveEvent(int account_id, int thread_id); - common::PlatformResult handleMailboxEvent(int account_id, int mailbox_id, int event); +class MessageProxy : public common::dbus::Proxy { + public: + virtual ~MessageProxy(); + static common::PlatformResult create(MessageProxyPtr *message_proxy); + + protected: + MessageProxy(); + virtual void signalCallback(GDBusConnection *connection, const gchar *sender_name, + const gchar *object_path, const gchar *interface_name, + const gchar *signal_name, GVariant *parameters); + /** + * Handles e-mail add and update only. + * @param account_id + * @param mail_id + * @param thread_id + * @param event + */ + common::PlatformResult handleEmailEvent(int account_id, int mail_id, int thread_id, int event); + void handleEmailRemoveEvent(int account_id, const std::string &idsString); + void notifyEmailManager(const std::string &idsString, email_noti_on_storage_event status); + void handleThreadRemoveEvent(int account_id, int thread_id); + common::PlatformResult handleMailboxEvent(int account_id, int mailbox_id, int event); }; -} //namespace DBus -} //namespace messaging -} //namespace extension +} // namespace DBus +} // namespace messaging +} // namespace extension #endif /* __TIZEN_MESSAGE_PROXY_H */ - diff --git a/src/messaging/DBus/SendProxy.cpp b/src/messaging/DBus/SendProxy.cpp index cc0a16f..f747113 100644 --- a/src/messaging/DBus/SendProxy.cpp +++ b/src/messaging/DBus/SendProxy.cpp @@ -29,50 +29,41 @@ namespace DBus { using namespace common; -SendProxy::SendProxy(): - EmailSignalProxy(kDBusPathNetworkStatus, - kDBusIfaceNetworkStatus) -{ +SendProxy::SendProxy() : EmailSignalProxy(kDBusPathNetworkStatus, kDBusIfaceNetworkStatus) { } -SendProxy::~SendProxy() -{ +SendProxy::~SendProxy() { } PlatformResult SendProxy::create(SendProxyPtr* send_proxy) { - send_proxy->reset(new SendProxy()); - if ((*send_proxy)->isNotProxyGot()) { - send_proxy->reset(); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get send proxy"); - } else { - return PlatformResult(ErrorCode::NO_ERROR); - } + send_proxy->reset(new SendProxy()); + if ((*send_proxy)->isNotProxyGot()) { + send_proxy->reset(); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get send proxy"); + } else { + return PlatformResult(ErrorCode::NO_ERROR); + } } -void SendProxy::handleEmailSignal(const int status, - const int account_id, - const std::string& source, - const int mail_id, - const int error_code) -{ - LoggerD("Enter"); - switch (status) { - case NOTI_SEND_FINISH: - case NOTI_SEND_FAIL: - LoggerD("Recognized status for email send"); - LoggerD("received email signal with:\n status: %d\n account_id: %d\n " - "source: %s\n mail_id: %d\n error_code: %d", - status, account_id, source.c_str(), mail_id, error_code); - EmailManager::getInstance().sendStatusCallback(mail_id, - static_cast(status), - error_code); - break; - default: - LoggerD("Unrecognized status %d, ignoring", status); - } +void SendProxy::handleEmailSignal(const int status, const int account_id, const std::string& source, + const int mail_id, const int error_code) { + LoggerD("Enter"); + switch (status) { + case NOTI_SEND_FINISH: + case NOTI_SEND_FAIL: + LoggerD("Recognized status for email send"); + LoggerD( + "received email signal with:\n status: %d\n account_id: %d\n " + "source: %s\n mail_id: %d\n error_code: %d", + status, account_id, source.c_str(), mail_id, error_code); + EmailManager::getInstance().sendStatusCallback( + mail_id, static_cast(status), error_code); + break; + default: + LoggerD("Unrecognized status %d, ignoring", status); + } } - -} //DBus -} //messaging -} //extension +} // DBus +} // messaging +} // extension diff --git a/src/messaging/DBus/SendProxy.h b/src/messaging/DBus/SendProxy.h index ef7d5ef..e9f211b 100644 --- a/src/messaging/DBus/SendProxy.h +++ b/src/messaging/DBus/SendProxy.h @@ -18,8 +18,8 @@ #ifndef __TIZEN_SEND_PROXY_H #define __TIZEN_SEND_PROXY_H -#include "common/platform_result.h" #include "EmailSignalProxy.h" +#include "common/platform_result.h" namespace extension { namespace messaging { @@ -28,22 +28,19 @@ namespace DBus { class SendProxy; typedef std::shared_ptr SendProxyPtr; -class SendProxy: public EmailSignalProxy { -public: - virtual ~SendProxy(); - static common::PlatformResult create(SendProxyPtr* send_proxy); -protected: - SendProxy(); - virtual void handleEmailSignal(const int status, - const int account_id, - const std::string& source, - const int op_handle, - const int error_code); +class SendProxy : public EmailSignalProxy { + public: + virtual ~SendProxy(); + static common::PlatformResult create(SendProxyPtr* send_proxy); + + protected: + SendProxy(); + virtual void handleEmailSignal(const int status, const int account_id, const std::string& source, + const int op_handle, const int error_code); }; -} //DBus -} //messaging -} //extension +} // DBus +} // messaging +} // extension #endif /* __TIZEN_SEND_PROXY_H */ - diff --git a/src/messaging/DBus/SyncProxy.cpp b/src/messaging/DBus/SyncProxy.cpp index 7ce525e..c47b6b2 100644 --- a/src/messaging/DBus/SyncProxy.cpp +++ b/src/messaging/DBus/SyncProxy.cpp @@ -20,11 +20,11 @@ */ #include "SyncProxy.h" -#include "common/logger.h" -#include "common/platform_result.h" -#include #include +#include #include "../message_service.h" +#include "common/logger.h" +#include "common/platform_result.h" namespace extension { namespace messaging { @@ -32,33 +32,26 @@ namespace DBus { using namespace common; -SyncProxy::SyncProxy(const std::string& path, - const std::string& iface) : - EmailSignalProxy(path, iface) -{ - +SyncProxy::SyncProxy(const std::string& path, const std::string& iface) + : EmailSignalProxy(path, iface) { } -SyncProxy::~SyncProxy() -{ - +SyncProxy::~SyncProxy() { } -PlatformResult SyncProxy::create(const std::string& path, - const std::string& iface, +PlatformResult SyncProxy::create(const std::string& path, const std::string& iface, SyncProxyPtr* sync_proxy) { - sync_proxy->reset(new SyncProxy(path, iface)); - if ((*sync_proxy)->isNotProxyGot()) { - sync_proxy->reset(); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get sync proxy"); - } else { - return PlatformResult(ErrorCode::NO_ERROR); - } + sync_proxy->reset(new SyncProxy(path, iface)); + if ((*sync_proxy)->isNotProxyGot()) { + sync_proxy->reset(); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get sync proxy"); + } else { + return PlatformResult(ErrorCode::NO_ERROR); + } } -void SyncProxy::addCallback(long op_id, CallbackUserData* callbackOwned) -{ - m_callback_map.insert(std::make_pair(op_id, callbackOwned)); +void SyncProxy::addCallback(long op_id, CallbackUserData* callbackOwned) { + m_callback_map.insert(std::make_pair(op_id, callbackOwned)); } CallbackUserData* SyncProxy::getCallback(long op_id) { @@ -84,85 +77,78 @@ void SyncProxy::removeCallback(long op_id) { } } -void SyncProxy::handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code) -{ - if( NOTI_DOWNLOAD_START != status && - NOTI_DOWNLOAD_FINISH != status && - NOTI_DOWNLOAD_FAIL != status ) { - // Nothing to do: this status is not related to sync nor syncFolder request - return; - } - - LoggerD("received email signal with:\n status: %d\n mail_id: %d\n " - "source: %s\n op_handle: %d\n error_code: %d", - status, mail_id, source.c_str(), op_handle, error_code); - - if (NOTI_DOWNLOAD_START == status) { - LoggerD("Sync started..."); - // There is nothing more to do so we can return now. - return; - } +void SyncProxy::handleEmailSignal(const int status, const int mail_id, const std::string& source, + const int op_handle, const int error_code) { + if (NOTI_DOWNLOAD_START != status && NOTI_DOWNLOAD_FINISH != status && + NOTI_DOWNLOAD_FAIL != status) { + // Nothing to do: this status is not related to sync nor syncFolder request + return; + } - SyncCallbackData* callback = NULL; - CallbackMap::iterator callback_it; + LoggerD( + "received email signal with:\n status: %d\n mail_id: %d\n " + "source: %s\n op_handle: %d\n error_code: %d", + status, mail_id, source.c_str(), op_handle, error_code); - PlatformResult ret = findSyncCallbackByOpHandle(op_handle, &callback_it); - if (ret.IsError()) { - LoggerE("Failed to find callback by handle - (%s)", ret.message().c_str()); - return; - } + if (NOTI_DOWNLOAD_START == status) { + LoggerD("Sync started..."); + // There is nothing more to do so we can return now. + return; + } - callback = dynamic_cast(callback_it->second); - if (!callback) { - LoggerE("Callback is null"); - return; - } + SyncCallbackData* callback = NULL; + CallbackMap::iterator callback_it; - switch (status) { - case NOTI_DOWNLOAD_FINISH: - LoggerD("Sync finished!"); - callback->SetSuccess(); - callback->Post(); - break; + PlatformResult ret = findSyncCallbackByOpHandle(op_handle, &callback_it); + if (ret.IsError()) { + LoggerE("Failed to find callback by handle - (%s)", ret.message().c_str()); + return; + } - case NOTI_DOWNLOAD_FAIL: - callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Sync failed!")); - callback->Post(); - break; + callback = dynamic_cast(callback_it->second); + if (!callback) { + LoggerE("Callback is null"); + return; + } - } + switch (status) { + case NOTI_DOWNLOAD_FINISH: + LoggerD("Sync finished!"); + callback->SetSuccess(); + callback->Post(); + break; + + case NOTI_DOWNLOAD_FAIL: + callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Sync failed!")); + callback->Post(); + break; + } - if (callback) { - delete callback; - m_callback_map.erase(callback_it); - } + if (callback) { + delete callback; + m_callback_map.erase(callback_it); + } } PlatformResult SyncProxy::findSyncCallbackByOpHandle(const int op_handle, - SyncProxy::CallbackMap::iterator* it) -{ - *it = m_callback_map.begin(); - for (; *it != m_callback_map.end(); ++(*it)) { - SyncCallbackData* cb = dynamic_cast((*it)->second); - if (!cb) continue; - - if (op_handle == cb->getOperationHandle()) { - return PlatformResult(ErrorCode::NO_ERROR); - } + SyncProxy::CallbackMap::iterator* it) { + *it = m_callback_map.begin(); + for (; *it != m_callback_map.end(); ++(*it)) { + SyncCallbackData* cb = dynamic_cast((*it)->second); + if (!cb) continue; + + if (op_handle == cb->getOperationHandle()) { + return PlatformResult(ErrorCode::NO_ERROR); } - // this situation may occur when there is no callback in the - // map with specified opId (for example stopSync() has - // removed it), but sync() was already started - only - // warning here: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not find callback", - ("Could not find callback with op_handle: %d", op_handle)); + } + // this situation may occur when there is no callback in the + // map with specified opId (for example stopSync() has + // removed it), but sync() was already started - only + // warning here: + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not find callback", + ("Could not find callback with op_handle: %d", op_handle)); } -} //namespace DBus -} //namespace Messaging -} //namespace DeviceAPI +} // namespace DBus +} // namespace Messaging +} // namespace DeviceAPI diff --git a/src/messaging/DBus/SyncProxy.h b/src/messaging/DBus/SyncProxy.h index 183f0ba..1b35df5 100644 --- a/src/messaging/DBus/SyncProxy.h +++ b/src/messaging/DBus/SyncProxy.h @@ -22,9 +22,9 @@ #ifndef __TIZEN_DBUS_SYNC_PROXY_H__ #define __TIZEN_DBUS_SYNC_PROXY_H__ -#include "messaging/callback_user_data.h" #include "EmailSignalProxy.h" #include "common/platform_result.h" +#include "messaging/callback_user_data.h" namespace extension { namespace messaging { @@ -34,43 +34,36 @@ class SyncProxy; typedef std::shared_ptr SyncProxyPtr; class SyncProxy : public EmailSignalProxy { -public: - - // Callback is owned by this map - typedef std::map CallbackMap; + public: + // Callback is owned by this map + typedef std::map CallbackMap; - virtual ~SyncProxy(); + virtual ~SyncProxy(); - static common::PlatformResult create(const std::string& path, - const std::string& iface, - SyncProxyPtr* sync_proxy); - //Passed callback will be owned by this proxy - void addCallback(long op_id, CallbackUserData* callbackOwned); - CallbackUserData* getCallback(long op_id); - void removeCallback(long op_id); + static common::PlatformResult create(const std::string& path, const std::string& iface, + SyncProxyPtr* sync_proxy); + // Passed callback will be owned by this proxy + void addCallback(long op_id, CallbackUserData* callbackOwned); + CallbackUserData* getCallback(long op_id); + void removeCallback(long op_id); -protected: - SyncProxy(const std::string& path, - const std::string& iface); + protected: + SyncProxy(const std::string& path, const std::string& iface); - virtual void handleEmailSignal(const int status, - const int mail_id, - const std::string& source, - const int op_handle, - const int error_code); + virtual void handleEmailSignal(const int status, const int mail_id, const std::string& source, + const int op_handle, const int error_code); -private: - /** - * Find callback by operation handle returned from: - * int email_sync_header(..., int *handle); - */ - common::PlatformResult findSyncCallbackByOpHandle(const int op_handle, - CallbackMap::iterator* it); - CallbackMap m_callback_map; + private: + /** + * Find callback by operation handle returned from: + * int email_sync_header(..., int *handle); + */ + common::PlatformResult findSyncCallbackByOpHandle(const int op_handle, CallbackMap::iterator* it); + CallbackMap m_callback_map; }; -} //namespace DBus -} //namespace Messaging -} //namespace DeviceAPI +} // namespace DBus +} // namespace Messaging +} // namespace DeviceAPI -#endif // __TIZEN_DBUS_SYNC_PROXY_H__ +#endif // __TIZEN_DBUS_SYNC_PROXY_H__ diff --git a/src/messaging/MsgCommon/AbstractFilter.cpp b/src/messaging/MsgCommon/AbstractFilter.cpp old mode 100755 new mode 100644 index 36a05f2..9cbddb9 --- a/src/messaging/MsgCommon/AbstractFilter.cpp +++ b/src/messaging/MsgCommon/AbstractFilter.cpp @@ -18,8 +18,8 @@ //#include "JSAttributeFilter.h" //#include "JSAttributeRangeFilter.h" //#include "JSCompositeFilter.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" //#include #include @@ -28,172 +28,154 @@ namespace tizen { using namespace common; -AbstractFilter::AbstractFilter(FilterType filter_type) : - m_filter_type(filter_type) -{ +AbstractFilter::AbstractFilter(FilterType filter_type) : m_filter_type(filter_type) { } -AbstractFilter::~AbstractFilter() -{ +AbstractFilter::~AbstractFilter() { } -FilterType AbstractFilter::getFilterType() const -{ - return m_filter_type; +FilterType AbstractFilter::getFilterType() const { + return m_filter_type; } -bool AbstractFilter::isMatching(const FilterableObject* const tested_object) const -{ - LoggerE("Calling isMatching on AbstractFilter!"); - return false; +bool AbstractFilter::isMatching(const FilterableObject* const tested_object) const { + LoggerE("Calling isMatching on AbstractFilter!"); + return false; } -AttributeFilterPtr castToAttributeFilter(AbstractFilterPtr from) -{ - if(ATTRIBUTE_FILTER != from->getFilterType()) { - LoggerE("Trying to get AttributeFilterPtr but filter's type is: %d", - from->getFilterType()); - return AttributeFilterPtr(); - } +AttributeFilterPtr castToAttributeFilter(AbstractFilterPtr from) { + if (ATTRIBUTE_FILTER != from->getFilterType()) { + LoggerE("Trying to get AttributeFilterPtr but filter's type is: %d", from->getFilterType()); + return AttributeFilterPtr(); + } - return std::dynamic_pointer_cast(from); + return std::dynamic_pointer_cast(from); } -AttributeRangeFilterPtr castToAttributeRangeFilter(AbstractFilterPtr from) -{ - if(ATTRIBUTE_RANGE_FILTER != from->getFilterType()) { - LoggerE("Trying to get AttributeRangeFilterPtr but filter's type is: %d", - from->getFilterType()); - return AttributeRangeFilterPtr(); - } +AttributeRangeFilterPtr castToAttributeRangeFilter(AbstractFilterPtr from) { + if (ATTRIBUTE_RANGE_FILTER != from->getFilterType()) { + LoggerE("Trying to get AttributeRangeFilterPtr but filter's type is: %d", + from->getFilterType()); + return AttributeRangeFilterPtr(); + } - return std::dynamic_pointer_cast(from); + return std::dynamic_pointer_cast(from); } -CompositeFilterPtr castToCompositeFilter(AbstractFilterPtr from) -{ - if(COMPOSITE_FILTER != from->getFilterType()) { - LoggerE("Trying to get CompositeFilterPtr but filter's type is: %d", - from->getFilterType()); - return CompositeFilterPtr(); - } +CompositeFilterPtr castToCompositeFilter(AbstractFilterPtr from) { + if (COMPOSITE_FILTER != from->getFilterType()) { + LoggerE("Trying to get CompositeFilterPtr but filter's type is: %d", from->getFilterType()); + return CompositeFilterPtr(); + } - return std::dynamic_pointer_cast(from); + return std::dynamic_pointer_cast(from); } namespace { -inline std::string convertToLowerCase(const std::string& input_string) -{ - std::string output_string = input_string; - std::transform(output_string.begin(), output_string.end(), output_string.begin(), - ::tolower); - return output_string; +inline std::string convertToLowerCase(const std::string& input_string) { + std::string output_string = input_string; + std::transform(output_string.begin(), output_string.end(), output_string.begin(), ::tolower); + return output_string; } -} // Anonymous namespace - -bool FilterUtils::isStringMatching(const std::string& key, - const std::string& value, - tizen::FilterMatchFlag flag) -{ - switch(flag) - { - case tizen::ENDSWITH: { - if (key.empty()) { - return false; - } - if (key.size() > value.size()) { - return false; - } - std::string lvalue = convertToLowerCase(value); - std::string lkey = convertToLowerCase(key); - return lvalue.substr(lvalue.size() - lkey.size(), lkey.size()) == lkey; - } - - case tizen::EXACTLY: { - return key == value; - } - - case tizen::STARTSWITH: { - if (key.empty()) { - return false; - } - if (key.size() > value.size()) { - return false; - } - std::string lvalue = convertToLowerCase(value); - std::string lkey = convertToLowerCase(key); - return lvalue.substr(0, lkey.size()) == lkey; - } - - case tizen::CONTAINS: { - if (key.empty()) { - return false; - } - if (key.size() > value.size()) { - return false; - } - std::string lvalue = convertToLowerCase(value); - std::string lkey = convertToLowerCase(key); - return lvalue.find(lkey) != std::string::npos; - } - - default: { - LoggerE("Unknown match flag"); - return false; - } +} // Anonymous namespace + +bool FilterUtils::isStringMatching(const std::string& key, const std::string& value, + tizen::FilterMatchFlag flag) { + switch (flag) { + case tizen::ENDSWITH: { + if (key.empty()) { + return false; + } + if (key.size() > value.size()) { + return false; + } + std::string lvalue = convertToLowerCase(value); + std::string lkey = convertToLowerCase(key); + return lvalue.substr(lvalue.size() - lkey.size(), lkey.size()) == lkey; } -} -bool FilterUtils::isAnyStringMatching(const std::string& key, - const std::vector& values, - tizen::FilterMatchFlag flag) -{ - for(auto it = values.begin(); it != values.end(); ++it) { - if(isStringMatching(key,*it,flag)) { - return true; - } + case tizen::EXACTLY: { + return key == value; } - return false; -} -bool FilterUtils::isTimeStampInRange(const time_t& time_stamp, - tizen::AnyPtr& initial_value, - tizen::AnyPtr& end_value) -{ - time_t from_time = 0; - time_t to_time = 0; - - bool initial_is_valid_time_value = false; - if (initial_value && !initial_value->isNullOrUndefined()) { - struct tm ftime = *initial_value->toDateTm(); - from_time = mktime(&ftime); - initial_is_valid_time_value = true; + case tizen::STARTSWITH: { + if (key.empty()) { + return false; + } + if (key.size() > value.size()) { + return false; + } + std::string lvalue = convertToLowerCase(value); + std::string lkey = convertToLowerCase(key); + return lvalue.substr(0, lkey.size()) == lkey; } - if (!initial_is_valid_time_value) { - LoggerE("initialValue is not Time!"); + + case tizen::CONTAINS: { + if (key.empty()) { return false; + } + if (key.size() > value.size()) { + return false; + } + std::string lvalue = convertToLowerCase(value); + std::string lkey = convertToLowerCase(key); + return lvalue.find(lkey) != std::string::npos; } - bool end_is_valid_time_value = false; - if (end_value && !end_value->isNullOrUndefined()) { - struct tm ttime = *end_value->toDateTm(); - to_time = mktime(&ttime); - end_is_valid_time_value = true; + default: { + LoggerE("Unknown match flag"); + return false; } - if (end_is_valid_time_value) { - LoggerE("endValue is not Time!"); - return false; + } +} + +bool FilterUtils::isAnyStringMatching(const std::string& key, + const std::vector& values, + tizen::FilterMatchFlag flag) { + for (auto it = values.begin(); it != values.end(); ++it) { + if (isStringMatching(key, *it, flag)) { + return true; } + } + return false; +} + +bool FilterUtils::isTimeStampInRange(const time_t& time_stamp, tizen::AnyPtr& initial_value, + tizen::AnyPtr& end_value) { + time_t from_time = 0; + time_t to_time = 0; + + bool initial_is_valid_time_value = false; + if (initial_value && !initial_value->isNullOrUndefined()) { + struct tm ftime = *initial_value->toDateTm(); + from_time = mktime(&ftime); + initial_is_valid_time_value = true; + } + if (!initial_is_valid_time_value) { + LoggerE("initialValue is not Time!"); + return false; + } + + bool end_is_valid_time_value = false; + if (end_value && !end_value->isNullOrUndefined()) { + struct tm ttime = *end_value->toDateTm(); + to_time = mktime(&ttime); + end_is_valid_time_value = true; + } + if (end_is_valid_time_value) { + LoggerE("endValue is not Time!"); + return false; + } - bool is_in_range = FilterUtils::isBetweenTimeRange(time_stamp, from_time, to_time); + bool is_in_range = FilterUtils::isBetweenTimeRange(time_stamp, from_time, to_time); - LoggerD("%d is%s in time range <%d, %d>", time_stamp, (is_in_range ? "" : " NOT"), - from_time, to_time); + LoggerD("%d is%s in time range <%d, %d>", time_stamp, (is_in_range ? "" : " NOT"), from_time, + to_time); - return is_in_range; + return is_in_range; } -} //Tizen -} //DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/AbstractFilter.h b/src/messaging/MsgCommon/AbstractFilter.h index 0ac41e4..3d91173 100644 --- a/src/messaging/MsgCommon/AbstractFilter.h +++ b/src/messaging/MsgCommon/AbstractFilter.h @@ -18,8 +18,8 @@ #define __TIZEN_TIZEN_ABSTRACT_FILTER_H__ #include -#include #include +#include //#include #include "Any.h" @@ -41,53 +41,40 @@ typedef std::shared_ptr AbstractFilterPtr; typedef std::vector AbstractFilterPtrVector; struct AbstractFilterHolder { - AbstractFilterPtr ptr; + AbstractFilterPtr ptr; }; -enum FilterType { - ABSTRACT_FILTER = 0, - ATTRIBUTE_FILTER, - ATTRIBUTE_RANGE_FILTER, - COMPOSITE_FILTER -}; +enum FilterType { ABSTRACT_FILTER = 0, ATTRIBUTE_FILTER, ATTRIBUTE_RANGE_FILTER, COMPOSITE_FILTER }; -enum FilterMatchFlag { - EXACTLY = 0, - FULLSTRING, - CONTAINS, - STARTSWITH, - ENDSWITH, - EXISTS -}; +enum FilterMatchFlag { EXACTLY = 0, FULLSTRING, CONTAINS, STARTSWITH, ENDSWITH, EXISTS }; class FilterableObject { -public: - virtual ~FilterableObject(){} + public: + virtual ~FilterableObject() { + } - virtual bool isMatchingAttribute(const std::string& attribute_name, - const FilterMatchFlag match_flag, - AnyPtr match_value) const = 0; + virtual bool isMatchingAttribute(const std::string& attribute_name, + const FilterMatchFlag match_flag, AnyPtr match_value) const = 0; - virtual bool isMatchingAttributeRange(const std::string& attribute_name, - AnyPtr initial_value, - AnyPtr end_value) const = 0; + virtual bool isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, + AnyPtr end_value) const = 0; }; class AbstractFilter { -public: - AbstractFilter(FilterType type = ABSTRACT_FILTER); - virtual ~AbstractFilter(); + public: + AbstractFilter(FilterType type = ABSTRACT_FILTER); + virtual ~AbstractFilter(); - FilterType getFilterType() const; + FilterType getFilterType() const; -// static JSValueRef makeJSValue(JSContextRef context, AbstractFilterPtr priv); -// static AbstractFilterPtr getPrivateObject(JSContextRef context, -// JSValueRef value); + // static JSValueRef makeJSValue(JSContextRef context, AbstractFilterPtr priv); + // static AbstractFilterPtr getPrivateObject(JSContextRef context, + // JSValueRef value); - virtual bool isMatching(const FilterableObject* const filtered_object) const; + virtual bool isMatching(const FilterableObject* const filtered_object) const; -protected: - FilterType m_filter_type; + protected: + FilterType m_filter_type; }; /** @@ -97,9 +84,8 @@ AttributeFilterPtr castToAttributeFilter(AbstractFilterPtr from); AttributeRangeFilterPtr castToAttributeRangeFilter(AbstractFilterPtr from); CompositeFilterPtr castToCompositeFilter(AbstractFilterPtr from); - -//class JSFilterArray : public Common::JSArray { -//public: +// class JSFilterArray : public Common::JSArray { +// public: // JSFilterArray(JSContextRef ctx, JSObjectRef array): // JSArray(ctx, array, AbstractFilter::getPrivateObject, // AbstractFilter::makeJSValue) @@ -116,44 +102,33 @@ CompositeFilterPtr castToCompositeFilter(AbstractFilterPtr from); // } //}; - - class FilterUtils { -public: - static bool isStringMatching(const std::string& key, - const std::string& value, - tizen::FilterMatchFlag flag); - static bool isAnyStringMatching(const std::string& key, - const std::vector& values, - tizen::FilterMatchFlag flag); - static bool isTimeStampInRange(const time_t& time_stamp, - tizen::AnyPtr& initial_value, - tizen::AnyPtr& end_value); - - static inline bool isBetweenTimeRange(const time_t current, - const time_t from, - const time_t to) - { - return ((current - from) >= 0 ) && ((to - current) >= 0); - } - - static inline std::string boolToString(const bool src) - { - if(src) { - return "true"; - } - else { - return "false"; - } + public: + static bool isStringMatching(const std::string& key, const std::string& value, + tizen::FilterMatchFlag flag); + static bool isAnyStringMatching(const std::string& key, const std::vector& values, + tizen::FilterMatchFlag flag); + static bool isTimeStampInRange(const time_t& time_stamp, tizen::AnyPtr& initial_value, + tizen::AnyPtr& end_value); + + static inline bool isBetweenTimeRange(const time_t current, const time_t from, const time_t to) { + return ((current - from) >= 0) && ((to - current) >= 0); + } + + static inline std::string boolToString(const bool src) { + if (src) { + return "true"; + } else { + return "false"; } + } }; -} // Tizen -} // DeviceAPI - +} // Tizen +} // DeviceAPI #include "AttributeFilter.h" #include "AttributeRangeFilter.h" #include "CompositeFilter.h" -#endif // __TIZEN_TIZEN_ABSTRACT_FILTER_H__ +#endif // __TIZEN_TIZEN_ABSTRACT_FILTER_H__ diff --git a/src/messaging/MsgCommon/Any.cpp b/src/messaging/MsgCommon/Any.cpp old mode 100755 new mode 100644 index 0bd8948..e61087b --- a/src/messaging/MsgCommon/Any.cpp +++ b/src/messaging/MsgCommon/Any.cpp @@ -21,34 +21,30 @@ namespace extension { namespace tizen { -Any::Any(picojson::value value) : -// m_context(context), - m_value(value) -{ -// JSValueProtect(m_context, m_value); +Any::Any(picojson::value value) + : // m_context(context), + m_value(value) { + // JSValueProtect(m_context, m_value); } -Any::~Any() -{ -// JSValueUnprotect(m_context, m_value); +Any::~Any() { + // JSValueUnprotect(m_context, m_value); } -//JSContextRef Any::getContext() const +// JSContextRef Any::getContext() const //{ // return m_context; //} -picojson::value Any::getValue() const -{ - return m_value; +picojson::value Any::getValue() const { + return m_value; } -void Any::setValue(picojson::value value) -{ -// JSValueUnprotect(m_context, m_value); -// m_context = context; - m_value = value; -// JSValueProtect(m_context, m_value); +void Any::setValue(picojson::value value) { + // JSValueUnprotect(m_context, m_value); + // m_context = context; + m_value = value; + // JSValueProtect(m_context, m_value); } bool Any::isNullOrUndefined() const { @@ -56,125 +52,116 @@ bool Any::isNullOrUndefined() const { return m_value.is(); } -bool Any::toBool() const -{ - if (m_value.is()) { - return m_value.get(); - } else { - return ("true" == this->toString()); - } +bool Any::toBool() const { + if (m_value.is()) { + return m_value.get(); + } else { + return ("true" == this->toString()); + } } -long Any::toLong() const -{ - if (m_value.is()) { - return static_cast(m_value.get()); - } else if (m_value.is()) { - try { - return std::stol(m_value.get()); - } catch (...) { - return static_cast(0); - } - } else { - return static_cast(0); +long Any::toLong() const { + if (m_value.is()) { + return static_cast(m_value.get()); + } else if (m_value.is()) { + try { + return std::stol(m_value.get()); + } catch (...) { + return static_cast(0); } + } else { + return static_cast(0); + } } -unsigned long Any::toULong() const -{ - if (m_value.is()) { - return static_cast(m_value.get()); - } else if (m_value.is()) { - try { - return std::stoul(m_value.get()); - } catch (...) { - return static_cast(0); - } - } else { - return static_cast(0); +unsigned long Any::toULong() const { + if (m_value.is()) { + return static_cast(m_value.get()); + } else if (m_value.is()) { + try { + return std::stoul(m_value.get()); + } catch (...) { + return static_cast(0); } + } else { + return static_cast(0); + } } -long long Any::toLongLong() const -{ - if (m_value.is()) { - return static_cast(m_value.get()); - } else if (m_value.is()) { - try { - return std::stoll(m_value.get()); - } catch (...) { - return static_cast(0); - } - } else { - return static_cast(0); +long long Any::toLongLong() const { + if (m_value.is()) { + return static_cast(m_value.get()); + } else if (m_value.is()) { + try { + return std::stoll(m_value.get()); + } catch (...) { + return static_cast(0); } + } else { + return static_cast(0); + } } -unsigned long long Any::toULongLong() const -{ - if (m_value.is()) { - return static_cast(m_value.get()); - } else if (m_value.is()) { - try { - return std::stoull(m_value.get()); - } catch (...) { - return static_cast(0); - } - } else { - return static_cast(0); +unsigned long long Any::toULongLong() const { + if (m_value.is()) { + return static_cast(m_value.get()); + } else if (m_value.is()) { + try { + return std::stoull(m_value.get()); + } catch (...) { + return static_cast(0); } + } else { + return static_cast(0); + } } -double Any::toDouble() const -{ - if (m_value.is()) { - return m_value.get(); - } else if (m_value.is()) { - try { - return std::stod(m_value.get()); - } catch (...) { - return 0.0; - } - } else { - return 0.0; +double Any::toDouble() const { + if (m_value.is()) { + return m_value.get(); + } else if (m_value.is()) { + try { + return std::stod(m_value.get()); + } catch (...) { + return 0.0; } + } else { + return 0.0; + } } -std::string Any::toString() const -{ - if (m_value.is()) { - return m_value.get(); - } else { - return ""; - } +std::string Any::toString() const { + if (m_value.is()) { + return m_value.get(); + } else { + return ""; + } } -std::tm* Any::toDateTm() const -{ - static std::tm t; - memset(&t, 0, sizeof(std::tm)); - strptime(toString().c_str(), "%Y-%m-%dT%H:%M:%S.%zZ", &t); - return &t; +std::tm* Any::toDateTm() const { + static std::tm t; + memset(&t, 0, sizeof(std::tm)); + strptime(toString().c_str(), "%Y-%m-%dT%H:%M:%S.%zZ", &t); + return &t; } -std::time_t Any::toTimeT() const -{ - std::time_t current_time; - std::time(¤t_time); - struct tm timeinfo = {0}; - long int gmtoff = 0; - tzset(); - if (nullptr != localtime_r(¤t_time, &timeinfo)) { - gmtoff = timeinfo.tm_gmtoff; - - if (timeinfo.tm_isdst) { - // if dst is set then 1 hour should be subtracted. - // 1 hour = 60 second * 60 minutes = 3600 seconds - gmtoff -= 3600; - } +std::time_t Any::toTimeT() const { + std::time_t current_time; + std::time(¤t_time); + struct tm timeinfo = {0}; + long int gmtoff = 0; + tzset(); + if (nullptr != localtime_r(¤t_time, &timeinfo)) { + gmtoff = timeinfo.tm_gmtoff; + + if (timeinfo.tm_isdst) { + // if dst is set then 1 hour should be subtracted. + // 1 hour = 60 second * 60 minutes = 3600 seconds + gmtoff -= 3600; } - return mktime(toDateTm()) + gmtoff; + } + return mktime(toDateTm()) + gmtoff; } -} // Tizen -} // Device_API +} // Tizen +} // Device_API diff --git a/src/messaging/MsgCommon/Any.h b/src/messaging/MsgCommon/Any.h index 009ae78..cb05869 100644 --- a/src/messaging/MsgCommon/Any.h +++ b/src/messaging/MsgCommon/Any.h @@ -19,58 +19,58 @@ #include //#include -#include #include +#include #include "common/picojson.h" namespace extension { namespace tizen { enum PrimitiveType { - PrimitiveType_NoType, - PrimitiveType_Null, - PrimitiveType_Boolean, - PrimitiveType_Long, - PrimitiveType_ULong, - PrimitiveType_LongLong, - PrimitiveType_ULongLong, - PrimitiveType_Double, - PrimitiveType_String, - PrimitiveType_Time, - PrimitiveType_Object, - PrimitiveType_PlatformObject + PrimitiveType_NoType, + PrimitiveType_Null, + PrimitiveType_Boolean, + PrimitiveType_Long, + PrimitiveType_ULong, + PrimitiveType_LongLong, + PrimitiveType_ULongLong, + PrimitiveType_Double, + PrimitiveType_String, + PrimitiveType_Time, + PrimitiveType_Object, + PrimitiveType_PlatformObject }; class Any; typedef std::shared_ptr AnyPtr; class Any { -public: - Any(picojson::value value); - virtual ~Any(); + public: + Any(picojson::value value); + virtual ~Any(); -// JSContextRef getContext() const; - picojson::value getValue() const; - void setValue(picojson::value value); + // JSContextRef getContext() const; + picojson::value getValue() const; + void setValue(picojson::value value); - bool isNullOrUndefined() const; + bool isNullOrUndefined() const; - bool toBool() const; - long toLong() const; - unsigned long toULong() const; - long long toLongLong() const; - unsigned long long toULongLong() const; - double toDouble() const; - std::string toString() const; - std::tm* toDateTm() const; - std::time_t toTimeT() const; + bool toBool() const; + long toLong() const; + unsigned long toULong() const; + long long toLongLong() const; + unsigned long long toULongLong() const; + double toDouble() const; + std::string toString() const; + std::tm* toDateTm() const; + std::time_t toTimeT() const; -private: -// JSContextRef m_context; - picojson::value m_value; + private: + // JSContextRef m_context; + picojson::value m_value; }; -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_ANY_H__ +#endif // __TIZEN_TIZEN_ANY_H__ diff --git a/src/messaging/MsgCommon/AttributeFilter.cpp b/src/messaging/MsgCommon/AttributeFilter.cpp old mode 100755 new mode 100644 index e3207f8..2342f5c --- a/src/messaging/MsgCommon/AttributeFilter.cpp +++ b/src/messaging/MsgCommon/AttributeFilter.cpp @@ -15,63 +15,51 @@ */ #include "AttributeFilter.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" namespace extension { namespace tizen { -AttributeFilter::AttributeFilter(const std::string &attribute_name) : - AbstractFilter(ATTRIBUTE_FILTER), - m_attribute_name(attribute_name), - m_match_flag(EXACTLY) -{ +AttributeFilter::AttributeFilter(const std::string &attribute_name) + : AbstractFilter(ATTRIBUTE_FILTER), m_attribute_name(attribute_name), m_match_flag(EXACTLY) { } -AttributeFilter::~AttributeFilter() -{ +AttributeFilter::~AttributeFilter() { } -std::string AttributeFilter::getAttributeName() const -{ - return m_attribute_name; +std::string AttributeFilter::getAttributeName() const { + return m_attribute_name; } -void AttributeFilter::setAttributeName(const std::string &attribute_name) -{ - m_attribute_name = attribute_name; +void AttributeFilter::setAttributeName(const std::string &attribute_name) { + m_attribute_name = attribute_name; } -FilterMatchFlag AttributeFilter::getMatchFlag() const -{ - return m_match_flag; +FilterMatchFlag AttributeFilter::getMatchFlag() const { + return m_match_flag; } -void AttributeFilter::setMatchFlag(FilterMatchFlag match_flag) -{ - m_match_flag = match_flag; +void AttributeFilter::setMatchFlag(FilterMatchFlag match_flag) { + m_match_flag = match_flag; } -AnyPtr AttributeFilter::getMatchValue() const -{ - return m_match_value; +AnyPtr AttributeFilter::getMatchValue() const { + return m_match_value; } -void AttributeFilter::setMatchValue(AnyPtr match_value) -{ - m_match_value = match_value; +void AttributeFilter::setMatchValue(AnyPtr match_value) { + m_match_value = match_value; } -bool AttributeFilter::isMatching(const FilterableObject* const filtered_object) const -{ - if (!filtered_object) { - LoggerE("Invalid object: NULL!"); - return false; - } +bool AttributeFilter::isMatching(const FilterableObject *const filtered_object) const { + if (!filtered_object) { + LoggerE("Invalid object: NULL!"); + return false; + } - return filtered_object->isMatchingAttribute(m_attribute_name, m_match_flag, - m_match_value); + return filtered_object->isMatchingAttribute(m_attribute_name, m_match_flag, m_match_value); } -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/AttributeFilter.h b/src/messaging/MsgCommon/AttributeFilter.h index b14ccbe..0f72188 100644 --- a/src/messaging/MsgCommon/AttributeFilter.h +++ b/src/messaging/MsgCommon/AttributeFilter.h @@ -17,9 +17,9 @@ #ifndef __TIZEN_TIZEN_ATTRIBUTE_FILTER_H__ #define __TIZEN_TIZEN_ATTRIBUTE_FILTER_H__ +#include #include "AbstractFilter.h" #include "Any.h" -#include namespace extension { namespace tizen { @@ -27,26 +27,27 @@ namespace tizen { class AttributeFilter; typedef std::shared_ptr AttributeFilterPtr; -class AttributeFilter: public AbstractFilter { -public: - AttributeFilter(const std::string &attribute_name); - virtual ~AttributeFilter(); - - std::string getAttributeName() const; - void setAttributeName(const std::string &attribute_name); - FilterMatchFlag getMatchFlag() const; - void setMatchFlag(FilterMatchFlag match_flag); - AnyPtr getMatchValue() const; - void setMatchValue(AnyPtr match_value); - - virtual bool isMatching(const FilterableObject* const filtered_object) const; -private: - std::string m_attribute_name; - FilterMatchFlag m_match_flag; - AnyPtr m_match_value; +class AttributeFilter : public AbstractFilter { + public: + AttributeFilter(const std::string &attribute_name); + virtual ~AttributeFilter(); + + std::string getAttributeName() const; + void setAttributeName(const std::string &attribute_name); + FilterMatchFlag getMatchFlag() const; + void setMatchFlag(FilterMatchFlag match_flag); + AnyPtr getMatchValue() const; + void setMatchValue(AnyPtr match_value); + + virtual bool isMatching(const FilterableObject *const filtered_object) const; + + private: + std::string m_attribute_name; + FilterMatchFlag m_match_flag; + AnyPtr m_match_value; }; -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_ABSTRACT_FILTER_H__ +#endif // __TIZEN_TIZEN_ABSTRACT_FILTER_H__ diff --git a/src/messaging/MsgCommon/AttributeRangeFilter.cpp b/src/messaging/MsgCommon/AttributeRangeFilter.cpp old mode 100755 new mode 100644 index 4c30628..242f3ba --- a/src/messaging/MsgCommon/AttributeRangeFilter.cpp +++ b/src/messaging/MsgCommon/AttributeRangeFilter.cpp @@ -13,66 +13,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "AttributeRangeFilter.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" namespace extension { namespace tizen { -AttributeRangeFilter::AttributeRangeFilter(const std::string &attribute_name) : - m_attribute_name(attribute_name) -{ - m_filter_type = ATTRIBUTE_RANGE_FILTER; +AttributeRangeFilter::AttributeRangeFilter(const std::string &attribute_name) + : m_attribute_name(attribute_name) { + m_filter_type = ATTRIBUTE_RANGE_FILTER; } -AttributeRangeFilter::~AttributeRangeFilter() -{ - +AttributeRangeFilter::~AttributeRangeFilter() { } -std::string AttributeRangeFilter::getAttributeName() const -{ - return m_attribute_name; +std::string AttributeRangeFilter::getAttributeName() const { + return m_attribute_name; } -void AttributeRangeFilter::setAttributeName(const std::string &attribute_name) -{ - m_attribute_name = attribute_name; +void AttributeRangeFilter::setAttributeName(const std::string &attribute_name) { + m_attribute_name = attribute_name; } - -AnyPtr AttributeRangeFilter::getInitialValue() const -{ - return m_initial_value; +AnyPtr AttributeRangeFilter::getInitialValue() const { + return m_initial_value; } -void AttributeRangeFilter::setInitialValue(AnyPtr initial_value) -{ - m_initial_value = initial_value; +void AttributeRangeFilter::setInitialValue(AnyPtr initial_value) { + m_initial_value = initial_value; } -AnyPtr AttributeRangeFilter::getEndValue() const -{ - return m_end_value; +AnyPtr AttributeRangeFilter::getEndValue() const { + return m_end_value; } -void AttributeRangeFilter::setEndValue(AnyPtr end_value) -{ - m_end_value = end_value; +void AttributeRangeFilter::setEndValue(AnyPtr end_value) { + m_end_value = end_value; } -bool AttributeRangeFilter::isMatching(const FilterableObject* const filtered_object) const -{ - if (!filtered_object) { - LoggerE("Invalid object: NULL!"); - return false; - } +bool AttributeRangeFilter::isMatching(const FilterableObject *const filtered_object) const { + if (!filtered_object) { + LoggerE("Invalid object: NULL!"); + return false; + } - return filtered_object->isMatchingAttributeRange(m_attribute_name, m_initial_value, - m_end_value); + return filtered_object->isMatchingAttributeRange(m_attribute_name, m_initial_value, m_end_value); } -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/AttributeRangeFilter.h b/src/messaging/MsgCommon/AttributeRangeFilter.h index 4c0d8e1..d847c4c 100644 --- a/src/messaging/MsgCommon/AttributeRangeFilter.h +++ b/src/messaging/MsgCommon/AttributeRangeFilter.h @@ -17,9 +17,9 @@ #ifndef __TIZEN_TIZEN_ATTRIBUTE_RANGE_FILTER_H__ #define __TIZEN_TIZEN_ATTRIBUTE_RANGE_FILTER_H__ +#include #include "AbstractFilter.h" #include "Any.h" -#include namespace extension { namespace tizen { @@ -27,28 +27,29 @@ namespace tizen { class AttributeRangeFilter; typedef std::shared_ptr AttributeRangeFilterPtr; -class AttributeRangeFilter: public AbstractFilter { -public: - AttributeRangeFilter(const std::string &attribute_name); - virtual ~AttributeRangeFilter(); +class AttributeRangeFilter : public AbstractFilter { + public: + AttributeRangeFilter(const std::string &attribute_name); + virtual ~AttributeRangeFilter(); + + std::string getAttributeName() const; + void setAttributeName(const std::string &attribute_name); - std::string getAttributeName() const; - void setAttributeName(const std::string &attribute_name); + AnyPtr getInitialValue() const; + void setInitialValue(AnyPtr initial_value); - AnyPtr getInitialValue() const; - void setInitialValue(AnyPtr initial_value); + AnyPtr getEndValue() const; + void setEndValue(AnyPtr end_value); - AnyPtr getEndValue() const; - void setEndValue(AnyPtr end_value); + virtual bool isMatching(const FilterableObject *const filtered_object) const; - virtual bool isMatching(const FilterableObject* const filtered_object) const; -private: - std::string m_attribute_name; - AnyPtr m_initial_value; - AnyPtr m_end_value; + private: + std::string m_attribute_name; + AnyPtr m_initial_value; + AnyPtr m_end_value; }; -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_ATTRIBUTE_RANGE_FILTER_H__ +#endif // __TIZEN_TIZEN_ATTRIBUTE_RANGE_FILTER_H__ diff --git a/src/messaging/MsgCommon/CompositeFilter.cpp b/src/messaging/MsgCommon/CompositeFilter.cpp old mode 100755 new mode 100644 index ea68e7e..3f5b352 --- a/src/messaging/MsgCommon/CompositeFilter.cpp +++ b/src/messaging/MsgCommon/CompositeFilter.cpp @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "CompositeFilter.h" #include "common/platform_exception.h" //#include @@ -22,77 +22,68 @@ namespace extension { namespace tizen { -CompositeFilter::CompositeFilter(CompositeFilterType type): - AbstractFilter(COMPOSITE_FILTER), - m_type(type) +CompositeFilter::CompositeFilter(CompositeFilterType type) + : AbstractFilter(COMPOSITE_FILTER), + m_type(type) // m_context(NULL) { } -CompositeFilter::~CompositeFilter() -{ +CompositeFilter::~CompositeFilter() { } -CompositeFilterType CompositeFilter::getType() const -{ - return m_type; +CompositeFilterType CompositeFilter::getType() const { + return m_type; } -void CompositeFilter::setType(CompositeFilterType type) -{ - m_type = type; +void CompositeFilter::setType(CompositeFilterType type) { + m_type = type; } -//JSContextRef CompositeFilter::getContext() const +// JSContextRef CompositeFilter::getContext() const //{ // return m_context; //} -const AbstractFilterPtrVector& CompositeFilter::getFilters() const -{ - return m_filters; +const AbstractFilterPtrVector& CompositeFilter::getFilters() const { + return m_filters; } -void CompositeFilter::addFilter(const AbstractFilterPtr& filter) -{ - m_filters.push_back(filter); +void CompositeFilter::addFilter(const AbstractFilterPtr& filter) { + m_filters.push_back(filter); } -bool CompositeFilter::isMatching(const FilterableObject* const filtered_object) const -{ - if (!filtered_object) { - LoggerE("Invalid object: NULL!"); - return false; - } +bool CompositeFilter::isMatching(const FilterableObject* const filtered_object) const { + if (!filtered_object) { + LoggerE("Invalid object: NULL!"); + return false; + } - bool composite_result = false; + bool composite_result = false; - const AbstractFilterPtrVector src_filters = getFilters(); - if(src_filters.empty()) { - //No filters present -> object match composite filter - composite_result = true; - } - else { - AbstractFilterPtrVector::const_iterator it = src_filters.begin(); - AbstractFilterPtrVector::const_iterator end_it = src_filters.end(); - for(;it != end_it; ++it) { - - const bool last_result = (*it)->isMatching(filtered_object); - if(INTERSECTION == m_type) { - composite_result = last_result; - if(!last_result) { //First false result causes whole composite - break; //filter to be false -> object does not match - } - } else if(UNION == m_type && last_result) { //First true result causes - composite_result = true; //composite filter to be - break; //true -> object match - } + const AbstractFilterPtrVector src_filters = getFilters(); + if (src_filters.empty()) { + // No filters present -> object match composite filter + composite_result = true; + } else { + AbstractFilterPtrVector::const_iterator it = src_filters.begin(); + AbstractFilterPtrVector::const_iterator end_it = src_filters.end(); + for (; it != end_it; ++it) { + const bool last_result = (*it)->isMatching(filtered_object); + if (INTERSECTION == m_type) { + composite_result = last_result; + if (!last_result) { // First false result causes whole composite + break; // filter to be false -> object does not match } + } else if (UNION == m_type && last_result) { // First true result causes + composite_result = true; // composite filter to be + break; // true -> object match + } } + } - return composite_result; + return composite_result; } - -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/CompositeFilter.h b/src/messaging/MsgCommon/CompositeFilter.h index e6d2c32..3b05b84 100644 --- a/src/messaging/MsgCommon/CompositeFilter.h +++ b/src/messaging/MsgCommon/CompositeFilter.h @@ -22,31 +22,29 @@ namespace extension { namespace tizen { -enum CompositeFilterType { - UNION, - INTERSECTION -}; +enum CompositeFilterType { UNION, INTERSECTION }; class CompositeFilter; typedef std::shared_ptr CompositeFilterPtr; -class CompositeFilter: public AbstractFilter { -public: - CompositeFilter(CompositeFilterType type); - virtual ~CompositeFilter(); +class CompositeFilter : public AbstractFilter { + public: + CompositeFilter(CompositeFilterType type); + virtual ~CompositeFilter(); + + CompositeFilterType getType() const; + void setType(CompositeFilterType type); + const AbstractFilterPtrVector& getFilters() const; + void addFilter(const AbstractFilterPtr& filter); - CompositeFilterType getType() const; - void setType(CompositeFilterType type); - const AbstractFilterPtrVector& getFilters() const; - void addFilter(const AbstractFilterPtr& filter); + virtual bool isMatching(const FilterableObject* const filtered_object) const; - virtual bool isMatching(const FilterableObject* const filtered_object) const; -private: - CompositeFilterType m_type; - AbstractFilterPtrVector m_filters; + private: + CompositeFilterType m_type; + AbstractFilterPtrVector m_filters; }; -} //Tizen -} //DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_COMPOSITE_FILTER_H__ +#endif // __TIZEN_TIZEN_COMPOSITE_FILTER_H__ diff --git a/src/messaging/MsgCommon/FilterIterator.cpp b/src/messaging/MsgCommon/FilterIterator.cpp old mode 100755 new mode 100644 index 1ec3427..4430f7d --- a/src/messaging/MsgCommon/FilterIterator.cpp +++ b/src/messaging/MsgCommon/FilterIterator.cpp @@ -13,166 +13,144 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "FilterIterator.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" using namespace common; namespace extension { namespace tizen { -FilterIterator::FilterIterator(AbstractFilterPtr filter) : - m_root_filter(filter), - m_current_state(FIS_NOT_VALID) -{ - if (!m_root_filter) { - LoggerE("Trying to create FilterIterator with NULL filter"); - m_root_filter = AbstractFilterPtr(new AbstractFilter()); - } +FilterIterator::FilterIterator(AbstractFilterPtr filter) + : m_root_filter(filter), m_current_state(FIS_NOT_VALID) { + if (!m_root_filter) { + LoggerE("Trying to create FilterIterator with NULL filter"); + m_root_filter = AbstractFilterPtr(new AbstractFilter()); + } - goToNext(m_root_filter); + goToNext(m_root_filter); } -FilterIteratorState FilterIterator::getState() const -{ - return m_current_state; +FilterIteratorState FilterIterator::getState() const { + return m_current_state; } -AbstractFilterPtr FilterIterator::operator*() const -{ - return m_current_filter; +AbstractFilterPtr FilterIterator::operator*() const { + return m_current_filter; } -AbstractFilterPtr FilterIterator::getCurrentFilter() const -{ - return m_current_filter; +AbstractFilterPtr FilterIterator::getCurrentFilter() const { + return m_current_filter; } -bool FilterIterator::isEnd() const -{ - return FIS_END == m_current_state; +bool FilterIterator::isEnd() const { + return FIS_END == m_current_state; } -bool FilterIterator::isInsideCompositeFilter() const -{ - return !m_composite_stack.empty(); +bool FilterIterator::isInsideCompositeFilter() const { + return !m_composite_stack.empty(); } -CompositeFilterPtr FilterIterator::getCurrentCompositeFilter() const -{ - if(m_composite_stack.empty()) { - return CompositeFilterPtr(); - } +CompositeFilterPtr FilterIterator::getCurrentCompositeFilter() const { + if (m_composite_stack.empty()) { + return CompositeFilterPtr(); + } - return m_composite_stack.top().filter; + return m_composite_stack.top().filter; } -int FilterIterator::getCurrentCompositeSubFilterIndex() const -{ - if(!isInsideCompositeFilter()) { - return 0; - } +int FilterIterator::getCurrentCompositeSubFilterIndex() const { + if (!isInsideCompositeFilter()) { + return 0; + } - return m_composite_stack.top().cur_sub_filter_index; + return m_composite_stack.top().cur_sub_filter_index; } -bool FilterIterator::isLastCompositeSubFilter() const -{ - if(!isInsideCompositeFilter()) { - return false; - } +bool FilterIterator::isLastCompositeSubFilter() const { + if (!isInsideCompositeFilter()) { + return false; + } - CompositeIterState cfilter = m_composite_stack.top(); - return (int)(cfilter.filter->getFilters().size() - 1) == cfilter.cur_sub_filter_index; + CompositeIterState cfilter = m_composite_stack.top(); + return (int)(cfilter.filter->getFilters().size() - 1) == cfilter.cur_sub_filter_index; } -void FilterIterator::operator++(int) -{ - this->operator++(); +void FilterIterator::operator++(int) { + this->operator++(); } -void FilterIterator::operator++() -{ - if(FIS_ATTRIBUTE_FILTER == m_current_state || - FIS_ATTRIBUTE_RANGE_FILTER == m_current_state) { - - if(m_composite_stack.empty()) { - //We are not inside composite filter iteration -> reached THE END - setReachedEnd(); - } else { - //We are inside a composite filter -> try move to next sub filter - goToNextInCurCompositeFilter(); - } +void FilterIterator::operator++() { + if (FIS_ATTRIBUTE_FILTER == m_current_state || FIS_ATTRIBUTE_RANGE_FILTER == m_current_state) { + if (m_composite_stack.empty()) { + // We are not inside composite filter iteration -> reached THE END + setReachedEnd(); + } else { + // We are inside a composite filter -> try move to next sub filter + goToNextInCurCompositeFilter(); } - else if(FIS_COMPOSITE_START == m_current_state) { - goToNextInCurCompositeFilter(); - } - else if(FIS_COMPOSITE_END == m_current_state) { - m_composite_stack.pop(); - if(m_composite_stack.empty()) { - //There is no parent composite filter -> reached THE END - setReachedEnd(); - } - else { - //There is parent composite filter -> go back and try move to next sub filter - goToNextInCurCompositeFilter(); - } - } - else if(FIS_NOT_VALID == m_current_state) { - //There is nothing to do -> reached THE END - setReachedEnd(); + } else if (FIS_COMPOSITE_START == m_current_state) { + goToNextInCurCompositeFilter(); + } else if (FIS_COMPOSITE_END == m_current_state) { + m_composite_stack.pop(); + if (m_composite_stack.empty()) { + // There is no parent composite filter -> reached THE END + setReachedEnd(); + } else { + // There is parent composite filter -> go back and try move to next sub filter + goToNextInCurCompositeFilter(); } + } else if (FIS_NOT_VALID == m_current_state) { + // There is nothing to do -> reached THE END + setReachedEnd(); + } } -void FilterIterator::goToNextInCurCompositeFilter() -{ - CompositeIterState& cur_cs = m_composite_stack.top(); - AbstractFilterPtrVector sub_filters = cur_cs.filter->getFilters(); - const size_t next_filter_index = cur_cs.cur_sub_filter_index + 1; - if(next_filter_index >= sub_filters.size()) { - //Reached last item of composite filter - m_current_filter = cur_cs.filter; - m_current_state = FIS_COMPOSITE_END; - } - else { - cur_cs.cur_sub_filter_index = next_filter_index; - //There is next item inside this composite filter - goToNext(sub_filters[next_filter_index]); - } +void FilterIterator::goToNextInCurCompositeFilter() { + CompositeIterState& cur_cs = m_composite_stack.top(); + AbstractFilterPtrVector sub_filters = cur_cs.filter->getFilters(); + const size_t next_filter_index = cur_cs.cur_sub_filter_index + 1; + if (next_filter_index >= sub_filters.size()) { + // Reached last item of composite filter + m_current_filter = cur_cs.filter; + m_current_state = FIS_COMPOSITE_END; + } else { + cur_cs.cur_sub_filter_index = next_filter_index; + // There is next item inside this composite filter + goToNext(sub_filters[next_filter_index]); + } } -void FilterIterator::setReachedEnd() -{ - m_current_state = FIS_END; - m_current_filter = AbstractFilterPtr(); +void FilterIterator::setReachedEnd() { + m_current_state = FIS_END; + m_current_filter = AbstractFilterPtr(); } -void FilterIterator::goToNext(AbstractFilterPtr next) -{ - switch(next->getFilterType()) { - case ATTRIBUTE_FILTER: { - m_current_state = FIS_ATTRIBUTE_FILTER; - } break; - case ATTRIBUTE_RANGE_FILTER: { - m_current_state = FIS_ATTRIBUTE_RANGE_FILTER; - } break; - case COMPOSITE_FILTER: { - m_current_state = FIS_COMPOSITE_START; - CompositeIterState cf_state; - cf_state.filter = castToCompositeFilter(next); - cf_state.cur_sub_filter_index = -1; - m_composite_stack.push(cf_state); - } break; - case ABSTRACT_FILTER: { - LoggerE("Reached AbstractFilter!!"); - m_current_state = FIS_NOT_VALID; - } break; - } - - m_current_filter = next; +void FilterIterator::goToNext(AbstractFilterPtr next) { + switch (next->getFilterType()) { + case ATTRIBUTE_FILTER: { + m_current_state = FIS_ATTRIBUTE_FILTER; + } break; + case ATTRIBUTE_RANGE_FILTER: { + m_current_state = FIS_ATTRIBUTE_RANGE_FILTER; + } break; + case COMPOSITE_FILTER: { + m_current_state = FIS_COMPOSITE_START; + CompositeIterState cf_state; + cf_state.filter = castToCompositeFilter(next); + cf_state.cur_sub_filter_index = -1; + m_composite_stack.push(cf_state); + } break; + case ABSTRACT_FILTER: { + LoggerE("Reached AbstractFilter!!"); + m_current_state = FIS_NOT_VALID; + } break; + } + + m_current_filter = next; } -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/FilterIterator.h b/src/messaging/MsgCommon/FilterIterator.h index a3d92d0..05df7cd 100644 --- a/src/messaging/MsgCommon/FilterIterator.h +++ b/src/messaging/MsgCommon/FilterIterator.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __TIZEN_TIZEN_FILTER_ITERATOR_H__ #define __TIZEN_TIZEN_FILTER_ITERATOR_H__ @@ -28,69 +28,66 @@ namespace extension { namespace tizen { enum FilterIteratorState { - FIS_NOT_VALID = 0, - FIS_ATTRIBUTE_FILTER, - FIS_ATTRIBUTE_RANGE_FILTER, - FIS_COMPOSITE_START, - FIS_COMPOSITE_END, - FIS_END + FIS_NOT_VALID = 0, + FIS_ATTRIBUTE_FILTER, + FIS_ATTRIBUTE_RANGE_FILTER, + FIS_COMPOSITE_START, + FIS_COMPOSITE_END, + FIS_END }; -class FilterIterator -{ -public: - FilterIterator(AbstractFilterPtr filter); - - FilterIteratorState getState() const; - AbstractFilterPtr operator*() const; - AbstractFilterPtr getCurrentFilter() const; - bool isEnd() const; - - bool isInsideCompositeFilter() const; - - /** - * Returns null shared pointer if we are not inside composite filter - */ - CompositeFilterPtr getCurrentCompositeFilter() const; - - /** - * Get index of current sub filter (inside composite filter) - * Returns 0 if we are not inside composite filter. - */ - int getCurrentCompositeSubFilterIndex() const; - - /** - * Return true if current sub filter is the last one in current composite filter - * Returns false if we are not inside composite filter. - */ - bool isLastCompositeSubFilter() const; - - void operator++(); - void operator++(int); - -private: - void setReachedEnd(); - void goToNext(AbstractFilterPtr next); - void goToNextInCurCompositeFilter(); - - AbstractFilterPtr m_root_filter; - FilterIteratorState m_current_state; - AbstractFilterPtr m_current_filter; - - struct CompositeIterState { - CompositeIterState() : - cur_sub_filter_index(0) - { - } - - CompositeFilterPtr filter; - int cur_sub_filter_index; - }; - - std::stack m_composite_stack; +class FilterIterator { + public: + FilterIterator(AbstractFilterPtr filter); + + FilterIteratorState getState() const; + AbstractFilterPtr operator*() const; + AbstractFilterPtr getCurrentFilter() const; + bool isEnd() const; + + bool isInsideCompositeFilter() const; + + /** + * Returns null shared pointer if we are not inside composite filter + */ + CompositeFilterPtr getCurrentCompositeFilter() const; + + /** + * Get index of current sub filter (inside composite filter) + * Returns 0 if we are not inside composite filter. + */ + int getCurrentCompositeSubFilterIndex() const; + + /** + * Return true if current sub filter is the last one in current composite filter + * Returns false if we are not inside composite filter. + */ + bool isLastCompositeSubFilter() const; + + void operator++(); + void operator++(int); + + private: + void setReachedEnd(); + void goToNext(AbstractFilterPtr next); + void goToNextInCurCompositeFilter(); + + AbstractFilterPtr m_root_filter; + FilterIteratorState m_current_state; + AbstractFilterPtr m_current_filter; + + struct CompositeIterState { + CompositeIterState() : cur_sub_filter_index(0) { + } + + CompositeFilterPtr filter; + int cur_sub_filter_index; + }; + + std::stack m_composite_stack; }; -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_FILTER_ITERATOR_H__ +#endif // __TIZEN_TIZEN_FILTER_ITERATOR_H__ diff --git a/src/messaging/MsgCommon/SortMode.cpp b/src/messaging/MsgCommon/SortMode.cpp old mode 100755 new mode 100644 index 6c2e36d..e81b595 --- a/src/messaging/MsgCommon/SortMode.cpp +++ b/src/messaging/MsgCommon/SortMode.cpp @@ -21,38 +21,30 @@ namespace extension { namespace tizen { -SortMode::SortMode(const std::string &attribute_name, SortModeOrder order) : - m_attribute_name(attribute_name), - m_order(order) -{ - LoggerD("SortMode attributeName: %s, SortMode order: %s", - attribute_name.c_str(), (order == SortModeOrder::DESC) ? "DESC" : "ASC"); +SortMode::SortMode(const std::string &attribute_name, SortModeOrder order) + : m_attribute_name(attribute_name), m_order(order) { + LoggerD("SortMode attributeName: %s, SortMode order: %s", attribute_name.c_str(), + (order == SortModeOrder::DESC) ? "DESC" : "ASC"); } -SortMode::~SortMode() -{ - +SortMode::~SortMode() { } -std::string SortMode::getAttributeName() const -{ - return m_attribute_name; +std::string SortMode::getAttributeName() const { + return m_attribute_name; } -void SortMode::setAttributeName(const std::string &attribute_name) -{ - m_attribute_name = attribute_name; +void SortMode::setAttributeName(const std::string &attribute_name) { + m_attribute_name = attribute_name; } -SortModeOrder SortMode::getOrder() const -{ - return m_order; +SortModeOrder SortMode::getOrder() const { + return m_order; } -void SortMode::setOrder(SortModeOrder order) -{ - m_order = order; +void SortMode::setOrder(SortModeOrder order) { + m_order = order; } -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI diff --git a/src/messaging/MsgCommon/SortMode.h b/src/messaging/MsgCommon/SortMode.h index d9491b1..1cd8cbb 100644 --- a/src/messaging/MsgCommon/SortMode.h +++ b/src/messaging/MsgCommon/SortMode.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __TIZEN_TIZEN_SORT_MODE_H__ #define __TIZEN_TIZEN_SORT_MODE_H__ @@ -26,27 +26,24 @@ namespace tizen { class SortMode; typedef std::shared_ptr SortModePtr; -enum SortModeOrder { - ASC, - DESC -}; +enum SortModeOrder { ASC, DESC }; class SortMode { -public: - SortMode(const std::string &attribute_name, SortModeOrder order); - virtual ~SortMode(); - - std::string getAttributeName() const; - void setAttributeName(const std::string &attribute_name); - SortModeOrder getOrder() const; - void setOrder(SortModeOrder order); - -private: - std::string m_attribute_name; - SortModeOrder m_order; + public: + SortMode(const std::string &attribute_name, SortModeOrder order); + virtual ~SortMode(); + + std::string getAttributeName() const; + void setAttributeName(const std::string &attribute_name); + SortModeOrder getOrder() const; + void setOrder(SortModeOrder order); + + private: + std::string m_attribute_name; + SortModeOrder m_order; }; -} // Tizen -} // DeviceAPI +} // Tizen +} // DeviceAPI -#endif // __TIZEN_TIZEN_SORT_MODE_H__ +#endif // __TIZEN_TIZEN_SORT_MODE_H__ diff --git a/src/messaging/change_listener_container.cc b/src/messaging/change_listener_container.cc old mode 100755 new mode 100644 index feabe1f..e530397 --- a/src/messaging/change_listener_container.cc +++ b/src/messaging/change_listener_container.cc @@ -167,8 +167,7 @@ class ChangeListenerContainer::ChangeListeners { bool HasListeners() const { LoggerD("Entered"); - return message_callbacks_.HasListeners() || - conversation_callbacks_.HasListeners() || + return message_callbacks_.HasListeners() || conversation_callbacks_.HasListeners() || folder_callbacks_.HasListeners(); } @@ -212,14 +211,13 @@ ChangeListenerContainer::ChangeListeners::ListenerGroup::Get struct CallbackDataHolder { +template +struct CallbackDataHolder { std::shared_ptr ptr; int operation_type; }; @@ -94,8 +95,7 @@ class ChangeListenerContainer { std::shared_ptr listeners_; }; - } // namespace messaging } // namespace extension -#endif // __TIZEN_CHANGE_LISTENER_CONTAINER_H__ +#endif // __TIZEN_CHANGE_LISTENER_CONTAINER_H__ diff --git a/src/messaging/conversation_callback_data.cc b/src/messaging/conversation_callback_data.cc old mode 100755 new mode 100644 index 18a917c..8f68409 --- a/src/messaging/conversation_callback_data.cc +++ b/src/messaging/conversation_callback_data.cc @@ -20,88 +20,76 @@ namespace extension { namespace messaging { -ConversationCallbackData::ConversationCallbackData(PostQueue& queue, long cid, bool keep /* = false */) : - CallbackUserData(queue, cid, keep), - m_limit(0), - m_offset(0), - m_account_id(0), - m_service_type(UNDEFINED) { +ConversationCallbackData::ConversationCallbackData(PostQueue& queue, long cid, + bool keep /* = false */) + : CallbackUserData(queue, cid, keep), + m_limit(0), + m_offset(0), + m_account_id(0), + m_service_type(UNDEFINED) { LoggerD("Entered"); } -ConversationCallbackData::~ConversationCallbackData() -{ - LoggerD("Entered"); +ConversationCallbackData::~ConversationCallbackData() { + LoggerD("Entered"); } -void ConversationCallbackData::setFilter(AbstractFilterPtr filter) -{ - m_filter = filter; +void ConversationCallbackData::setFilter(AbstractFilterPtr filter) { + m_filter = filter; } -void ConversationCallbackData::setSortMode(SortModePtr sortMode) -{ - m_sort = sortMode; +void ConversationCallbackData::setSortMode(SortModePtr sortMode) { + m_sort = sortMode; } -void ConversationCallbackData::setLimit(long limit) -{ - m_limit = limit; +void ConversationCallbackData::setLimit(long limit) { + m_limit = limit; } -void ConversationCallbackData::setOffset(long offset) -{ - m_offset = offset; +void ConversationCallbackData::setOffset(long offset) { + m_offset = offset; } -void ConversationCallbackData::addConversation(std::shared_ptr msg) -{ - m_conversations.push_back(msg); +void ConversationCallbackData::addConversation(std::shared_ptr msg) { + m_conversations.push_back(msg); } -std::vector> ConversationCallbackData::getConversations() const -{ - return m_conversations; +std::vector> ConversationCallbackData::getConversations() + const { + return m_conversations; } -void ConversationCallbackData::setAccountId(int account_id){ - m_account_id = account_id; +void ConversationCallbackData::setAccountId(int account_id) { + m_account_id = account_id; } -int ConversationCallbackData::getAccountId() const -{ - return m_account_id; +int ConversationCallbackData::getAccountId() const { + return m_account_id; } -void ConversationCallbackData::setMessageServiceType(MessageType m_msg_type) -{ - m_service_type = m_msg_type; +void ConversationCallbackData::setMessageServiceType(MessageType m_msg_type) { + m_service_type = m_msg_type; } -MessageType ConversationCallbackData::getMessageServiceType() const -{ - return m_service_type; +MessageType ConversationCallbackData::getMessageServiceType() const { + return m_service_type; } -AbstractFilterPtr ConversationCallbackData::getFilter() const -{ - return m_filter; +AbstractFilterPtr ConversationCallbackData::getFilter() const { + return m_filter; } -SortModePtr ConversationCallbackData::getSortMode() const -{ - return m_sort; +SortModePtr ConversationCallbackData::getSortMode() const { + return m_sort; } -long ConversationCallbackData::getLimit() const -{ - return m_limit; +long ConversationCallbackData::getLimit() const { + return m_limit; } -long ConversationCallbackData::getOffset() const -{ - return m_offset; +long ConversationCallbackData::getOffset() const { + return m_offset; } -}//messaging -}//extension +} // messaging +} // extension diff --git a/src/messaging/conversation_callback_data.h b/src/messaging/conversation_callback_data.h index 9d82d82..2bbfb8c 100644 --- a/src/messaging/conversation_callback_data.h +++ b/src/messaging/conversation_callback_data.h @@ -21,9 +21,9 @@ #include #include -#include "messaging/callback_user_data.h" #include "MsgCommon/AttributeFilter.h" #include "MsgCommon/SortMode.h" +#include "messaging/callback_user_data.h" #include "messaging_util.h" using namespace extension::tizen; @@ -35,39 +35,39 @@ class Message; class MessageConversation; class ConversationCallbackData : public CallbackUserData { -public: - ConversationCallbackData(PostQueue& queue, long cid, bool keep = false); - virtual ~ConversationCallbackData(); + public: + ConversationCallbackData(PostQueue& queue, long cid, bool keep = false); + virtual ~ConversationCallbackData(); - void setFilter(AbstractFilterPtr filter); - void setSortMode(SortModePtr sortMode); - void setLimit(long limit); - void setOffset(long offset); - void addConversation(std::shared_ptr msg); + void setFilter(AbstractFilterPtr filter); + void setSortMode(SortModePtr sortMode); + void setLimit(long limit); + void setOffset(long offset); + void addConversation(std::shared_ptr msg); - std::vector> getConversations() const; + std::vector> getConversations() const; - void setAccountId(int account_id); - int getAccountId() const; + void setAccountId(int account_id); + int getAccountId() const; - void setMessageServiceType(MessageType m_msg_type); - MessageType getMessageServiceType() const; - AbstractFilterPtr getFilter() const; - SortModePtr getSortMode() const; - long getLimit() const; - long getOffset() const; + void setMessageServiceType(MessageType m_msg_type); + MessageType getMessageServiceType() const; + AbstractFilterPtr getFilter() const; + SortModePtr getSortMode() const; + long getLimit() const; + long getOffset() const; -private: - AbstractFilterPtr m_filter; - SortModePtr m_sort; - long m_limit; - long m_offset; - std::vector> m_conversations; - int m_account_id; - MessageType m_service_type; + private: + AbstractFilterPtr m_filter; + SortModePtr m_sort; + long m_limit; + long m_offset; + std::vector> m_conversations; + int m_account_id; + MessageType m_service_type; }; -}//messaging -}//extension +} // messaging +} // extension -#endif // MESSAGING_CONVERSATION_CALLBACK_DATA_H_ +#endif // MESSAGING_CONVERSATION_CALLBACK_DATA_H_ diff --git a/src/messaging/conversations_change_callback.cc b/src/messaging/conversations_change_callback.cc old mode 100755 new mode 100644 index 95d75f3..e84428f --- a/src/messaging/conversations_change_callback.cc +++ b/src/messaging/conversations_change_callback.cc @@ -34,187 +34,163 @@ namespace extension { namespace messaging { - const char* CONVERSATIONSADDED = "conversationsadded"; const char* CONVERSATIONSUPDATED = "conversationsupdated"; const char* CONVERSATIONSREMOVED = "conversationsremoved"; -ConversationsChangeCallback::ConversationsChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue) : - m_callback_data(queue, cid, true), - m_id(service_id), - m_msg_type(service_type), - m_is_act(true) -{ - LoggerD("Entered"); - m_callback_data.SetListenerId("ConversationsChangeListener"); +ConversationsChangeCallback::ConversationsChangeCallback(long cid, int service_id, + MessageType service_type, PostQueue& queue) + : m_callback_data(queue, cid, true), + m_id(service_id), + m_msg_type(service_type), + m_is_act(true) { + LoggerD("Entered"); + m_callback_data.SetListenerId("ConversationsChangeListener"); } -ConversationsChangeCallback::~ConversationsChangeCallback() -{ - LoggerD("Entered"); +ConversationsChangeCallback::~ConversationsChangeCallback() { + LoggerD("Entered"); } ConversationPtrVector ConversationsChangeCallback::filterConversations( - AbstractFilterPtr filter, - const ConversationPtrVector& source_conversations) -{ - LoggerD("Entered"); - if (filter) { - LoggerD("filter pointer is valid"); - ConversationPtrVector filtered_conversations; - ConversationPtrVector::const_iterator it = source_conversations.begin(); - ConversationPtrVector::const_iterator end_it = source_conversations.end(); - - for(int i = 0; it != end_it; ++i, ++it) { - const ConversationPtr& conversation = *it; - const bool matched = filter->isMatching(conversation.get()); - if(matched) { - filtered_conversations.push_back(conversation); - } - - LoggerD("[%d] conversation id:%d", i, conversation->getConversationId()); - LoggerD("[%d] conversation subject :%s", i, conversation->getSubject().c_str()); - LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); - } - - LoggerD("returning matching %d of %d conversations", filtered_conversations.size(), - source_conversations.size()); - - return filtered_conversations; - } - else { - LoggerD("filter pointer is not valid"); - return source_conversations; + AbstractFilterPtr filter, const ConversationPtrVector& source_conversations) { + LoggerD("Entered"); + if (filter) { + LoggerD("filter pointer is valid"); + ConversationPtrVector filtered_conversations; + ConversationPtrVector::const_iterator it = source_conversations.begin(); + ConversationPtrVector::const_iterator end_it = source_conversations.end(); + + for (int i = 0; it != end_it; ++i, ++it) { + const ConversationPtr& conversation = *it; + const bool matched = filter->isMatching(conversation.get()); + if (matched) { + filtered_conversations.push_back(conversation); + } + + LoggerD("[%d] conversation id:%d", i, conversation->getConversationId()); + LoggerD("[%d] conversation subject :%s", i, conversation->getSubject().c_str()); + LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); } + + LoggerD("returning matching %d of %d conversations", filtered_conversations.size(), + source_conversations.size()); + + return filtered_conversations; + } else { + LoggerD("filter pointer is not valid"); + return source_conversations; + } } -void ConversationsChangeCallback::added( - const ConversationPtrVector& conversations) -{ - LoggerD("Entered conversations.size()=%d", conversations.size()); - if (!m_is_act) { - return; - } +void ConversationsChangeCallback::added(const ConversationPtrVector& conversations) { + LoggerD("Entered conversations.size()=%d", conversations.size()); + if (!m_is_act) { + return; + } - ConversationPtrVector filtered = filterConversations(m_filter, conversations); + ConversationPtrVector filtered = filterConversations(m_filter, conversations); - //if filter is set but there is no conversation matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no conversation matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr c)->void { - array.push_back(MessagingUtil::conversationToJson(c)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr c) -> void { + array.push_back(MessagingUtil::conversationToJson(c)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSADDED, - filtered.size()); + LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSADDED, filtered.size()); - m_callback_data.SetAction(CONVERSATIONSADDED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::MEDIUM); + m_callback_data.SetAction(CONVERSATIONSADDED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::MEDIUM); } -void ConversationsChangeCallback::updated( - const ConversationPtrVector& conversations) -{ - LoggerD("Entered conversations.size()=%d", conversations.size()); - if (!m_is_act) { - return; - } +void ConversationsChangeCallback::updated(const ConversationPtrVector& conversations) { + LoggerD("Entered conversations.size()=%d", conversations.size()); + if (!m_is_act) { + return; + } - ConversationPtrVector filtered = filterConversations(m_filter, conversations); + ConversationPtrVector filtered = filterConversations(m_filter, conversations); - //if filter is set but there is no conversation matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no conversation matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr c)->void { - array.push_back(MessagingUtil::conversationToJson(c)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr c) -> void { + array.push_back(MessagingUtil::conversationToJson(c)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSUPDATED, - filtered.size()); + LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSUPDATED, filtered.size()); - m_callback_data.SetAction(CONVERSATIONSUPDATED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LOW); + m_callback_data.SetAction(CONVERSATIONSUPDATED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LOW); } -void ConversationsChangeCallback::removed( - const ConversationPtrVector& conversations) -{ - LoggerD("Entered conversations.size()=%d", conversations.size()); - if (!m_is_act) { - return; - } +void ConversationsChangeCallback::removed(const ConversationPtrVector& conversations) { + LoggerD("Entered conversations.size()=%d", conversations.size()); + if (!m_is_act) { + return; + } - ConversationPtrVector filtered = filterConversations(m_filter, conversations); + ConversationPtrVector filtered = filterConversations(m_filter, conversations); - //if filter is set but there is no conversation matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no conversation matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr c)->void { - array.push_back(MessagingUtil::conversationToJson(c)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr c) -> void { + array.push_back(MessagingUtil::conversationToJson(c)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSREMOVED, - filtered.size()); + LoggerD("Calling:%s with:%d added conversations", CONVERSATIONSREMOVED, filtered.size()); - m_callback_data.SetAction(CONVERSATIONSREMOVED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LAST); + m_callback_data.SetAction(CONVERSATIONSREMOVED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LAST); } -void ConversationsChangeCallback::setFilter(tizen::AbstractFilterPtr filter) -{ - m_filter = filter; +void ConversationsChangeCallback::setFilter(tizen::AbstractFilterPtr filter) { + m_filter = filter; } -tizen::AbstractFilterPtr ConversationsChangeCallback::getFilter() const -{ - return m_filter; +tizen::AbstractFilterPtr ConversationsChangeCallback::getFilter() const { + return m_filter; } -int ConversationsChangeCallback::getServiceId() const -{ - return m_id; +int ConversationsChangeCallback::getServiceId() const { + return m_id; } -MessageType ConversationsChangeCallback::getServiceType() const -{ - return m_msg_type; +MessageType ConversationsChangeCallback::getServiceType() const { + return m_msg_type; } void ConversationsChangeCallback::setActive(bool act) { - m_is_act = act; + m_is_act = act; } bool ConversationsChangeCallback::isActive() { - return m_is_act; + return m_is_act; } -void ConversationsChangeCallback::setItems(ConversationPtrVector& items) -{ - m_items = items; +void ConversationsChangeCallback::setItems(ConversationPtrVector& items) { + m_items = items; } -ConversationPtrVector ConversationsChangeCallback::getItems() -{ - return m_items; +ConversationPtrVector ConversationsChangeCallback::getItems() { + return m_items; } -} //namespace messaging -} //namespace extension +} // namespace messaging +} // namespace extension diff --git a/src/messaging/conversations_change_callback.h b/src/messaging/conversations_change_callback.h index ca71198..e3edfdb 100644 --- a/src/messaging/conversations_change_callback.h +++ b/src/messaging/conversations_change_callback.h @@ -30,49 +30,42 @@ extern const char* CONVERSATIONSUPDATED; extern const char* CONVERSATIONSREMOVED; class ConversationsChangeCallback { -public: - typedef void(ConversationsChangeCallback::*Signature)(const ConversationPtrVector& conversations); - - ConversationsChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue); - virtual ~ConversationsChangeCallback(); - - void added(const ConversationPtrVector& conversations); - void updated(const ConversationPtrVector& conversations); - void removed(const ConversationPtrVector& conversations); - - void setFilter(tizen::AbstractFilterPtr filter); - tizen::AbstractFilterPtr getFilter() const; - - int getServiceId() const; - MessageType getServiceType() const; - - void setActive(bool act); - bool isActive(); - - void setItems(ConversationPtrVector& items); - ConversationPtrVector getItems(); -private: - static ConversationPtrVector filterConversations( - tizen::AbstractFilterPtr a_filter, - const ConversationPtrVector& a_sourceConversations); - - ConversationCallbackData m_callback_data; - tizen::AbstractFilterPtr m_filter; - int m_id; - MessageType m_msg_type; - bool m_is_act; - ConversationPtrVector m_items; + public: + typedef void (ConversationsChangeCallback::*Signature)( + const ConversationPtrVector& conversations); -}; + ConversationsChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue); + virtual ~ConversationsChangeCallback(); + + void added(const ConversationPtrVector& conversations); + void updated(const ConversationPtrVector& conversations); + void removed(const ConversationPtrVector& conversations); + + void setFilter(tizen::AbstractFilterPtr filter); + tizen::AbstractFilterPtr getFilter() const; -} //messaging -} //extension + int getServiceId() const; + MessageType getServiceType() const; + void setActive(bool act); + bool isActive(); + void setItems(ConversationPtrVector& items); + ConversationPtrVector getItems(); + + private: + static ConversationPtrVector filterConversations( + tizen::AbstractFilterPtr a_filter, const ConversationPtrVector& a_sourceConversations); + + ConversationCallbackData m_callback_data; + tizen::AbstractFilterPtr m_filter; + int m_id; + MessageType m_msg_type; + bool m_is_act; + ConversationPtrVector m_items; +}; +} // messaging +} // extension -#endif // __MESSAGING_CONVERSATIONS_CHANGE_CALLBACK_H__ +#endif // __MESSAGING_CONVERSATIONS_CHANGE_CALLBACK_H__ diff --git a/src/messaging/email_manager.cc b/src/messaging/email_manager.cc old mode 100755 new mode 100644 index 6fa77de..753c752 --- a/src/messaging/email_manager.cc +++ b/src/messaging/email_manager.cc @@ -17,29 +17,29 @@ //#include //#include //#include -#include "common/logger.h" -#include "common/scope_exit.h" #include -#include "common/platform_exception.h" #include +#include "common/logger.h" +#include "common/platform_exception.h" +#include "common/scope_exit.h" //#include #include "MsgCommon/AbstractFilter.h" -#include #include #include #include +#include #include "email_manager.h" -#include "messaging_util.h" -#include "message_service.h" #include "message.h" #include "message_conversation.h" +#include "message_service.h" +#include "messaging_util.h" //#include "MessageCallbackUserData.h" //#include "MessagesCallbackUserData.h" -#include "find_msg_callback_user_data.h" #include "conversation_callback_data.h" +#include "find_msg_callback_user_data.h" #include "message_email.h" #include "messaging_database_manager.h" @@ -68,73 +68,68 @@ namespace messaging { namespace { const int ACCOUNT_ID_NOT_INITIALIZED = -1; -const std::string FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME = "serviceId"; -} //anonymous namespace +const std::string FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME = "serviceId"; +} // anonymous namespace -EmailManager::EmailManager() : m_slot_size(-1), m_is_initialized(false) -{ - LoggerD("Entered"); +EmailManager::EmailManager() : m_slot_size(-1), m_is_initialized(false) { + LoggerD("Entered"); } -EmailManager& EmailManager::getInstance() -{ - LoggerD("Entered"); - static EmailManager instance; - return instance; +EmailManager& EmailManager::getInstance() { + LoggerD("Entered"); + static EmailManager instance; + return instance; } #define CHECK_ERROR(ret, message) \ - if (ret.IsError()) { \ - LoggerE(message); \ - return ret; \ + if (ret.IsError()) { \ + LoggerE(message); \ + return ret; \ + } + +PlatformResult EmailManager::InitializeEmailService() { + LoggerD("Entered"); + EmailManager& instance = EmailManager::getInstance(); + + if (!instance.m_is_initialized) { + instance.getUniqueOpId(); + + int ntv_ret = email_service_begin(); + if (ntv_ret != EMAIL_ERROR_NONE) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Email service failed to begin", + ("email_service_begin error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } -PlatformResult EmailManager::InitializeEmailService() -{ - LoggerD("Entered"); - EmailManager& instance = EmailManager::getInstance(); - - if (!instance.m_is_initialized) { - instance.getUniqueOpId(); - - int ntv_ret = email_service_begin(); - if(ntv_ret != EMAIL_ERROR_NONE){ - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Email service failed to begin", - ("email_service_begin error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } + ntv_ret = email_open_db(); + if (ntv_ret != EMAIL_ERROR_NONE) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Email DB failed to open", + ("email_open_db error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } - ntv_ret = email_open_db(); - if(ntv_ret != EMAIL_ERROR_NONE){ - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Email DB failed to open", - ("email_open_db error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } + int slot_size = -1; + vconf_get_int("db/private/email-service/slot_size", &(slot_size)); + if (slot_size > 0) { + instance.m_slot_size = slot_size; + } - int slot_size = -1; - vconf_get_int("db/private/email-service/slot_size", &(slot_size)); - if (slot_size > 0) { - instance.m_slot_size = slot_size; - } + PlatformResult ret = DBus::SyncProxy::create( + DBus::kDBusPathNetworkStatus, DBus::kDBusIfaceNetworkStatus, &instance.m_proxy_sync); + CHECK_ERROR(ret, "create sync proxy failed"); + if (!instance.m_proxy_sync) { + LoggerE("Sync proxy is null"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Sync proxy is null"); + } + instance.m_proxy_sync->signalSubscribe(); - PlatformResult ret = DBus::SyncProxy::create(DBus::kDBusPathNetworkStatus, - DBus::kDBusIfaceNetworkStatus, - &instance.m_proxy_sync); - CHECK_ERROR(ret, "create sync proxy failed"); - if (!instance.m_proxy_sync) { - LoggerE("Sync proxy is null"); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Sync proxy is null"); - } - instance.m_proxy_sync->signalSubscribe(); - - ret = DBus::LoadBodyProxy::create(DBus::kDBusPathNetworkStatus, - DBus::kDBusIfaceNetworkStatus, - &instance.m_proxy_load_body); - CHECK_ERROR(ret, "create load body proxy failed"); - if (!instance.m_proxy_load_body) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load body proxy is null"); - } - instance.m_proxy_load_body->signalSubscribe(); + ret = DBus::LoadBodyProxy::create(DBus::kDBusPathNetworkStatus, DBus::kDBusIfaceNetworkStatus, + &instance.m_proxy_load_body); + CHECK_ERROR(ret, "create load body proxy failed"); + if (!instance.m_proxy_load_body) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load body proxy is null"); + } + instance.m_proxy_load_body->signalSubscribe(); // ret = DBus::LoadAttachmentProxy::create(DBus::Proxy::DBUS_PATH_NETWORK_STATUS, // DBus::Proxy::DBUS_IFACE_NETWORK_STATUS, @@ -146,208 +141,195 @@ PlatformResult EmailManager::InitializeEmailService() // } // m_proxy_load_attachment->signalSubscribe(); - ret = DBus::MessageProxy::create(&instance.m_proxy_messageStorage); - CHECK_ERROR(ret, "create message proxy failed"); - if (!instance.m_proxy_messageStorage) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Message proxy is null"); - } - instance.m_proxy_messageStorage->signalSubscribe(); - - ret = DBus::SendProxy::create(&instance.m_proxy_send); - CHECK_ERROR(ret, "create send proxy failed"); - if (!instance.m_proxy_send) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Send proxy is null"); - } - instance.m_proxy_send->signalSubscribe(); + ret = DBus::MessageProxy::create(&instance.m_proxy_messageStorage); + CHECK_ERROR(ret, "create message proxy failed"); + if (!instance.m_proxy_messageStorage) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Message proxy is null"); + } + instance.m_proxy_messageStorage->signalSubscribe(); - instance.m_is_initialized = true; + ret = DBus::SendProxy::create(&instance.m_proxy_send); + CHECK_ERROR(ret, "create send proxy failed"); + if (!instance.m_proxy_send) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Send proxy is null"); } + instance.m_proxy_send->signalSubscribe(); - return PlatformResult(ErrorCode::NO_ERROR); + instance.m_is_initialized = true; + } + + return PlatformResult(ErrorCode::NO_ERROR); } -EmailManager::~EmailManager() -{ - LoggerD("Entered"); +EmailManager::~EmailManager() { + LoggerD("Entered"); } PlatformResult EmailManager::addDraftMessagePlatform(int account_id, - std::shared_ptr message) -{ - LoggerD("Entered"); - return addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_DRAFT); + std::shared_ptr message) { + LoggerD("Entered"); + return addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_DRAFT); } PlatformResult EmailManager::addOutboxMessagePlatform(int account_id, - std::shared_ptr message) -{ + std::shared_ptr message) { return addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_OUTBOX); } -PlatformResult EmailManager::addMessagePlatform(int account_id, - std::shared_ptr message, email_mailbox_type_e mailbox_type) -{ - LoggerD("Entered"); - email_mail_data_t* mail_data = NULL; - email_mail_data_t* mail_data_final = NULL; - int err = EMAIL_ERROR_NONE; +PlatformResult EmailManager::addMessagePlatform(int account_id, std::shared_ptr message, + email_mailbox_type_e mailbox_type) { + LoggerD("Entered"); + email_mail_data_t* mail_data = NULL; + email_mail_data_t* mail_data_final = NULL; + int err = EMAIL_ERROR_NONE; - PlatformResult ret = Message::convertPlatformEmail(message, &mail_data); - if (ret.IsError()) return ret; + PlatformResult ret = Message::convertPlatformEmail(message, &mail_data); + if (ret.IsError()) return ret; - mail_data->account_id = account_id; + mail_data->account_id = account_id; - //Adding "from" email address - email_account_t* account = NULL; - err = email_get_account(account_id, GET_FULL_DATA_WITHOUT_PASSWORD, &account); - if(EMAIL_ERROR_NONE != err) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot retrieve email account information", - ("email_get_account error: %d (%s)", err, get_error_message(err))); - } - LoggerE("FROM %s", account->user_email_address); - std::stringstream ss; - ss << "<" << account->user_email_address << ">"; - std::string address_from; - ss >> address_from; - mail_data->full_address_from = strdup(address_from.c_str()); - LoggerE("FROM %s", mail_data->full_address_from); - err = email_free_account(&account,1); - if(EMAIL_ERROR_NONE != err) { - LoggerE("Failed to free account data memory"); - } - //Setting mailbox id - email_mailbox_t *mailbox_data = NULL; - err = email_get_mailbox_by_mailbox_type(account_id, mailbox_type, - &mailbox_data); - if(EMAIL_ERROR_NONE != err) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot retrieve draft mailbox", - ("email_get_mailbox_by_mailbox_type error: %d (%s)", err, get_error_message(err))); + // Adding "from" email address + email_account_t* account = NULL; + err = email_get_account(account_id, GET_FULL_DATA_WITHOUT_PASSWORD, &account); + if (EMAIL_ERROR_NONE != err) { + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory %d (%s)", ntv_ret, get_error_message(ntv_ret)); } - else { - LoggerD("email_get_mailbox_by_mailbox_type success.\n"); - mail_data->mailbox_id = mailbox_data->mailbox_id; - mail_data->mailbox_type = mailbox_data->mailbox_type; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot retrieve email account information", + ("email_get_account error: %d (%s)", err, get_error_message(err))); + } + LoggerE("FROM %s", account->user_email_address); + std::stringstream ss; + ss << "<" << account->user_email_address << ">"; + std::string address_from; + ss >> address_from; + mail_data->full_address_from = strdup(address_from.c_str()); + LoggerE("FROM %s", mail_data->full_address_from); + err = email_free_account(&account, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Failed to free account data memory"); + } + // Setting mailbox id + email_mailbox_t* mailbox_data = NULL; + err = email_get_mailbox_by_mailbox_type(account_id, mailbox_type, &mailbox_data); + if (EMAIL_ERROR_NONE != err) { + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Cannot retrieve draft mailbox", + ("email_get_mailbox_by_mailbox_type error: %d (%s)", err, get_error_message(err))); + } else { + LoggerD("email_get_mailbox_by_mailbox_type success.\n"); + mail_data->mailbox_id = mailbox_data->mailbox_id; + mail_data->mailbox_type = mailbox_data->mailbox_type; + } - mail_data->report_status = EMAIL_MAIL_REPORT_NONE; - mail_data->save_status = EMAIL_MAIL_STATUS_SAVED; - mail_data->flags_draft_field = 1; + mail_data->report_status = EMAIL_MAIL_REPORT_NONE; + mail_data->save_status = EMAIL_MAIL_STATUS_SAVED; + mail_data->flags_draft_field = 1; - //adding email without attachments - err = email_add_mail(mail_data, NULL, 0, NULL, 0); - if(EMAIL_ERROR_NONE != err) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - ntv_ret = email_free_mailbox(&mailbox_data, 1); - if (EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to destroy mailbox: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't add message to draft mailbox", - ("email_add_mail error: %d (%s)", err, get_error_message(err))); + // adding email without attachments + err = email_add_mail(mail_data, NULL, 0, NULL, 0); + if (EMAIL_ERROR_NONE != err) { + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } - else { - LoggerD("email_add_mail success.\n"); + ntv_ret = email_free_mailbox(&mailbox_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to destroy mailbox: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Couldn't add message to draft mailbox", + ("email_add_mail error: %d (%s)", err, get_error_message(err))); + } else { + LoggerD("email_add_mail success.\n"); + } - LoggerD("saved mail without attachments id = [%d]\n", mail_data->mail_id); - - message->setId(mail_data->mail_id); - message->setMessageStatus(MessageStatus::STATUS_DRAFT); + LoggerD("saved mail without attachments id = [%d]\n", mail_data->mail_id); - if (message->getHasAttachment()){ - ret = Message::addEmailAttachments(message); - if (ret.IsError()) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return ret; - } - } + message->setId(mail_data->mail_id); + message->setMessageStatus(MessageStatus::STATUS_DRAFT); - err = email_get_mail_data(message->getId(), &mail_data_final); - if(EMAIL_ERROR_NONE != err) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't retrieve added mail data", - ("email_get_mail_data error: %d (%s)", err, get_error_message(err))); - } - ret = message->updateEmailMessage(*mail_data_final); + if (message->getHasAttachment()) { + ret = Message::addEmailAttachments(message); if (ret.IsError()) { - int ntv_ret = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != ntv_ret) { - LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } return ret; } + } - err = email_free_mail_data(&mail_data_final,1); - if(EMAIL_ERROR_NONE != err) { - LoggerE("Failed to free mail data final memory: %d (%s)", err, get_error_message(err)); + err = email_get_mail_data(message->getId(), &mail_data_final); + if (EMAIL_ERROR_NONE != err) { + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } - - err = email_free_mail_data(&mail_data,1); - if(EMAIL_ERROR_NONE != err) { - LoggerE("Failed to free mail data memory: %d (%s)", err, get_error_message(err)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Couldn't retrieve added mail data", + ("email_get_mail_data error: %d (%s)", err, get_error_message(err))); + } + ret = message->updateEmailMessage(*mail_data_final); + if (ret.IsError()) { + int ntv_ret = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerE("Failed to free mail data memory: %d (%s)", ntv_ret, get_error_message(ntv_ret)); } + return ret; + } - err = email_free_mailbox(&mailbox_data, 1); - if (EMAIL_ERROR_NONE != err) { - LoggerE("Failed to destroy mailbox: %d (%s)", err, get_error_message(err)); - } - return PlatformResult(ErrorCode::NO_ERROR); + err = email_free_mail_data(&mail_data_final, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Failed to free mail data final memory: %d (%s)", err, get_error_message(err)); + } + + err = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Failed to free mail data memory: %d (%s)", err, get_error_message(err)); + } + + err = email_free_mailbox(&mailbox_data, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Failed to destroy mailbox: %d (%s)", err, get_error_message(err)); + } + return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean addDraftMessageCompleteCB(void *data) -{ - LoggerD("Entered"); - MessageCallbackUserData* callback = - static_cast(data); - if (!callback) { - LoggerE("Callback is null"); - return false; - } +static gboolean addDraftMessageCompleteCB(void* data) { + LoggerD("Entered"); + MessageCallbackUserData* callback = static_cast(data); + if (!callback) { + LoggerE("Callback is null"); + return false; + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); + } else { + LoggerD("Calling success callback"); - picojson::object args; - args[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); - callback->SetSuccess(picojson::value(args)); - } + picojson::object args; + args[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); + callback->SetSuccess(picojson::value(args)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return false; + return false; } -void EmailManager::addDraftMessage(MessageCallbackUserData* callback) -{ +void EmailManager::addDraftMessage(MessageCallbackUserData* callback) { LoggerD("Entered"); - if(!callback){ + if (!callback) { LoggerE("Callback is null"); return; } @@ -359,8 +341,8 @@ void EmailManager::addDraftMessage(MessageCallbackUserData* callback) callback->SetError(ret); } } - //Complete task - if (!g_idle_add(addDraftMessageCompleteCB, static_cast(callback))) { + // Complete task + if (!g_idle_add(addDraftMessageCompleteCB, static_cast(callback))) { LoggerE("g_idle addition failed"); delete callback; callback = NULL; @@ -368,56 +350,52 @@ void EmailManager::addDraftMessage(MessageCallbackUserData* callback) } //**** sending email **** -static gboolean sendEmailCompleteCB(void* data) -{ - LoggerD("Entered"); - - MessageRecipientsCallbackData* callback = - static_cast(data); - if (!callback) { - LoggerE("Callback is null"); - return false; - } +static gboolean sendEmailCompleteCB(void* data) { + LoggerD("Entered"); - if (callback->IsError()) { - LoggerD("Calling error callback"); - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); - } - else { - LoggerD("Calling success callback"); + MessageRecipientsCallbackData* callback = static_cast(data); + if (!callback) { + LoggerE("Callback is null"); + return false; + } + + if (callback->IsError()) { + LoggerD("Calling error callback"); + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); + } else { + LoggerD("Calling success callback"); - std::vector recipients; - auto addToRecipients = [&recipients](std::string& e)->void { - recipients.push_back(picojson::value(e)); - }; + std::vector recipients; + auto addToRecipients = [&recipients](std::string& e) -> void { + recipients.push_back(picojson::value(e)); + }; - auto toVect = callback->getMessage()->getTO(); - std::for_each(toVect.begin(), toVect.end(), addToRecipients); + auto toVect = callback->getMessage()->getTO(); + std::for_each(toVect.begin(), toVect.end(), addToRecipients); - auto ccVect = callback->getMessage()->getCC(); - std::for_each(ccVect.begin(), ccVect.end(), addToRecipients); + auto ccVect = callback->getMessage()->getCC(); + std::for_each(ccVect.begin(), ccVect.end(), addToRecipients); - auto bccVect = callback->getMessage()->getBCC(); - std::for_each(bccVect.begin(), bccVect.end(), addToRecipients); + auto bccVect = callback->getMessage()->getBCC(); + std::for_each(bccVect.begin(), bccVect.end(), addToRecipients); - picojson::object data; - data[JSON_DATA_RECIPIENTS] = picojson::value(recipients); - data[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); + picojson::object data; + data[JSON_DATA_RECIPIENTS] = picojson::value(recipients); + data[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); - callback->SetSuccess(picojson::value(data)); - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT); - } + callback->SetSuccess(picojson::value(data)); + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return false; + return false; } -PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback) -{ +PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback) { LoggerD("Entered"); if (!callback) { @@ -425,7 +403,7 @@ PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback } int err = EMAIL_ERROR_NONE; - email_mail_data_t *mail_data = NULL; + email_mail_data_t* mail_data = NULL; PlatformResult platform_result(ErrorCode::NO_ERROR); @@ -437,11 +415,11 @@ PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback } if (platform_result) { - err = email_get_mail_data(message->getId(),&mail_data); + err = email_get_mail_data(message->getId(), &mail_data); if (EMAIL_ERROR_NONE != err) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get platform email structure", - ("email_get_mail_data %d (%s)", err, get_error_message(err))); + platform_result = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get platform email structure", + ("email_get_mail_data %d (%s)", err, get_error_message(err))); } else { LoggerD("email_get_mail_data success.\n"); @@ -452,9 +430,9 @@ PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback err = email_send_mail(mail_data->mail_id, &req_id); if (EMAIL_ERROR_NONE != err) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to send message", - ("email_send_mail error: %d (%s)", err, get_error_message(err))); + platform_result = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to send message", + ("email_send_mail error: %d (%s)", err, get_error_message(err))); } else { LoggerD("req_id: %d", req_id); callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENDING); @@ -490,123 +468,115 @@ PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback return platform_result; } -void EmailManager::sendStatusCallback(int mail_id, - email_noti_on_network_event status, - int error_code) -{ - LoggerD("Entered"); +void EmailManager::sendStatusCallback(int mail_id, email_noti_on_network_event status, + int error_code) { + LoggerD("Entered"); - std::lock_guard lock(m_mutex); - //find first request for this mail_id - SendReqMapIterator it = getSendRequest(mail_id); - if (it != m_sendRequests.end()) { - LoggerD("Found request"); - MessageRecipientsCallbackData* callback = it->second; - m_sendRequests.erase(it); - - if (NOTI_SEND_FAIL == status) { - LoggerD("Failed to send message, set proper error"); - switch (error_code) { - case EMAIL_ERROR_NO_SIM_INSERTED: - case EMAIL_ERROR_SOCKET_FAILURE: - case EMAIL_ERROR_CONNECTION_FAILURE: - case EMAIL_ERROR_CONNECTION_BROKEN: - case EMAIL_ERROR_NO_SUCH_HOST: - case EMAIL_ERROR_NETWORK_NOT_AVAILABLE: - case EMAIL_ERROR_INVALID_STREAM: - case EMAIL_ERROR_NO_RESPONSE: - { - callback->SetError(LogAndCreateResult( - ErrorCode::NETWORK_ERR, "Failed to send message", - ("Network error: %d (%s)", error_code, get_error_message(error_code)))); - break; - } - default: - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to send message", - ("Unknown error: %d (%s)", error_code, get_error_message(error_code)))); - break; - } - } else if (NOTI_SEND_FINISH == status) { - LoggerD("Message sent successfully"); + std::lock_guard lock(m_mutex); + // find first request for this mail_id + SendReqMapIterator it = getSendRequest(mail_id); + if (it != m_sendRequests.end()) { + LoggerD("Found request"); + MessageRecipientsCallbackData* callback = it->second; + m_sendRequests.erase(it); + + if (NOTI_SEND_FAIL == status) { + LoggerD("Failed to send message, set proper error"); + switch (error_code) { + case EMAIL_ERROR_NO_SIM_INSERTED: + case EMAIL_ERROR_SOCKET_FAILURE: + case EMAIL_ERROR_CONNECTION_FAILURE: + case EMAIL_ERROR_CONNECTION_BROKEN: + case EMAIL_ERROR_NO_SUCH_HOST: + case EMAIL_ERROR_NETWORK_NOT_AVAILABLE: + case EMAIL_ERROR_INVALID_STREAM: + case EMAIL_ERROR_NO_RESPONSE: { + callback->SetError(LogAndCreateResult( + ErrorCode::NETWORK_ERR, "Failed to send message", + ("Network error: %d (%s)", error_code, get_error_message(error_code)))); + break; } + default: + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to send message", + ("Unknown error: %d (%s)", error_code, get_error_message(error_code)))); + break; + } + } else if (NOTI_SEND_FINISH == status) { + LoggerD("Message sent successfully"); + } - if (!g_idle_add(sendEmailCompleteCB, static_cast(callback))) { - LoggerE("g_idle addition failed"); - delete callback; - callback = NULL; - } - } else { - LoggerW("No matching request found"); + if (!g_idle_add(sendEmailCompleteCB, static_cast(callback))) { + LoggerE("g_idle addition failed"); + delete callback; + callback = NULL; } + } else { + LoggerW("No matching request found"); + } } -email_mail_data_t* EmailManager::loadMessage(int msg_id) -{ - LoggerD("Entered"); - email_mail_data_t* mail_data = NULL; - int err = email_get_mail_data(msg_id, &mail_data); - if (EMAIL_ERROR_NONE != err) { - LoggerE("email_get_mail_data failed. [%d] (%s)", err, get_error_message(err)); - } else { - LoggerD("email_get_mail_data success."); - } - return mail_data; +email_mail_data_t* EmailManager::loadMessage(int msg_id) { + LoggerD("Entered"); + email_mail_data_t* mail_data = NULL; + int err = email_get_mail_data(msg_id, &mail_data); + if (EMAIL_ERROR_NONE != err) { + LoggerE("email_get_mail_data failed. [%d] (%s)", err, get_error_message(err)); + } else { + LoggerD("email_get_mail_data success."); + } + return mail_data; } -EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id) -{ - LoggerD("Entered"); - for (auto it = m_sendRequests.begin(); it != m_sendRequests.end(); it++) { - if (it->second->getMessage()->getId() == mail_id) { - return it; - } +EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id) { + LoggerD("Entered"); + for (auto it = m_sendRequests.begin(); it != m_sendRequests.end(); it++) { + if (it->second->getMessage()->getId() == mail_id) { + return it; } - return m_sendRequests.end(); + } + return m_sendRequests.end(); } -void EmailManager::freeMessage(email_mail_data_t* mail_data) -{ - LoggerD("Entered"); - if(!mail_data) { - return; - } +void EmailManager::freeMessage(email_mail_data_t* mail_data) { + LoggerD("Entered"); + if (!mail_data) { + return; + } - int err = email_free_mail_data(&mail_data, 1); - if(EMAIL_ERROR_NONE != err) { - LoggerE("Could not free mail data!"); - } + int err = email_free_mail_data(&mail_data, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Could not free mail data!"); + } } -void EmailManager::loadMessageBody(MessageBodyCallbackData* callback) -{ - LoggerD("Entered"); - if(!callback){ - LoggerE("Callback is null"); - return; - } +void EmailManager::loadMessageBody(MessageBodyCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + LoggerE("Callback is null"); + return; + } - if(!callback->getMessage()) { - LoggerE("Callback's message is null"); - return; - } + if (!callback->getMessage()) { + LoggerE("Callback's message is null"); + return; + } - m_proxy_load_body->addCallback(callback); + m_proxy_load_body->addCallback(callback); - const int mailId = callback->getMessage()->getId(); + const int mailId = callback->getMessage()->getId(); - int op_handle = -1; - int err = email_download_body(mailId, 0, &op_handle); - if(EMAIL_ERROR_NONE != err){ - LoggerE("Email download body failed, %d (%s)", err, get_error_message(err)); - m_proxy_load_body->removeCallback(callback); - return; - } - callback->setOperationHandle(op_handle); + int op_handle = -1; + int err = email_download_body(mailId, 0, &op_handle); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Email download body failed, %d (%s)", err, get_error_message(err)); + m_proxy_load_body->removeCallback(callback); + return; + } + callback->setOperationHandle(op_handle); } -PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData* callback) -{ +PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData* callback) { LoggerD("Entered"); if (!callback) { @@ -614,12 +584,12 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData } if (!callback->getMessageAttachment()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Callback's message attachment is null"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Callback's message attachment is null"); } std::shared_ptr msgAttachment = callback->getMessageAttachment(); - LoggerD("attachmentId: [%d] mailId: [%d]", msgAttachment->getId(), - msgAttachment->getMessageId()); + LoggerD("attachmentId: [%d] mailId: [%d]", msgAttachment->getId(), msgAttachment->getMessageId()); email_mail_data_t* mail_data = EmailManager::loadMessage(msgAttachment->getMessageId()); @@ -629,8 +599,8 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData if (!mail_data) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't load message.", - ("Couldn't get email_mail_data_t for messageId: %d", msgAttachment->getMessageId())); + ErrorCode::UNKNOWN_ERR, "Couldn't load message.", + ("Couldn't get email_mail_data_t for messageId: %d", msgAttachment->getMessageId())); } AttachmentPtrVector attachments; @@ -640,8 +610,8 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData return platform_result; } - LoggerD("Mail: [%d] contains: [%d] attachments", - msgAttachment->getMessageId(), attachments.size()); + LoggerD("Mail: [%d] contains: [%d] attachments", msgAttachment->getMessageId(), + attachments.size()); auto it = attachments.begin(); int attachmentIndex = -1; @@ -653,24 +623,23 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData } if (attachmentIndex < 0) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't find attachment.", - ("Attachment with id: %d not found", msgAttachment->getId())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Couldn't find attachment.", + ("Attachment with id: %d not found", msgAttachment->getId())); } - LoggerD("Attachment with id: [%d] is located at index: [%d]", - msgAttachment->getId(), attachmentIndex); + LoggerD("Attachment with id: [%d] is located at index: [%d]", msgAttachment->getId(), + attachmentIndex); int op_handle = -1; - const int nth = attachmentIndex + 1; //in documentation: the minimum number is "1" + const int nth = attachmentIndex + 1; // in documentation: the minimum number is "1" callback->setNth(nth); int err = email_download_attachment(msgAttachment->getMessageId(), nth, &op_handle); if (EMAIL_ERROR_NONE != err) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to load attachment.", - ("Download email attachment failed with error: %d (%s)", err, get_error_message(err))); + ErrorCode::UNKNOWN_ERR, "Failed to load attachment.", + ("Download email attachment failed with error: %d (%s)", err, get_error_message(err))); } else { LoggerD("email_download_attachment returned handle: [%d]", op_handle); callback->setOperationHandle(op_handle); @@ -681,8 +650,7 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData //#################################### sync: ################################### -void EmailManager::sync(void* data) -{ +void EmailManager::sync(void* data) { LoggerD("Entered"); SyncCallbackData* callback = static_cast(data); @@ -729,8 +697,7 @@ void EmailManager::sync(void* data) //################################## syncFolder: ############################### -void EmailManager::syncFolder(SyncFolderCallbackData* callback) -{ +void EmailManager::syncFolder(SyncFolderCallbackData* callback) { LoggerD("Entered"); if (!callback) { @@ -800,8 +767,7 @@ void EmailManager::syncFolder(SyncFolderCallbackData* callback) //################################## stopSync: ################################# -void EmailManager::stopSync(long op_id) -{ +void EmailManager::stopSync(long op_id) { LoggerD("Entered"); SyncCallbackData* callback = static_cast(m_proxy_sync->getCallback(op_id)); @@ -811,9 +777,8 @@ void EmailManager::stopSync(long op_id) return; } - int err = email_cancel_job(callback->getAccountId(), - callback->getOperationHandle(), - EMAIL_CANCELED_BY_USER); + int err = email_cancel_job(callback->getAccountId(), callback->getOperationHandle(), + EMAIL_CANCELED_BY_USER); if (EMAIL_ERROR_NONE != err) { LoggerE("Email cancel job failed, %d (%s)", err, get_error_message(err)); @@ -845,15 +810,13 @@ void EmailManager::RemoveCallbacksByQueue(const PostQueue& q) { } } -void removeEmailCompleteCB(MessagesCallbackUserData* callback) -{ +void removeEmailCompleteCB(MessagesCallbackUserData* callback) { LoggerD("Entered"); if (!callback) { LoggerE("Callback is null"); return; } - if (callback->IsError()) { LoggerD("Calling error callback"); @@ -870,90 +833,86 @@ void removeEmailCompleteCB(MessagesCallbackUserData* callback) } EmailManager::DeleteReqVector::iterator EmailManager::getDeleteRequest( - const std::vector &ids) -{ - LoggerD("Entered"); - for (auto idIt = ids.begin(); idIt != ids.end(); ++idIt) { - for (auto reqIt = m_deleteRequests.begin(); reqIt != m_deleteRequests.end(); ++reqIt) { - MessagePtrVector msgs = reqIt->callback->getMessages(); - for (auto msgIt = msgs.begin(); msgIt != msgs.end(); ++msgIt) { - if ((*msgIt)->getId() == *idIt) { - return reqIt; - } - } + const std::vector& ids) { + LoggerD("Entered"); + for (auto idIt = ids.begin(); idIt != ids.end(); ++idIt) { + for (auto reqIt = m_deleteRequests.begin(); reqIt != m_deleteRequests.end(); ++reqIt) { + MessagePtrVector msgs = reqIt->callback->getMessages(); + for (auto msgIt = msgs.begin(); msgIt != msgs.end(); ++msgIt) { + if ((*msgIt)->getId() == *idIt) { + return reqIt; } + } } - return m_deleteRequests.end(); + } + return m_deleteRequests.end(); } -void EmailManager::removeStatusCallback(const std::vector &ids, - email_noti_on_storage_event status) -{ - LoggerD("Entered"); - std::lock_guard lock(m_mutex); - DeleteReqVector::iterator it = getDeleteRequest(ids); - if (it != m_deleteRequests.end()) { - LoggerD("Found request"); - if (NOTI_MAIL_DELETE_FINISH == status) { - LoggerD("Successfully removed %d mails", ids.size()); - it->messagesDeleted += ids.size(); - } - MessagesCallbackUserData* callback = it->callback; - if (NOTI_MAIL_DELETE_FAIL == status) { - callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Messages remove failed")); - } - //if one of mails failed, call error callback - //if all mails are deleted, call success. - // >= is used in case of duplicated dbus messages - if (NOTI_MAIL_DELETE_FAIL == status || - static_cast(it->messagesDeleted) >= it->callback->getMessages().size()) { - LoggerD("Calling callback"); - m_deleteRequests.erase(it); - m_mutex.unlock(); - removeEmailCompleteCB(callback); - } else { - LoggerD("Not all messages are removed, waiting for next callback"); - } +void EmailManager::removeStatusCallback(const std::vector& ids, + email_noti_on_storage_event status) { + LoggerD("Entered"); + std::lock_guard lock(m_mutex); + DeleteReqVector::iterator it = getDeleteRequest(ids); + if (it != m_deleteRequests.end()) { + LoggerD("Found request"); + if (NOTI_MAIL_DELETE_FINISH == status) { + LoggerD("Successfully removed %d mails", ids.size()); + it->messagesDeleted += ids.size(); + } + MessagesCallbackUserData* callback = it->callback; + if (NOTI_MAIL_DELETE_FAIL == status) { + callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Messages remove failed")); + } + // if one of mails failed, call error callback + // if all mails are deleted, call success. + // >= is used in case of duplicated dbus messages + if (NOTI_MAIL_DELETE_FAIL == status || + static_cast(it->messagesDeleted) >= it->callback->getMessages().size()) { + LoggerD("Calling callback"); + m_deleteRequests.erase(it); + m_mutex.unlock(); + removeEmailCompleteCB(callback); } else { - LoggerD("Request not found, ignoring"); + LoggerD("Not all messages are removed, waiting for next callback"); } + } else { + LoggerD("Request not found, ignoring"); + } } -PlatformResult EmailManager::RemoveMessagesPlatform(MessagesCallbackUserData* callback) -{ +PlatformResult EmailManager::RemoveMessagesPlatform(MessagesCallbackUserData* callback) { LoggerD("Entered"); int error; - email_mail_data_t *mail = NULL; + email_mail_data_t* mail = NULL; std::lock_guard lock(m_mutex); std::vector> messages = callback->getMessages(); MessageType type = callback->getMessageServiceType(); - for(auto it = messages.begin() ; it != messages.end(); ++it) { - if((*it)->getType() != type) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting email", - ("Invalid message type %d", (*it)->getType())); + for (auto it = messages.begin(); it != messages.end(); ++it) { + if ((*it)->getType() != type) { + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting email", + ("Invalid message type %d", (*it)->getType())); } } - for (auto it = messages.begin() ; it != messages.end(); ++it) { + for (auto it = messages.begin(); it != messages.end(); ++it) { error = email_get_mail_data((*it)->getId(), &mail); if (EMAIL_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting mail", - ("Couldn't retrieve mail data: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Error while deleting mail", + ("Couldn't retrieve mail data: %d (%s)", error, get_error_message(error))); } - //This task (_EMAIL_API_DELETE_MAIL) is for async + // This task (_EMAIL_API_DELETE_MAIL) is for async error = email_delete_mail(mail->mailbox_id, &mail->mail_id, 1, 0); if (EMAIL_ERROR_NONE != error) { email_free_mail_data(&mail, 1); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting mail", - ("email_delete_mail error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Error while deleting mail", + ("email_delete_mail error: %d (%s)", error, get_error_message(error))); } email_free_mail_data(&mail, 1); } - //store delete request and wait for dbus response + // store delete request and wait for dbus response DeleteReq request; request.callback = callback; request.messagesDeleted = 0; @@ -962,11 +921,10 @@ PlatformResult EmailManager::RemoveMessagesPlatform(MessagesCallbackUserData* ca return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::removeMessages(MessagesCallbackUserData* callback) -{ +void EmailManager::removeMessages(MessagesCallbackUserData* callback) { LoggerD("Entered"); - if (!callback){ + if (!callback) { LoggerE("Callback is null"); return; } @@ -982,7 +940,7 @@ void EmailManager::removeMessages(MessagesCallbackUserData* callback) PlatformResult EmailManager::UpdateMessagesPlatform(MessagesCallbackUserData* callback) { LoggerD("Entered"); int error; - email_mail_data_t *mail = NULL; + email_mail_data_t* mail = NULL; SCOPE_EXIT { if (mail) { email_free_mail_data(&mail, 1); @@ -993,95 +951,90 @@ PlatformResult EmailManager::UpdateMessagesPlatform(MessagesCallbackUserData* ca std::lock_guard lock(m_mutex); std::vector> messages = callback->getMessages(); MessageType type = callback->getMessageServiceType(); - for (auto it = messages.begin() ; it != messages.end(); ++it) { + for (auto it = messages.begin(); it != messages.end(); ++it) { if ((*it)->getType() != type) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while updating message", - ("Invalid message type: %d", (*it)->getType())); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Error while updating message", + ("Invalid message type: %d", (*it)->getType())); } } - for (auto it = messages.begin() ; it != messages.end(); ++it) { - + for (auto it = messages.begin(); it != messages.end(); ++it) { PlatformResult ret = Message::convertPlatformEmail((*it), &mail); if (ret.IsError()) return ret; - if((*it)->getHasAttachment()) - { + if ((*it)->getHasAttachment()) { LoggerD("Message has attachments. Workaround need to be used."); - //Update of mail on server using function email_update_mail() is not possible. - //Attachment is updated only locally (can't be later loaded from server), - //so use of workaround is needed: - //1. add new mail - //2. delete old mail + // Update of mail on server using function email_update_mail() is not possible. + // Attachment is updated only locally (can't be later loaded from server), + // so use of workaround is needed: + // 1. add new mail + // 2. delete old mail - //adding message again after changes + // adding message again after changes PlatformResult ret = addDraftMessagePlatform(mail->account_id, (*it)); if (ret.IsError()) { return ret; } LoggerD("mail added - new id = [%d]\n", (*it)->getId()); - //storing old message id + // storing old message id (*it)->setOldId(mail->mail_id); - //deleting old mail + // deleting old mail LoggerD("mail deleted = [%d]\n", mail->mail_id); - error = email_delete_mail(mail->mailbox_id,&mail->mail_id,1,1); + error = email_delete_mail(mail->mailbox_id, &mail->mail_id, 1, 1); if (EMAIL_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting old mail on update", - ("email_delete_mail error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Error while deleting old mail on update", + ("email_delete_mail error: %d (%s)", error, get_error_message(error))); } } else { LoggerD("There are no attachments, updating only email data."); error = email_update_mail(mail, NULL, 0, NULL, 0); if (EMAIL_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while updating mail", - ("email_update_mail error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Error while updating mail", + ("email_update_mail error: %d (%s)", error, get_error_message(error))); } } } return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::updateMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); - - if (!callback){ - LoggerE("Callback is null"); - return; - } +void EmailManager::updateMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - PlatformResult ret = UpdateMessagesPlatform(callback); - if (ret.IsError()) { - LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); - callback->SetError(ret); - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + PlatformResult ret = UpdateMessagesPlatform(callback); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + callback->SetError(ret); + } - picojson::array array; - auto messages = callback->getMessages(); - size_t messages_size = messages.size(); - for (size_t i = 0 ; i < messages_size; ++i) { - array.push_back(MessagingUtil::messageToJson(messages[i])); - } + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - callback->SetSuccess(picojson::value(array)); + picojson::array array; + auto messages = callback->getMessages(); + size_t messages_size = messages.size(); + for (size_t i = 0; i < messages_size; ++i) { + array.push_back(MessagingUtil::messageToJson(messages[i])); } - callback->Post(); + callback->SetSuccess(picojson::value(array)); + } - delete callback; - callback = NULL; + callback->Post(); + + delete callback; + callback = NULL; } -PlatformResult EmailManager::FindMessagesPlatform(FindMsgCallbackUserData* callback) -{ +PlatformResult EmailManager::FindMessagesPlatform(FindMsgCallbackUserData* callback) { LoggerD("Entered"); email_mail_data_t* mailList = NULL; int mailListCount = 0; @@ -1114,11 +1067,10 @@ PlatformResult EmailManager::FindMessagesPlatform(FindMsgCallbackUserData* callb return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::findMessages(FindMsgCallbackUserData* callback) -{ +void EmailManager::findMessages(FindMsgCallbackUserData* callback) { LoggerD("Entered"); - if(!callback){ + if (!callback) { LoggerE("Callback is null"); return; } @@ -1129,7 +1081,7 @@ void EmailManager::findMessages(FindMsgCallbackUserData* callback) callback->SetError(ret); } - //Complete task + // Complete task LoggerD("callback: %p error: %d messages.size() = %d", callback, callback->IsError(), callback->getMessages().size()); @@ -1140,7 +1092,7 @@ void EmailManager::findMessages(FindMsgCallbackUserData* callback) LoggerD("Calling success callback"); std::vector response; auto messages = callback->getMessages(); - std::for_each(messages.begin(), messages.end(), [&response](MessagePtr &message){ + std::for_each(messages.begin(), messages.end(), [&response](MessagePtr& message) { response.push_back(MessagingUtil::messageToJson(message)); }); @@ -1153,15 +1105,14 @@ void EmailManager::findMessages(FindMsgCallbackUserData* callback) callback = NULL; } -PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* callback) -{ +PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* callback) { LoggerD("Entered"); int convListCount = 0; std::lock_guard lock(m_mutex); std::vector conversationsInfo; - PlatformResult ret = MessagingDatabaseManager::getInstance(). - findEmailConversations(callback, &conversationsInfo); + PlatformResult ret = + MessagingDatabaseManager::getInstance().findEmailConversations(callback, &conversationsInfo); if (ret.IsError()) return ret; convListCount = conversationsInfo.size(); @@ -1178,60 +1129,56 @@ PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::findConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void EmailManager::findConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if(!callback){ - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - PlatformResult ret = FindConversationsPlatform(callback); - if (ret.IsError()) { - LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); - callback->SetError(ret); - } + PlatformResult ret = FindConversationsPlatform(callback); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + callback->SetError(ret); + } - //Complete task - LoggerD("callback: %p error:%d conversations.size()=%d", callback, callback->IsError(), - callback->getConversations().size()); + // Complete task + LoggerD("callback: %p error:%d conversations.size()=%d", callback, callback->IsError(), + callback->getConversations().size()); - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - std::vector response; - auto messages = callback->getConversations(); - std::for_each(messages.begin(), messages.end(), - [&response](std::shared_ptr &conversation) { - response.push_back(MessagingUtil::conversationToJson(conversation)); - } - ); + std::vector response; + auto messages = callback->getConversations(); + std::for_each(messages.begin(), messages.end(), + [&response](std::shared_ptr& conversation) { + response.push_back(MessagingUtil::conversationToJson(conversation)); + }); - callback->SetSuccess(picojson::value(response)); - } + callback->SetSuccess(picojson::value(response)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -long EmailManager::getUniqueOpId() -{ - LoggerD("Entered"); - // mutex is created only on first call (first call added to constructor - // to initialize mutex correctly) - static std::mutex op_id_mutex; - std::lock_guard lock(op_id_mutex); - static long op_id = 0; - return op_id++; +long EmailManager::getUniqueOpId() { + LoggerD("Entered"); + // mutex is created only on first call (first call added to constructor + // to initialize mutex correctly) + static std::mutex op_id_mutex; + std::lock_guard lock(op_id_mutex); + static long op_id = 0; + return op_id++; } -PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) -{ +PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) { LoggerD("Entered"); int ret = EMAIL_ERROR_UNKNOWN; int account_id = ACCOUNT_ID_NOT_INITIALIZED; @@ -1241,8 +1188,7 @@ PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) SCOPE_EXIT { if (mailboxes != NULL) { - if (EMAIL_ERROR_NONE != email_free_mailbox(&mailboxes, - mailboxes_count)) { + if (EMAIL_ERROR_NONE != email_free_mailbox(&mailboxes, mailboxes_count)) { LoggerW("Free mailboxes failed: %d", ret); } } @@ -1255,26 +1201,22 @@ PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Filter not provided"); } - for(FilterIterator it(filter); false == it.isEnd(); it++) { - + for (FilterIterator it(filter); false == it.isEnd(); it++) { if (FIS_COMPOSITE_START == it.getState()) { CompositeFilterPtr cf = castToCompositeFilter((*it)); - if(cf && INTERSECTION != cf->getType()) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Invalid Filter Type", - ("Invalid Filter type: %d", cf->getType())); + if (cf && INTERSECTION != cf->getType()) { + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid Filter Type", + ("Invalid Filter type: %d", cf->getType())); } - } - else if (FIS_ATTRIBUTE_FILTER == it.getState()) { + } else if (FIS_ATTRIBUTE_FILTER == it.getState()) { AttributeFilterPtr attrf = castToAttributeFilter((*it)); if (attrf) { const std::string attr_name = attrf->getAttributeName(); if (FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME == attr_name) { account_id = static_cast(attrf->getMatchValue()->toLong()); } else { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "The attribute name is invalid", - ("The attribute name: %s is invalid", attr_name.c_str())); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "The attribute name is invalid", + ("The attribute name: %s is invalid", attr_name.c_str())); } } } @@ -1282,20 +1224,16 @@ PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) LoggerD("Listing folders for account ID: %d", account_id); if (account_id > 0) { - ret = email_get_mailbox_list(account_id, - -1, - &mailboxes, - &mailboxes_count); + ret = email_get_mailbox_list(account_id, -1, &mailboxes, &mailboxes_count); if (EMAIL_ERROR_NONE != ret || !mailboxes) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Platform error, cannot get folders", - ("email_get_mailbox_list error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Platform error, cannot get folders", + ("email_get_mailbox_list error: %d (%s)", ret, get_error_message(ret))); } if (mailboxes_count <= 0) { LoggerD("Empty mailboxes"); - } - else { + } else { LoggerD("Founded mailboxes: %d", mailboxes_count); nth_mailbox = mailboxes; @@ -1310,83 +1248,78 @@ PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::findFolders(FoldersCallbackData* callback) -{ - LoggerD("Entered"); +void EmailManager::findFolders(FoldersCallbackData* callback) { + LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - PlatformResult ret = FindFoldersPlatform(callback); - if (ret.IsError()) { - LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); - callback->SetError(ret); - } + PlatformResult ret = FindFoldersPlatform(callback); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + callback->SetError(ret); + } - //Complete task - LoggerD("callback: %p error:%d folders.size()=%d", callback, callback->IsError(), - callback->getFolders().size()); + // Complete task + LoggerD("callback: %p error:%d folders.size()=%d", callback, callback->IsError(), + callback->getFolders().size()); - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - std::vector response; - auto folders = callback->getFolders(); - std::for_each(folders.begin(), folders.end(), - [&response](std::shared_ptr &folder) { - response.push_back(MessagingUtil::folderToJson(folder)); - } - ); + std::vector response; + auto folders = callback->getFolders(); + std::for_each(folders.begin(), folders.end(), + [&response](std::shared_ptr& folder) { + response.push_back(MessagingUtil::folderToJson(folder)); + }); - callback->SetSuccess(picojson::value(response)); - } + callback->SetSuccess(picojson::value(response)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -PlatformResult EmailManager::RemoveConversationsPlatform(ConversationCallbackData* callback) -{ +PlatformResult EmailManager::RemoveConversationsPlatform(ConversationCallbackData* callback) { LoggerD("Entered"); int error; std::lock_guard lock(m_mutex); - std::vector> conversations = - callback->getConversations(); + std::vector> conversations = callback->getConversations(); MessageType type = callback->getMessageServiceType(); int thread_id = 0; - for(auto it = conversations.begin() ; it != conversations.end(); ++it) { + for (auto it = conversations.begin(); it != conversations.end(); ++it) { if ((*it)->getType() != type) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting email conversation", - ("Invalid message type %d", (*it)->getType())); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, + "Error while deleting email conversation", + ("Invalid message type %d", (*it)->getType())); } } - for (auto it = conversations.begin() ; it != conversations.end(); ++it) { + for (auto it = conversations.begin(); it != conversations.end(); ++it) { thread_id = (*it)->getConversationId(); error = email_delete_thread(thread_id, false); if (EMAIL_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting email conversation", - ("Couldn't delete email conversation data %d (%s)", error, get_error_message(error))); + ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting email conversation", + ("Couldn't delete email conversation data %d (%s)", error, get_error_message(error))); } // for now, there is no way to recognize deleting email thread job is completed. // so use polling to wait the thread is removed. - email_mail_data_t *thread_info = NULL; + email_mail_data_t* thread_info = NULL; do { - struct timespec sleep_time = { 0, 300L * 1000L * 1000L }; + struct timespec sleep_time = {0, 300L * 1000L * 1000L}; nanosleep(&sleep_time, nullptr); LoggerD("Waiting to delete this email thread..."); - error = email_get_thread_information_by_thread_id( - thread_id, &thread_info); + error = email_get_thread_information_by_thread_id(thread_id, &thread_info); if (thread_info != NULL) { free(thread_info); @@ -1397,39 +1330,38 @@ PlatformResult EmailManager::RemoveConversationsPlatform(ConversationCallbackDat return PlatformResult(ErrorCode::NO_ERROR); } -void EmailManager::removeConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void EmailManager::removeConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - PlatformResult ret = RemoveConversationsPlatform(callback); - if (ret.IsError()) { - LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); - callback->SetError(ret); - } + PlatformResult ret = RemoveConversationsPlatform(callback); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + callback->SetError(ret); + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - callback->SetSuccess(); - } + callback->SetSuccess(); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } std::string EmailManager::getMessageStatus(int id) { LoggerD("Entered"); - email_mail_data_t *mail = nullptr; + email_mail_data_t* mail = nullptr; MessageStatus status = MessageStatus::STATUS_UNDEFINED; int ret = email_get_mail_data(id, &mail); @@ -1438,7 +1370,7 @@ std::string EmailManager::getMessageStatus(int id) { return ""; } - switch(mail->save_status) { + switch (mail->save_status) { case EMAIL_MAIL_STATUS_SENT: status = MessageStatus::STATUS_SENT; break; @@ -1457,12 +1389,12 @@ std::string EmailManager::getMessageStatus(int id) { } ret = email_free_mail_data(&mail, 1); - if (EMAIL_ERROR_NONE != ret ) { + if (EMAIL_ERROR_NONE != ret) { LoggerD("Failed to free mail data %d (%s)", ret, get_error_message(ret)); } return MessagingUtil::messageStatusToString(status); } -} // Messaging -} // DeviceAPI +} // Messaging +} // DeviceAPI diff --git a/src/messaging/email_manager.h b/src/messaging/email_manager.h index 8828d29..e6e8c1d 100644 --- a/src/messaging/email_manager.h +++ b/src/messaging/email_manager.h @@ -22,127 +22,122 @@ #define __TIZEN_EMAIL_MANAGER_H__ #include +#include #include #include -#include #include -#include "email-api-network.h" #include "email-api-account.h" #include "email-api-mail.h" #include "email-api-mailbox.h" +#include "email-api-network.h" -#include "messaging/callback_user_data.h" #include "common/GDBus/connection.h" #include "common/platform_exception.h" #include "common/platform_result.h" +#include "messaging/callback_user_data.h" -#include "messaging_util.h" #include "message_service.h" +#include "messaging_util.h" -#include "DBus/SyncProxy.h" -#include "DBus/LoadBodyProxy.h" #include "DBus/LoadAttachmentProxy.h" +#include "DBus/LoadBodyProxy.h" #include "DBus/MessageProxy.h" #include "DBus/SendProxy.h" +#include "DBus/SyncProxy.h" namespace extension { namespace messaging { -//class Message; -//class MessageCallbackUserData; +// class Message; +// class MessageCallbackUserData; class FindMsgCallbackUserData; -//class SyncFolderCallbackData; +// class SyncFolderCallbackData; class MessageBodyCallbackData; class EmailManager { -public: - static EmailManager& getInstance(); - static common::PlatformResult InitializeEmailService(); - - void addDraftMessage(MessageCallbackUserData* callback); - void removeMessages(MessagesCallbackUserData* callback); - void updateMessages(MessagesCallbackUserData* callback); - void findMessages(FindMsgCallbackUserData* callback); - void findConversations(ConversationCallbackData* callback); - void findFolders(FoldersCallbackData* callback); - void removeConversations(ConversationCallbackData* callback); - std::string getMessageStatus(int id); - - common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); - void sendStatusCallback(int mail_id, email_noti_on_network_event status, - int error_code); - void removeStatusCallback(const std::vector &ids, - email_noti_on_storage_event status); - - void loadMessageBody(MessageBodyCallbackData* callback); - common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); - - void sync(void* data); - void syncFolder(SyncFolderCallbackData* callback); - void stopSync(long op_id); - - void RemoveSyncCallback(long op_id); - void RemoveCallbacksByQueue(const PostQueue& q); - -// void registerStatusCallback(msg_handle_t msg_handle); - - /** - * Use freeMessage() to release returned email_mail_data_t object. - */ - static email_mail_data_t* loadMessage(int msg_id); - static void freeMessage(email_mail_data_t*); - - long getUniqueOpId(); - -private: - EmailManager(); - EmailManager(const EmailManager &); - void operator=(const EmailManager &); - virtual ~EmailManager(); - common::PlatformResult addDraftMessagePlatform(int account_id, - std::shared_ptr message); - common::PlatformResult addOutboxMessagePlatform(int account_id, - std::shared_ptr message); - common::PlatformResult addMessagePlatform(int account_id, std::shared_ptr message, - email_mailbox_type_e mailbox_type); - common::PlatformResult UpdateMessagesPlatform(MessagesCallbackUserData* callback); - common::PlatformResult RemoveMessagesPlatform( - MessagesCallbackUserData* callback); - common::PlatformResult FindMessagesPlatform(FindMsgCallbackUserData* callback); - common::PlatformResult FindConversationsPlatform(ConversationCallbackData* callback); - common::PlatformResult FindFoldersPlatform(FoldersCallbackData* callback); - common::PlatformResult RemoveConversationsPlatform(ConversationCallbackData* callback); - - typedef std::map SendReqMap; - typedef SendReqMap::iterator SendReqMapIterator; - SendReqMapIterator getSendRequest(int mail_id); - SendReqMap m_sendRequests; - struct DeleteReq { - MessagesCallbackUserData* callback; - int messagesDeleted; - }; - typedef std::vector DeleteReqVector; - /** - * Find first request containing at least one message id - * @param ids - * @return - */ - DeleteReqVector::iterator getDeleteRequest(const std::vector &ids); - DeleteReqVector m_deleteRequests; - - int m_slot_size; - - DBus::SyncProxyPtr m_proxy_sync; - DBus::LoadBodyProxyPtr m_proxy_load_body; - DBus::LoadAttachmentProxyPtr m_proxy_load_attachment; - DBus::MessageProxyPtr m_proxy_messageStorage; - DBus::SendProxyPtr m_proxy_send; - - std::mutex m_mutex; - bool m_is_initialized; + public: + static EmailManager& getInstance(); + static common::PlatformResult InitializeEmailService(); + + void addDraftMessage(MessageCallbackUserData* callback); + void removeMessages(MessagesCallbackUserData* callback); + void updateMessages(MessagesCallbackUserData* callback); + void findMessages(FindMsgCallbackUserData* callback); + void findConversations(ConversationCallbackData* callback); + void findFolders(FoldersCallbackData* callback); + void removeConversations(ConversationCallbackData* callback); + std::string getMessageStatus(int id); + + common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); + void sendStatusCallback(int mail_id, email_noti_on_network_event status, int error_code); + void removeStatusCallback(const std::vector& ids, email_noti_on_storage_event status); + + void loadMessageBody(MessageBodyCallbackData* callback); + common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); + + void sync(void* data); + void syncFolder(SyncFolderCallbackData* callback); + void stopSync(long op_id); + + void RemoveSyncCallback(long op_id); + void RemoveCallbacksByQueue(const PostQueue& q); + + // void registerStatusCallback(msg_handle_t msg_handle); + + /** + * Use freeMessage() to release returned email_mail_data_t object. + */ + static email_mail_data_t* loadMessage(int msg_id); + static void freeMessage(email_mail_data_t*); + + long getUniqueOpId(); + + private: + EmailManager(); + EmailManager(const EmailManager&); + void operator=(const EmailManager&); + virtual ~EmailManager(); + common::PlatformResult addDraftMessagePlatform(int account_id, std::shared_ptr message); + common::PlatformResult addOutboxMessagePlatform(int account_id, std::shared_ptr message); + common::PlatformResult addMessagePlatform(int account_id, std::shared_ptr message, + email_mailbox_type_e mailbox_type); + common::PlatformResult UpdateMessagesPlatform(MessagesCallbackUserData* callback); + common::PlatformResult RemoveMessagesPlatform(MessagesCallbackUserData* callback); + common::PlatformResult FindMessagesPlatform(FindMsgCallbackUserData* callback); + common::PlatformResult FindConversationsPlatform(ConversationCallbackData* callback); + common::PlatformResult FindFoldersPlatform(FoldersCallbackData* callback); + common::PlatformResult RemoveConversationsPlatform(ConversationCallbackData* callback); + + typedef std::map SendReqMap; + typedef SendReqMap::iterator SendReqMapIterator; + SendReqMapIterator getSendRequest(int mail_id); + SendReqMap m_sendRequests; + struct DeleteReq { + MessagesCallbackUserData* callback; + int messagesDeleted; + }; + typedef std::vector DeleteReqVector; + /** + * Find first request containing at least one message id + * @param ids + * @return + */ + DeleteReqVector::iterator getDeleteRequest(const std::vector& ids); + DeleteReqVector m_deleteRequests; + + int m_slot_size; + + DBus::SyncProxyPtr m_proxy_sync; + DBus::LoadBodyProxyPtr m_proxy_load_body; + DBus::LoadAttachmentProxyPtr m_proxy_load_attachment; + DBus::MessageProxyPtr m_proxy_messageStorage; + DBus::SendProxyPtr m_proxy_send; + + std::mutex m_mutex; + bool m_is_initialized; }; -} // Messaging -} // DeviceAPI -#endif // __TIZEN_EMAIL_MANAGER_H__ +} // Messaging +} // DeviceAPI +#endif // __TIZEN_EMAIL_MANAGER_H__ diff --git a/src/messaging/find_msg_callback_user_data.cc b/src/messaging/find_msg_callback_user_data.cc old mode 100755 new mode 100644 index 0cef06c..bd28ba4 --- a/src/messaging/find_msg_callback_user_data.cc +++ b/src/messaging/find_msg_callback_user_data.cc @@ -23,88 +23,74 @@ namespace extension { namespace messaging { -FindMsgCallbackUserData::FindMsgCallbackUserData(PostQueue& queue, long cid) : - CallbackUserData(queue, cid), - m_limit(0), - m_offset(0), - m_account_id(0), - m_service_type(UNDEFINED) { +FindMsgCallbackUserData::FindMsgCallbackUserData(PostQueue& queue, long cid) + : CallbackUserData(queue, cid), + m_limit(0), + m_offset(0), + m_account_id(0), + m_service_type(UNDEFINED) { LoggerD("Entered"); } -FindMsgCallbackUserData::~FindMsgCallbackUserData() -{ - LoggerD("Entered"); +FindMsgCallbackUserData::~FindMsgCallbackUserData() { + LoggerD("Entered"); } -void FindMsgCallbackUserData::setFilter(AbstractFilterPtr filter) -{ - m_filter = filter; +void FindMsgCallbackUserData::setFilter(AbstractFilterPtr filter) { + m_filter = filter; } -void FindMsgCallbackUserData::setSortMode(SortModePtr sortMode) -{ - m_sort = sortMode; +void FindMsgCallbackUserData::setSortMode(SortModePtr sortMode) { + m_sort = sortMode; } -void FindMsgCallbackUserData::setLimit(long limit) -{ - m_limit = limit; +void FindMsgCallbackUserData::setLimit(long limit) { + m_limit = limit; } -void FindMsgCallbackUserData::setOffset(long offset) -{ - m_offset = offset; +void FindMsgCallbackUserData::setOffset(long offset) { + m_offset = offset; } -void FindMsgCallbackUserData::addMessage(std::shared_ptr msg) -{ - m_messages.push_back(msg); +void FindMsgCallbackUserData::addMessage(std::shared_ptr msg) { + m_messages.push_back(msg); } -std::vector> FindMsgCallbackUserData::getMessages() const -{ - return m_messages; +std::vector> FindMsgCallbackUserData::getMessages() const { + return m_messages; } -void FindMsgCallbackUserData::setAccountId(int account_id){ - m_account_id = account_id; +void FindMsgCallbackUserData::setAccountId(int account_id) { + m_account_id = account_id; } -int FindMsgCallbackUserData::getAccountId() const -{ - return m_account_id; +int FindMsgCallbackUserData::getAccountId() const { + return m_account_id; } -void FindMsgCallbackUserData::setMessageServiceType(MessageType m_msg_type) -{ - m_service_type = m_msg_type; +void FindMsgCallbackUserData::setMessageServiceType(MessageType m_msg_type) { + m_service_type = m_msg_type; } -MessageType FindMsgCallbackUserData::getMessageServiceType() const -{ - return m_service_type; +MessageType FindMsgCallbackUserData::getMessageServiceType() const { + return m_service_type; } -AbstractFilterPtr FindMsgCallbackUserData::getFilter() const -{ - return m_filter; +AbstractFilterPtr FindMsgCallbackUserData::getFilter() const { + return m_filter; } -SortModePtr FindMsgCallbackUserData::getSortMode() const -{ - return m_sort; +SortModePtr FindMsgCallbackUserData::getSortMode() const { + return m_sort; } -long FindMsgCallbackUserData::getLimit() const -{ - return m_limit; +long FindMsgCallbackUserData::getLimit() const { + return m_limit; } -long FindMsgCallbackUserData::getOffset() const -{ - return m_offset; +long FindMsgCallbackUserData::getOffset() const { + return m_offset; } -}//Messaging -}//DeviceAPI +} // Messaging +} // DeviceAPI diff --git a/src/messaging/find_msg_callback_user_data.h b/src/messaging/find_msg_callback_user_data.h index d778228..da7f194 100644 --- a/src/messaging/find_msg_callback_user_data.h +++ b/src/messaging/find_msg_callback_user_data.h @@ -25,11 +25,11 @@ #include #include -#include "messaging/callback_user_data.h" #include "MsgCommon/AttributeFilter.h" #include "MsgCommon/SortMode.h" -#include "messaging_util.h" #include "common/platform_result.h" +#include "messaging/callback_user_data.h" +#include "messaging_util.h" using namespace extension::tizen; @@ -39,38 +39,38 @@ namespace messaging { class Message; class FindMsgCallbackUserData : public CallbackUserData { -public: - FindMsgCallbackUserData(PostQueue& queue, long cid); - virtual ~FindMsgCallbackUserData(); + public: + FindMsgCallbackUserData(PostQueue& queue, long cid); + virtual ~FindMsgCallbackUserData(); - void setFilter(AbstractFilterPtr filter); - void setSortMode(SortModePtr sortMode); - void setLimit(long limit); - void setOffset(long offset); - void addMessage(std::shared_ptr msg); - std::vector> getMessages() const; + void setFilter(AbstractFilterPtr filter); + void setSortMode(SortModePtr sortMode); + void setLimit(long limit); + void setOffset(long offset); + void addMessage(std::shared_ptr msg); + std::vector> getMessages() const; - void setAccountId(int account_id); - int getAccountId() const; + void setAccountId(int account_id); + int getAccountId() const; - void setMessageServiceType(MessageType m_msg_type); - MessageType getMessageServiceType() const; - AbstractFilterPtr getFilter() const; - SortModePtr getSortMode() const; - long getLimit() const; - long getOffset() const; + void setMessageServiceType(MessageType m_msg_type); + MessageType getMessageServiceType() const; + AbstractFilterPtr getFilter() const; + SortModePtr getSortMode() const; + long getLimit() const; + long getOffset() const; -private: - AbstractFilterPtr m_filter; - SortModePtr m_sort; - long m_limit; - long m_offset; - std::vector> m_messages; - int m_account_id; - MessageType m_service_type; + private: + AbstractFilterPtr m_filter; + SortModePtr m_sort; + long m_limit; + long m_offset; + std::vector> m_messages; + int m_account_id; + MessageType m_service_type; }; -}//Messaging -}//DeviceAPI +} // Messaging +} // DeviceAPI #endif /* __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H */ diff --git a/src/messaging/folders_callback_data.cc b/src/messaging/folders_callback_data.cc old mode 100755 new mode 100644 index e5566b9..6d5f3da --- a/src/messaging/folders_callback_data.cc +++ b/src/messaging/folders_callback_data.cc @@ -13,35 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "folders_callback_data.h" namespace extension { namespace messaging { FoldersCallbackData::~FoldersCallbackData() { - LoggerD("Entered"); + LoggerD("Entered"); } -void FoldersCallbackData::addFolder(std::shared_ptr folder) -{ - m_folders.push_back(folder); +void FoldersCallbackData::addFolder(std::shared_ptr folder) { + m_folders.push_back(folder); } -const std::vector>& FoldersCallbackData::getFolders() const -{ - return m_folders; +const std::vector>& FoldersCallbackData::getFolders() const { + return m_folders; } -void FoldersCallbackData::setFilter(tizen::AbstractFilterPtr filter) -{ - m_filter = filter; +void FoldersCallbackData::setFilter(tizen::AbstractFilterPtr filter) { + m_filter = filter; } -tizen::AbstractFilterPtr FoldersCallbackData::getFilter() const -{ - return m_filter; +tizen::AbstractFilterPtr FoldersCallbackData::getFilter() const { + return m_filter; } -}//messaging -}//extension +} // messaging +} // extension diff --git a/src/messaging/folders_callback_data.h b/src/messaging/folders_callback_data.h index 34a5076..422b27f 100644 --- a/src/messaging/folders_callback_data.h +++ b/src/messaging/folders_callback_data.h @@ -20,11 +20,11 @@ #include "common/platform_result.h" #include -#include #include +#include -#include "messaging/callback_user_data.h" #include "MsgCommon/AbstractFilter.h" +#include "messaging/callback_user_data.h" #include "message_folder.h" #include "messaging_util.h" @@ -35,22 +35,22 @@ namespace messaging { class MessageFolder; class FoldersCallbackData : public CallbackUserData { -public: - using CallbackUserData::CallbackUserData; - virtual ~FoldersCallbackData(); + public: + using CallbackUserData::CallbackUserData; + virtual ~FoldersCallbackData(); - void addFolder(std::shared_ptr folder); - const std::vector>& getFolders() const; + void addFolder(std::shared_ptr folder); + const std::vector>& getFolders() const; - void setFilter(tizen::AbstractFilterPtr filter); - tizen::AbstractFilterPtr getFilter() const; + void setFilter(tizen::AbstractFilterPtr filter); + tizen::AbstractFilterPtr getFilter() const; -private: - std::vector> m_folders; - tizen::AbstractFilterPtr m_filter; + private: + std::vector> m_folders; + tizen::AbstractFilterPtr m_filter; }; -}//messaging -}//extension +} // messaging +} // extension #endif /* __TIZEN_FOLDERS_CALLBACK_DATA_H__ */ diff --git a/src/messaging/folders_change_callback.cc b/src/messaging/folders_change_callback.cc old mode 100755 new mode 100644 index adb821e..7211313 --- a/src/messaging/folders_change_callback.cc +++ b/src/messaging/folders_change_callback.cc @@ -27,176 +27,155 @@ const char* FOLDERSADDED = "foldersadded"; const char* FOLDERSUPDATED = "foldersupdated"; const char* FOLDERSREMOVED = "foldersremoved"; -FoldersChangeCallback::FoldersChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue): - m_callback_data(queue, cid, true), - m_id(service_id), - m_msg_type(service_type), - m_is_act(true) -{ - LoggerD("Entered"); - m_callback_data.SetListenerId("FoldersChangeListener"); +FoldersChangeCallback::FoldersChangeCallback(long cid, int service_id, MessageType service_type, + PostQueue& queue) + : m_callback_data(queue, cid, true), + m_id(service_id), + m_msg_type(service_type), + m_is_act(true) { + LoggerD("Entered"); + m_callback_data.SetListenerId("FoldersChangeListener"); } -FoldersChangeCallback::~FoldersChangeCallback() -{ - LoggerD("Entered"); +FoldersChangeCallback::~FoldersChangeCallback() { + LoggerD("Entered"); } -FolderPtrVector FoldersChangeCallback::filterFolders( - tizen::AbstractFilterPtr filter, - const FolderPtrVector& source_folders) -{ - LoggerD("Entered"); - if (filter) { - LoggerD("filter pointer is valid"); - FolderPtrVector filtered_folders; - FolderPtrVector::const_iterator it = source_folders.begin(); - FolderPtrVector::const_iterator end_it = source_folders.end(); - - for(int i = 0; it != end_it; ++i, ++it) { - const FolderPtr& folder = *it; - const bool matched = filter->isMatching(folder.get()); - if (matched) { - filtered_folders.push_back(folder); - } - - LoggerD("[%d] folder id:%s", i, folder->getId().c_str()); - LoggerD("[%d] folder name:%s", i, folder->getName().c_str()); - LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); - } - - return filtered_folders; - } - else { - return source_folders; +FolderPtrVector FoldersChangeCallback::filterFolders(tizen::AbstractFilterPtr filter, + const FolderPtrVector& source_folders) { + LoggerD("Entered"); + if (filter) { + LoggerD("filter pointer is valid"); + FolderPtrVector filtered_folders; + FolderPtrVector::const_iterator it = source_folders.begin(); + FolderPtrVector::const_iterator end_it = source_folders.end(); + + for (int i = 0; it != end_it; ++i, ++it) { + const FolderPtr& folder = *it; + const bool matched = filter->isMatching(folder.get()); + if (matched) { + filtered_folders.push_back(folder); + } + + LoggerD("[%d] folder id:%s", i, folder->getId().c_str()); + LoggerD("[%d] folder name:%s", i, folder->getName().c_str()); + LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); } + + return filtered_folders; + } else { + return source_folders; + } } -void FoldersChangeCallback::added(const FolderPtrVector& folders) -{ - LoggerD("Entered folders.size()=%d", folders.size()); - if (!m_is_act) { - return; - } +void FoldersChangeCallback::added(const FolderPtrVector& folders) { + LoggerD("Entered folders.size()=%d", folders.size()); + if (!m_is_act) { + return; + } - FolderPtrVector filtered = filterFolders(m_filter, folders); + FolderPtrVector filtered = filterFolders(m_filter, folders); - //if filter is set but there is no folder matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no folder matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr f)->void { - array.push_back(MessagingUtil::folderToJson(f)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr f) -> void { + array.push_back(MessagingUtil::folderToJson(f)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d added folders", FOLDERSADDED, - filtered.size()); + LoggerD("Calling:%s with:%d added folders", FOLDERSADDED, filtered.size()); - m_callback_data.SetAction(FOLDERSADDED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::MEDIUM); + m_callback_data.SetAction(FOLDERSADDED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::MEDIUM); } -void FoldersChangeCallback::updated(const FolderPtrVector& folders) -{ - LoggerD("Entered folders.size()=%d", folders.size()); - if (!m_is_act) { - return; - } +void FoldersChangeCallback::updated(const FolderPtrVector& folders) { + LoggerD("Entered folders.size()=%d", folders.size()); + if (!m_is_act) { + return; + } - FolderPtrVector filtered = filterFolders(m_filter, folders); + FolderPtrVector filtered = filterFolders(m_filter, folders); - //if filter is set but there is no folder matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no folder matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr f)->void { - array.push_back(MessagingUtil::folderToJson(f)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr f) -> void { + array.push_back(MessagingUtil::folderToJson(f)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d updated folders", FOLDERSUPDATED, - filtered.size()); + LoggerD("Calling:%s with:%d updated folders", FOLDERSUPDATED, filtered.size()); - m_callback_data.SetAction(FOLDERSUPDATED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LOW); + m_callback_data.SetAction(FOLDERSUPDATED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LOW); } -void FoldersChangeCallback::removed(const FolderPtrVector& folders) -{ - LoggerD("Entered folders.size()=%d", folders.size()); - if (!m_is_act) { - return; - } +void FoldersChangeCallback::removed(const FolderPtrVector& folders) { + LoggerD("Entered folders.size()=%d", folders.size()); + if (!m_is_act) { + return; + } - FolderPtrVector filtered = filterFolders(m_filter, folders); + FolderPtrVector filtered = filterFolders(m_filter, folders); - //if filter is set but there is no folder matched just return; - if (!filtered.size()) { - LoggerD("There is no matched result."); - return; - } + // if filter is set but there is no folder matched just return; + if (!filtered.size()) { + LoggerD("There is no matched result."); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr f)->void { - array.push_back(MessagingUtil::folderToJson(f)); - }; - for_each(filtered.begin(), filtered.end(), each); + picojson::array array; + auto each = [&array](std::shared_ptr f) -> void { + array.push_back(MessagingUtil::folderToJson(f)); + }; + for_each(filtered.begin(), filtered.end(), each); - LoggerD("Calling:%s with:%d removed folders", FOLDERSREMOVED, - filtered.size()); + LoggerD("Calling:%s with:%d removed folders", FOLDERSREMOVED, filtered.size()); - m_callback_data.SetAction(FOLDERSREMOVED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LAST); + m_callback_data.SetAction(FOLDERSREMOVED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LAST); } -void FoldersChangeCallback::setFilter(tizen::AbstractFilterPtr filter) -{ - m_filter = filter; +void FoldersChangeCallback::setFilter(tizen::AbstractFilterPtr filter) { + m_filter = filter; } -tizen::AbstractFilterPtr FoldersChangeCallback::getFilter() const -{ - return m_filter; +tizen::AbstractFilterPtr FoldersChangeCallback::getFilter() const { + return m_filter; } -int FoldersChangeCallback::getServiceId() const -{ - return m_id; +int FoldersChangeCallback::getServiceId() const { + return m_id; } -MessageType FoldersChangeCallback::getServiceType() const -{ - return m_msg_type; +MessageType FoldersChangeCallback::getServiceType() const { + return m_msg_type; } void FoldersChangeCallback::setActive(bool act) { - m_is_act = act; + m_is_act = act; } bool FoldersChangeCallback::isActive() { - return m_is_act; + return m_is_act; } -void FoldersChangeCallback::setItems(FolderPtrVector& items) -{ - m_items = items; +void FoldersChangeCallback::setItems(FolderPtrVector& items) { + m_items = items; } -FolderPtrVector FoldersChangeCallback::getItems() -{ - return m_items; +FolderPtrVector FoldersChangeCallback::getItems() { + return m_items; } -} //namespace messaging -} //namespace extension - +} // namespace messaging +} // namespace extension diff --git a/src/messaging/folders_change_callback.h b/src/messaging/folders_change_callback.h index 68c4fc1..f6649a0 100644 --- a/src/messaging/folders_change_callback.h +++ b/src/messaging/folders_change_callback.h @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __MESSAGING_FOLDERS_CHANGE_CALLBACK_H__ #define __MESSAGING_FOLDERS_CHANGE_CALLBACK_H__ - #include "MsgCommon/AbstractFilter.h" -#include "messaging_util.h" #include "message_folder.h" +#include "messaging_util.h" #include "folders_callback_data.h" @@ -35,45 +34,41 @@ extern const char* FOLDERSUPDATED; extern const char* FOLDERSREMOVED; class FoldersChangeCallback { -public: - typedef void(FoldersChangeCallback::*Signature)(const FolderPtrVector& conversations); - - FoldersChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue); - virtual ~FoldersChangeCallback(); - - void added(const FolderPtrVector& folders); - void updated(const FolderPtrVector& folders); - void removed(const FolderPtrVector& folders); - - void setFilter(tizen::AbstractFilterPtr filter); - tizen::AbstractFilterPtr getFilter() const; - - int getServiceId() const; - MessageType getServiceType() const; - - void setActive(bool act); - bool isActive(); - - void setItems(FolderPtrVector& items); - FolderPtrVector getItems(); - -private: - static FolderPtrVector filterFolders(tizen::AbstractFilterPtr filter, - const FolderPtrVector& source_folders); - - FoldersCallbackData m_callback_data; - tizen::AbstractFilterPtr m_filter; - int m_id; - MessageType m_msg_type; - bool m_is_act; - FolderPtrVector m_items; + public: + typedef void (FoldersChangeCallback::*Signature)(const FolderPtrVector& conversations); + + FoldersChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue); + virtual ~FoldersChangeCallback(); + + void added(const FolderPtrVector& folders); + void updated(const FolderPtrVector& folders); + void removed(const FolderPtrVector& folders); + + void setFilter(tizen::AbstractFilterPtr filter); + tizen::AbstractFilterPtr getFilter() const; + + int getServiceId() const; + MessageType getServiceType() const; + + void setActive(bool act); + bool isActive(); + + void setItems(FolderPtrVector& items); + FolderPtrVector getItems(); + + private: + static FolderPtrVector filterFolders(tizen::AbstractFilterPtr filter, + const FolderPtrVector& source_folders); + + FoldersCallbackData m_callback_data; + tizen::AbstractFilterPtr m_filter; + int m_id; + MessageType m_msg_type; + bool m_is_act; + FolderPtrVector m_items; }; -} //messaging -} //extension +} // messaging +} // extension -#endif // __MESSAGING_FOLDERS_CHANGE_CALLBACK_H__ +#endif // __MESSAGING_FOLDERS_CHANGE_CALLBACK_H__ diff --git a/src/messaging/message.cc b/src/messaging/message.cc old mode 100755 new mode 100644 index 14f3763..2a10840 --- a/src/messaging/message.cc +++ b/src/messaging/message.cc @@ -16,8 +16,8 @@ #include "message.h" -#include #include +#include #include #include "common/logger.h" @@ -25,12 +25,12 @@ #include "common/scope_exit.h" #include "Ecore_File.h" +#include "common/filesystem/filesystem_provider.h" #include "message_email.h" -#include "message_sms.h" #include "message_mms.h" -#include "short_message_manager.h" +#include "message_sms.h" #include "messaging_util.h" -#include "common/filesystem/filesystem_provider.h" +#include "short_message_manager.h" using common::ErrorCode; using common::PlatformResult; @@ -41,41 +41,49 @@ namespace messaging { using namespace common; // *** constructor -Message::Message(): - m_id(-1), m_old_id(-1), m_id_set(false), m_conversation_id(-1), - m_conversation_id_set(false), m_folder_id(-1), m_folder_id_set(false), - m_type(UNDEFINED), m_timestamp(-1), m_timestamp_set(false), - m_from_set(false), m_body(new(std::nothrow) MessageBody()), - m_service_id(0), m_is_read(false), m_has_attachment(false), - m_high_priority(false), m_in_response(-1), m_in_response_set(false), - m_service_id_set(false), m_status(STATUS_UNDEFINED), - m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) -{ - LoggerD("Message constructor (%p)", this); -} - -Message::~Message() -{ - LoggerD("Message destructor (%p)", this); +Message::Message() + : m_id(-1), + m_old_id(-1), + m_id_set(false), + m_conversation_id(-1), + m_conversation_id_set(false), + m_folder_id(-1), + m_folder_id_set(false), + m_type(UNDEFINED), + m_timestamp(-1), + m_timestamp_set(false), + m_from_set(false), + m_body(new (std::nothrow) MessageBody()), + m_service_id(0), + m_is_read(false), + m_has_attachment(false), + m_high_priority(false), + m_in_response(-1), + m_in_response_set(false), + m_service_id_set(false), + m_status(STATUS_UNDEFINED), + m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { + LoggerD("Message constructor (%p)", this); +} + +Message::~Message() { + LoggerD("Message destructor (%p)", this); } // *** attribute getters -int Message::getId() const -{ - return m_id; +int Message::getId() const { + return m_id; } -int Message::getOldId() const -{ - if (-1 == m_old_id) { - return m_id; - } - return m_old_id; +int Message::getOldId() const { + if (-1 == m_old_id) { + return m_id; + } + return m_old_id; } -int Message::getConversationId() const -{ - return m_conversation_id; +int Message::getConversationId() const { + return m_conversation_id; } int Message::getFolderId() const { @@ -111,1546 +119,1444 @@ int Message::getFolderIdForUser() const { } } -MessageType Message::getType() const -{ - return m_type; +MessageType Message::getType() const { + return m_type; } std::string Message::getTypeString() const { return MessagingUtil::messageTypeToString(getType()); } -time_t Message::getTimestamp() const -{ - return m_timestamp; +time_t Message::getTimestamp() const { + return m_timestamp; } -std::string Message::getFrom() const -{ - return m_from; +std::string Message::getFrom() const { + return m_from; } -std::vector Message::getTO() const -{ - return m_to; +std::vector Message::getTO() const { + return m_to; } -std::vector Message::getCC() const -{ - return m_cc; +std::vector Message::getCC() const { + return m_cc; } -std::vector Message::getBCC() const -{ - return m_bcc; +std::vector Message::getBCC() const { + return m_bcc; } -std::shared_ptr Message::getBody() const -{ - return m_body; +std::shared_ptr Message::getBody() const { + return m_body; } -bool Message::getIsRead() const -{ - return m_is_read; +bool Message::getIsRead() const { + return m_is_read; } -bool Message::getHasAttachment() const -{ - // This function should be reimplemented for MMS and email - return m_has_attachment; +bool Message::getHasAttachment() const { + // This function should be reimplemented for MMS and email + return m_has_attachment; } -bool Message::getIsHighPriority() const -{ - return m_high_priority; +bool Message::getIsHighPriority() const { + return m_high_priority; } -std::string Message::getSubject() const -{ - return m_subject; +std::string Message::getSubject() const { + return m_subject; } -int Message::getInResponseTo() const -{ - return m_in_response; +int Message::getInResponseTo() const { + return m_in_response; } -MessageStatus Message::getMessageStatus() const -{ - return m_status; +MessageStatus Message::getMessageStatus() const { + return m_status; } -AttachmentPtrVector Message::getMessageAttachments() const -{ - return m_attachments; +AttachmentPtrVector Message::getMessageAttachments() const { + return m_attachments; } -int Message::getServiceId() const -{ - return m_service_id; +int Message::getServiceId() const { + return m_service_id; } -TelNetworkDefaultDataSubs_t Message::getSimIndex() const -{ - return m_sim_index; +TelNetworkDefaultDataSubs_t Message::getSimIndex() const { + return m_sim_index; } // *** attributes setters -void Message::setId(int id) -{ - LoggerD("Entered"); - m_id = id; - m_id_set = true; - m_body->setMessageId(m_id); - for (auto& att : m_attachments) { - att->setMessageId(m_id); - } +void Message::setId(int id) { + LoggerD("Entered"); + m_id = id; + m_id_set = true; + m_body->setMessageId(m_id); + for (auto& att : m_attachments) { + att->setMessageId(m_id); + } } -void Message::setOldId(int id) -{ - LoggerD("Entered"); - m_old_id = id; +void Message::setOldId(int id) { + LoggerD("Entered"); + m_old_id = id; } - -void Message::setConversationId(int id) -{ - LoggerD("Entered"); - m_conversation_id = id; - m_conversation_id_set = true; +void Message::setConversationId(int id) { + LoggerD("Entered"); + m_conversation_id = id; + m_conversation_id_set = true; } -void Message::setFolderId(int id) -{ - LoggerD("Entered"); - m_folder_id = id; - m_folder_id_set = true; +void Message::setFolderId(int id) { + LoggerD("Entered"); + m_folder_id = id; + m_folder_id_set = true; } // type setting not allowed - no setter for type -void Message::setTimeStamp(time_t timestamp) -{ - LoggerD("Entered"); - m_timestamp = timestamp; - m_timestamp_set = true; +void Message::setTimeStamp(time_t timestamp) { + LoggerD("Entered"); + m_timestamp = timestamp; + m_timestamp_set = true; } -void Message::setFrom(std::string from) -{ - LoggerD("Entered"); - m_from = from; - m_from_set = true; +void Message::setFrom(std::string from) { + LoggerD("Entered"); + m_from = from; + m_from_set = true; } -void Message::setTO(std::vector &to) -{ - LoggerD("Entered"); - // Recipient's format validation should be done by Core API service - m_to = to; +void Message::setTO(std::vector& to) { + LoggerD("Entered"); + // Recipient's format validation should be done by Core API service + m_to = to; - if(m_to.empty()) { - LoggerD("Recipient's list cleared"); - return; - } + if (m_to.empty()) { + LoggerD("Recipient's list cleared"); + return; + } } -void Message::setCC(std::vector &cc) -{ - // implementation (address/number format checking) is message specific +void Message::setCC(std::vector& cc) { + // implementation (address/number format checking) is message specific } -void Message::setBCC(std::vector &bcc) -{ - // implementation (address/number format checking) is message specific +void Message::setBCC(std::vector& bcc) { + // implementation (address/number format checking) is message specific } -void Message::setBody(std::shared_ptr& body) -{ - LoggerD("Entered"); - // while replacing message body old body should have some invalid id mark - m_body->setMessageId(-1); +void Message::setBody(std::shared_ptr& body) { + LoggerD("Entered"); + // while replacing message body old body should have some invalid id mark + m_body->setMessageId(-1); - m_body = body; - if(m_id_set) { - m_body->setMessageId(m_id); - } + m_body = body; + if (m_id_set) { + m_body->setMessageId(m_id); + } } -void Message::setIsRead(bool read) -{ - LoggerD("Entered"); - m_is_read = read; +void Message::setIsRead(bool read) { + LoggerD("Entered"); + m_is_read = read; } // has attachment can't be set explicity -> no setter for this flag -void Message::setIsHighPriority(bool highpriority) -{ - LoggerD("Entered"); - // High priority field is used only in MessageEmail - m_high_priority = highpriority; +void Message::setIsHighPriority(bool highpriority) { + LoggerD("Entered"); + // High priority field is used only in MessageEmail + m_high_priority = highpriority; } -void Message::setSubject(std::string subject) -{ - // Subject is used only in MessageEmail and MessageMMS +void Message::setSubject(std::string subject) { + // Subject is used only in MessageEmail and MessageMMS } -void Message::setInResponseTo(int inresp) -{ - LoggerD("Entered"); - m_in_response = inresp; - m_in_response_set = true; +void Message::setInResponseTo(int inresp) { + LoggerD("Entered"); + m_in_response = inresp; + m_in_response_set = true; } -void Message::setMessageStatus(MessageStatus status) -{ - LoggerD("Entered"); - m_status = status; +void Message::setMessageStatus(MessageStatus status) { + LoggerD("Entered"); + m_status = status; } -void Message::setMessageAttachments(AttachmentPtrVector &attachments) -{ - // implementation provided only for MMS and email +void Message::setMessageAttachments(AttachmentPtrVector& attachments) { + // implementation provided only for MMS and email } -void Message::setServiceId(int service_id) -{ - LoggerD("Entered"); - m_service_id = service_id; - m_service_id_set = true; +void Message::setServiceId(int service_id) { + LoggerD("Entered"); + m_service_id = service_id; + m_service_id_set = true; } -void Message::setSimIndex(TelNetworkDefaultDataSubs_t sim_index) -{ - LoggerD("Entered"); - m_sim_index = sim_index; +void Message::setSimIndex(TelNetworkDefaultDataSubs_t sim_index) { + LoggerD("Entered"); + m_sim_index = sim_index; } // *** support for optional, nullable (at JS layer) attibutes -bool Message::is_id_set() const -{ - return m_id_set; +bool Message::is_id_set() const { + return m_id_set; } -bool Message::is_conversation_id_set() const -{ - return m_conversation_id_set; +bool Message::is_conversation_id_set() const { + return m_conversation_id_set; } -bool Message::is_folder_id_set() const -{ - return m_folder_id_set; +bool Message::is_folder_id_set() const { + return m_folder_id_set; } -bool Message::is_timestamp_set() const -{ - return m_timestamp_set; +bool Message::is_timestamp_set() const { + return m_timestamp_set; } -bool Message::is_from_set() const -{ - return m_from_set; +bool Message::is_from_set() const { + return m_from_set; } -bool Message::is_in_response_set() const -{ - return m_in_response_set; +bool Message::is_in_response_set() const { + return m_in_response_set; } -bool Message::is_service_is_set() const -{ - return m_service_id_set; +bool Message::is_service_is_set() const { + return m_service_id_set; } -std::string Message::convertEmailRecipients(const std::vector &recipients) -{ - LoggerD("Entered"); - std::string address = ""; - unsigned size = recipients.size(); - for (unsigned i=0; i; "; - } +std::string Message::convertEmailRecipients(const std::vector& recipients) { + LoggerD("Entered"); + std::string address = ""; + unsigned size = recipients.size(); + for (unsigned i = 0; i < size; ++i) { + address += "<" + recipients[i] + ">; "; + } - return address; + return address; } -PlatformResult saveToTempFile(const std::string &data, std::string* file_name) -{ - LoggerD("Entered"); - char buf[] = "XXXXXX"; +PlatformResult saveToTempFile(const std::string& data, std::string* file_name) { + LoggerD("Entered"); + char buf[] = "XXXXXX"; - mode_t mask = umask(S_IWGRP | S_IWOTH); - mkstemp(buf); //Just generate unique name + mode_t mask = umask(S_IWGRP | S_IWOTH); + mkstemp(buf); // Just generate unique name - std::string tmp_name = std::string("/tmp/") + buf; + std::string tmp_name = std::string("/tmp/") + buf; - mode_t old_mask = umask(mask); - FILE *file = fopen(tmp_name.c_str(), "w"); - umask(old_mask); + mode_t old_mask = umask(mask); + FILE* file = fopen(tmp_name.c_str(), "w"); + umask(old_mask); - if (NULL == file) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create file"); - } - if (fprintf(file, "%s", data.c_str()) < 0) { - fclose(file); - remove(tmp_name.c_str()); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to write data into file"); - } - fflush(file); + if (NULL == file) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create file"); + } + if (fprintf(file, "%s", data.c_str()) < 0) { fclose(file); - *file_name = tmp_name; - return PlatformResult(ErrorCode::NO_ERROR); + remove(tmp_name.c_str()); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to write data into file"); + } + fflush(file); + fclose(file); + *file_name = tmp_name; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult copyFileToTemp(const std::string& sourcePath, std::string* result_path) -{ - LoggerD("Entered"); - char buf[] = "XXXXXX"; - std::string fileName, attPath, tmpPath; +PlatformResult copyFileToTemp(const std::string& sourcePath, std::string* result_path) { + LoggerD("Entered"); + char buf[] = "XXXXXX"; + std::string fileName, attPath, tmpPath; - mode_t mask = umask(S_IWGRP | S_IWOTH); - int err = mkstemp(buf); - if (-1 == err) { - LoggerW("Failed to create unique filename"); - } + mode_t mask = umask(S_IWGRP | S_IWOTH); + int err = mkstemp(buf); + if (-1 == err) { + LoggerW("Failed to create unique filename"); + } - umask(mask); - std::string dirPath = "/tmp/" + std::string(buf); + umask(mask); + std::string dirPath = "/tmp/" + std::string(buf); - if ( sourcePath[0] != '/' ) { - attPath = common::FilesystemProvider::Create().GetRealPath(sourcePath); - } else { // Assuming that the path is a real path - attPath = sourcePath; - } + if (sourcePath[0] != '/') { + attPath = common::FilesystemProvider::Create().GetRealPath(sourcePath); + } else { // Assuming that the path is a real path + attPath = sourcePath; + } - // Looking for the last occurrence of slash in source path - std::size_t slashPos; - if ((slashPos = attPath.find_last_of('/')) == std::string::npos) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Error while copying file to temp: the source path is invalid."); - } + // Looking for the last occurrence of slash in source path + std::size_t slashPos; + if ((slashPos = attPath.find_last_of('/')) == std::string::npos) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Error while copying file to temp: the source path is invalid."); + } - fileName = attPath.substr(slashPos + 1); - tmpPath = dirPath + "/" + fileName; + fileName = attPath.substr(slashPos + 1); + tmpPath = dirPath + "/" + fileName; - LoggerD("attPath: %s, tmpPath: %s", attPath.c_str(), tmpPath.c_str()); - if(EINA_TRUE != ecore_file_mkdir(dirPath.c_str())) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error while creating temp directory."); - } + LoggerD("attPath: %s, tmpPath: %s", attPath.c_str(), tmpPath.c_str()); + if (EINA_TRUE != ecore_file_mkdir(dirPath.c_str())) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Unknown error while creating temp directory."); + } - FILE *f1, *f2; - size_t num; - int ret = 1; + FILE *f1, *f2; + size_t num; + int ret = 1; - f1 = fopen(attPath.c_str(), "rb"); - if (!f1) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail open attPath"); - } - f2 = fopen(tmpPath.c_str(), "wb"); - if (!f2) { - fclose (f1); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail open tmpPath"); - } + f1 = fopen(attPath.c_str(), "rb"); + if (!f1) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail open attPath"); + } + f2 = fopen(tmpPath.c_str(), "wb"); + if (!f2) { + fclose(f1); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail open tmpPath"); + } - while ((num = fread(buf, 1, sizeof(buf), f1)) > 0) { - if (fwrite(buf, 1, num, f2) != num) - ret = 0; - } + while ((num = fread(buf, 1, sizeof(buf), f1)) > 0) { + if (fwrite(buf, 1, num, f2) != num) ret = 0; + } - fclose (f1); - fclose (f2); + fclose(f1); + fclose(f2); - if(EINA_TRUE != ret /*ecore_file_cp(attPath.c_str(), tmpPath.c_str())*/) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error while copying file to temp."); - } + if (EINA_TRUE != ret /*ecore_file_cp(attPath.c_str(), tmpPath.c_str())*/) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error while copying file to temp."); + } - *result_path = dirPath; - return PlatformResult(ErrorCode::NO_ERROR); + *result_path = dirPath; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult removeDirFromTemp(const std::string& dirPath) -{ - LoggerD("Entered"); - if(EINA_TRUE != ecore_file_recursive_rm(dirPath.c_str())) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error while deleting temp directory."); - } - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult removeDirFromTemp(const std::string& dirPath) { + LoggerD("Entered"); + if (EINA_TRUE != ecore_file_recursive_rm(dirPath.c_str())) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Unknown error while deleting temp directory."); + } + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult Message::convertPlatformEmail(std::shared_ptr message, - email_mail_data_t** result_mail_data) -{ - LoggerD("Entered"); - email_mail_data_t* mail_data = nullptr; - if(EMAIL != message->getType()) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid type."); - } + email_mail_data_t** result_mail_data) { + LoggerD("Entered"); + email_mail_data_t* mail_data = nullptr; + if (EMAIL != message->getType()) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid type."); + } - if(message->is_id_set()) { - int ret = email_get_mail_data(message->getId(), &mail_data); - if (EMAIL_ERROR_NONE != ret || !mail_data) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get mail data."); - } - } else { - mail_data = (email_mail_data_t*)malloc(sizeof(email_mail_data_t)); - if (!mail_data) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to allocate memory."); - } - memset(mail_data, 0x00, sizeof(email_mail_data_t)); + if (message->is_id_set()) { + int ret = email_get_mail_data(message->getId(), &mail_data); + if (EMAIL_ERROR_NONE != ret || !mail_data) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get mail data."); } - - std::unique_ptr mail_data_ptr( - mail_data, [](email_mail_data_t* mail) {email_free_mail_data(&mail, 1);}); - - if(!message->getFrom().empty()) { - std::string from = "<"+message->getFrom()+">"; - mail_data->full_address_from = strdup(from.c_str()); + } else { + mail_data = (email_mail_data_t*)malloc(sizeof(email_mail_data_t)); + if (!mail_data) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to allocate memory."); } + memset(mail_data, 0x00, sizeof(email_mail_data_t)); + } - if(!message->getTO().empty()) { - std::string to = Message::convertEmailRecipients(message->getTO()); - mail_data->full_address_to = strdup(to.c_str()); - } + std::unique_ptr mail_data_ptr( + mail_data, [](email_mail_data_t* mail) { email_free_mail_data(&mail, 1); }); - if(!message->getCC().empty()) { - std::string cc = Message::convertEmailRecipients(message->getCC()); - mail_data->full_address_cc = strdup(cc.c_str()); - } + if (!message->getFrom().empty()) { + std::string from = "<" + message->getFrom() + ">"; + mail_data->full_address_from = strdup(from.c_str()); + } - if(!message->getBCC().empty()) { - std::string bcc = Message::convertEmailRecipients(message->getBCC()); - mail_data->full_address_bcc = strdup(bcc.c_str()); - } + if (!message->getTO().empty()) { + std::string to = Message::convertEmailRecipients(message->getTO()); + mail_data->full_address_to = strdup(to.c_str()); + } - if(!message->getSubject().empty()) { - std::string subject = message->getSubject(); - mail_data->subject = strdup(subject.c_str()); - } + if (!message->getCC().empty()) { + std::string cc = Message::convertEmailRecipients(message->getCC()); + mail_data->full_address_cc = strdup(cc.c_str()); + } - if(message->getBody()) { - LoggerD("get Body success"); - std::shared_ptr body; - body = message->getBody(); - if(!body->getPlainBody().empty()) { - std::string body_file_path = ""; - PlatformResult ret = saveToTempFile(body->getPlainBody(), &body_file_path); - if (ret.IsError()) return ret; - mail_data->file_path_plain = strdup(body_file_path.c_str()); - if(!mail_data->file_path_plain) - { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Plain Body file is NULL."); - } - } + if (!message->getBCC().empty()) { + std::string bcc = Message::convertEmailRecipients(message->getBCC()); + mail_data->full_address_bcc = strdup(bcc.c_str()); + } - if(!body->getHtmlBody().empty()) { - std::string html_file_path = ""; - PlatformResult ret = saveToTempFile(body->getHtmlBody(), &html_file_path); - mail_data->file_path_html = strdup(html_file_path.c_str()); - if(!mail_data->file_path_html) - { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Html Body file is NULL."); - } - } else if(!body->getPlainBody().empty()) { - // check html data is exist if not exist copy plain body to html body - std::string html_file_path = ""; - PlatformResult ret = saveToTempFile(body->getPlainBody(), &html_file_path); - mail_data->file_path_html = strdup(html_file_path.c_str()); - if(!mail_data->file_path_html) - { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Plain Body file is NULL."); - } - } + if (!message->getSubject().empty()) { + std::string subject = message->getSubject(); + mail_data->subject = strdup(subject.c_str()); + } + + if (message->getBody()) { + LoggerD("get Body success"); + std::shared_ptr body; + body = message->getBody(); + if (!body->getPlainBody().empty()) { + std::string body_file_path = ""; + PlatformResult ret = saveToTempFile(body->getPlainBody(), &body_file_path); + if (ret.IsError()) return ret; + mail_data->file_path_plain = strdup(body_file_path.c_str()); + if (!mail_data->file_path_plain) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Plain Body file is NULL."); + } + } + + if (!body->getHtmlBody().empty()) { + std::string html_file_path = ""; + PlatformResult ret = saveToTempFile(body->getHtmlBody(), &html_file_path); + mail_data->file_path_html = strdup(html_file_path.c_str()); + if (!mail_data->file_path_html) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Html Body file is NULL."); + } + } else if (!body->getPlainBody().empty()) { + // check html data is exist if not exist copy plain body to html body + std::string html_file_path = ""; + PlatformResult ret = saveToTempFile(body->getPlainBody(), &html_file_path); + mail_data->file_path_html = strdup(html_file_path.c_str()); + if (!mail_data->file_path_html) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Plain Body file is NULL."); + } } + } - mail_data->flags_seen_field = message->getIsRead()?1:0; + mail_data->flags_seen_field = message->getIsRead() ? 1 : 0; - if(message->getIsHighPriority()) { - mail_data->priority = EMAIL_MAIL_PRIORITY_HIGH; - } else { - mail_data->priority = EMAIL_MAIL_PRIORITY_NORMAL; - } + if (message->getIsHighPriority()) { + mail_data->priority = EMAIL_MAIL_PRIORITY_HIGH; + } else { + mail_data->priority = EMAIL_MAIL_PRIORITY_NORMAL; + } - *result_mail_data = mail_data_ptr.release(); // release ownership - return PlatformResult(ErrorCode::NO_ERROR); + *result_mail_data = mail_data_ptr.release(); // release ownership + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult addSingleEmailAttachment(std::shared_ptr message, - std::shared_ptr att, AttachmentType attType) -{ - LoggerD("Entered"); - std::string dirPath = ""; - PlatformResult ret = copyFileToTemp(att->getFilePath(), &dirPath); - if (ret.IsError()) return ret; - - email_attachment_data_t* tmp = (email_attachment_data_t*)calloc(1, sizeof(email_attachment_data_t)); - if (nullptr == tmp) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error while adding attachment."); - } - tmp->attachment_name = strdup(att->getShortFileName().c_str()); - tmp->attachment_path = strdup(std::string(dirPath + "/" - + att->getShortFileName()).c_str()); - if (att->isMimeTypeSet()) { - tmp->attachment_mime_type = strdup(att->getMimeType().c_str()); - } - tmp->save_status = 1; - tmp->inline_content_status = attType; - - int id = message->getId(); - int err = email_add_attachment(id, tmp); - if(EMAIL_ERROR_NONE != err) { - int ntv_ret = email_free_attachment_data(&tmp, 1); - if (EMAIL_ERROR_NONE != ntv_ret) { - LoggerW("Failed to free attachment data: %d (%s)", ntv_ret, get_error_message(ntv_ret)); - } - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error while adding attachment", - ("email_add_attachment error: %d (%s)", err, get_error_message(err))); - } + std::shared_ptr att, + AttachmentType attType) { + LoggerD("Entered"); + std::string dirPath = ""; + PlatformResult ret = copyFileToTemp(att->getFilePath(), &dirPath); + if (ret.IsError()) return ret; + + email_attachment_data_t* tmp = + (email_attachment_data_t*)calloc(1, sizeof(email_attachment_data_t)); + if (nullptr == tmp) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error while adding attachment."); + } + tmp->attachment_name = strdup(att->getShortFileName().c_str()); + tmp->attachment_path = strdup(std::string(dirPath + "/" + att->getShortFileName()).c_str()); + if (att->isMimeTypeSet()) { + tmp->attachment_mime_type = strdup(att->getMimeType().c_str()); + } + tmp->save_status = 1; + tmp->inline_content_status = attType; + + int id = message->getId(); + int err = email_add_attachment(id, tmp); + if (EMAIL_ERROR_NONE != err) { + int ntv_ret = email_free_attachment_data(&tmp, 1); + if (EMAIL_ERROR_NONE != ntv_ret) { + LoggerW("Failed to free attachment data: %d (%s)", ntv_ret, get_error_message(ntv_ret)); + } + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error while adding attachment", + ("email_add_attachment error: %d (%s)", err, get_error_message(err))); + } - att->setId(tmp->attachment_id); - att->setMessageId(id); - err = email_free_attachment_data(&tmp, 1); - if (EMAIL_ERROR_NONE != err) { - LoggerW("Failed to free attachment data %d (%s)", err, get_error_message(err)); - } + att->setId(tmp->attachment_id); + att->setMessageId(id); + err = email_free_attachment_data(&tmp, 1); + if (EMAIL_ERROR_NONE != err) { + LoggerW("Failed to free attachment data %d (%s)", err, get_error_message(err)); + } - return removeDirFromTemp(dirPath); + return removeDirFromTemp(dirPath); } -PlatformResult Message::addEmailAttachments(std::shared_ptr message) -{ - LoggerD("Entered"); - - int attachment_data_count = 0, error; - email_mail_data_t *mail = NULL; - email_attachment_data_t *attachment_data_list = NULL; - email_meeting_request_t *meeting_req = NULL; +PlatformResult Message::addEmailAttachments(std::shared_ptr message) { + LoggerD("Entered"); - AttachmentPtrVector attachments = message->getMessageAttachments(); - AttachmentPtrVector inlineAttachments = message->getBody()->getInlineAttachments(); - LoggerD("Attachments size: %d", attachments.size()); - LoggerD("Inline attachments size: %d", inlineAttachments.size()); - LoggerD("Adding attachments for mail id = [%d]\n", message->getId()); - for (auto it = attachments.begin(); it != attachments.end(); ++it) { - PlatformResult ret = addSingleEmailAttachment(message, *it, AttachmentType::EXTERNAL); - if (ret.IsError()) return ret; - } - for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) { - PlatformResult ret = addSingleEmailAttachment(message, *it, AttachmentType::INLINE); - if (ret.IsError()) return ret; - } + int attachment_data_count = 0, error; + email_mail_data_t* mail = NULL; + email_attachment_data_t* attachment_data_list = NULL; + email_meeting_request_t* meeting_req = NULL; + + AttachmentPtrVector attachments = message->getMessageAttachments(); + AttachmentPtrVector inlineAttachments = message->getBody()->getInlineAttachments(); + LoggerD("Attachments size: %d", attachments.size()); + LoggerD("Inline attachments size: %d", inlineAttachments.size()); + LoggerD("Adding attachments for mail id = [%d]\n", message->getId()); + for (auto it = attachments.begin(); it != attachments.end(); ++it) { + PlatformResult ret = addSingleEmailAttachment(message, *it, AttachmentType::EXTERNAL); + if (ret.IsError()) return ret; + } + for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) { + PlatformResult ret = addSingleEmailAttachment(message, *it, AttachmentType::INLINE); + if (ret.IsError()) return ret; + } - //Update of mail on server using function email_update_mail() is not possible. - //Attachment is updated only locally, so there is need to use workaround: - //1. add new mail with null attachments list - //2. add attachments to mail (locally) - //3. create new email with attachments and add it to server - //4. delete mail without attachments + // Update of mail on server using function email_update_mail() is not possible. + // Attachment is updated only locally, so there is need to use workaround: + // 1. add new mail with null attachments list + // 2. add attachments to mail (locally) + // 3. create new email with attachments and add it to server + // 4. delete mail without attachments - //getting mail and attachments data - PlatformResult ret = Message::convertPlatformEmail(message, &mail); - if (ret.IsError()) return ret; + // getting mail and attachments data + PlatformResult ret = Message::convertPlatformEmail(message, &mail); + if (ret.IsError()) return ret; - error = email_get_attachment_data_list(mail->mail_id, &attachment_data_list, &attachment_data_count); - if (EMAIL_ERROR_NONE != error) { - email_free_mail_data(&mail, 1); - email_free_attachment_data(&attachment_data_list,attachment_data_count); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "Error while adding attachments. Failed to get attachment list.", - ("Error %d while adding attachments. Failed to get attachment list. (%s)", - error, get_error_message(error))); - } + error = + email_get_attachment_data_list(mail->mail_id, &attachment_data_list, &attachment_data_count); + if (EMAIL_ERROR_NONE != error) { + email_free_mail_data(&mail, 1); + email_free_attachment_data(&attachment_data_list, attachment_data_count); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while adding attachments. Failed to get attachment list.", + ("Error %d while adding attachments. Failed to get attachment list. (%s)", error, + get_error_message(error))); + } - //save mail without attachments id - int tmp_id = mail->mail_id; + // save mail without attachments id + int tmp_id = mail->mail_id; - //adding new mail with attachments - error = email_add_mail(mail, attachment_data_list, attachment_data_count, meeting_req, 0); - if (EMAIL_ERROR_NONE != error) { - email_free_mail_data(&mail, 1); - email_free_attachment_data(&attachment_data_list,attachment_data_count); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while re-adding mail", - ("Error %d while re-adding mail (%s)", error, get_error_message(error))); - } - LoggerD("mail added - new id = [%d]\n", mail->mail_id); + // adding new mail with attachments + error = email_add_mail(mail, attachment_data_list, attachment_data_count, meeting_req, 0); + if (EMAIL_ERROR_NONE != error) { + email_free_mail_data(&mail, 1); + email_free_attachment_data(&attachment_data_list, attachment_data_count); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while re-adding mail", + ("Error %d while re-adding mail (%s)", error, get_error_message(error))); + } + LoggerD("mail added - new id = [%d]\n", mail->mail_id); - //refresh message object - message->setId(mail->mail_id); - message->setMessageStatus(MessageStatus::STATUS_DRAFT); - for (auto it = attachments.begin(); it != attachments.end(); ++it) { - (*it)->setMessageId(mail->mail_id); - } - for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) { - (*it)->setMessageId(mail->mail_id); - } - email_free_attachment_data(&attachment_data_list,attachment_data_count); + // refresh message object + message->setId(mail->mail_id); + message->setMessageStatus(MessageStatus::STATUS_DRAFT); + for (auto it = attachments.begin(); it != attachments.end(); ++it) { + (*it)->setMessageId(mail->mail_id); + } + for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) { + (*it)->setMessageId(mail->mail_id); + } + email_free_attachment_data(&attachment_data_list, attachment_data_count); - //deleting mail without attachments - error = email_delete_mail(mail->mailbox_id,&tmp_id,1,1); - if (EMAIL_ERROR_NONE != error) { - email_free_mail_data(&mail, 1); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting mail from server", - ("email_delete_mail error: %d (%s)", error, get_error_message(error))); - } + // deleting mail without attachments + error = email_delete_mail(mail->mailbox_id, &tmp_id, 1, 1); + if (EMAIL_ERROR_NONE != error) { email_free_mail_data(&mail, 1); - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Message::addSMSRecipientsToStruct(const std::vector &recipients, - msg_struct_t &msg) -{ - LoggerD("Entered"); - const unsigned size = recipients.size(); - for (unsigned int i = 0; i < size; ++i) { - char *address = const_cast(recipients.at(i).c_str()); - - LoggerD("[%d] address:[%s]", i, address); - msg_struct_t tmpAddr = NULL; - if (MSG_SUCCESS - == msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr)) { - msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT, - MSG_ADDRESS_TYPE_PLMN); - msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, - MSG_RECIPIENTS_TYPE_TO); - msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, - address, strlen(address)); - } - else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add address", - ("failed to add address[%d] %s", i, address)); - } + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while deleting mail from server", + ("email_delete_mail error: %d (%s)", error, get_error_message(error))); + } + email_free_mail_data(&mail, 1); + return PlatformResult(ErrorCode::NO_ERROR); +} + +PlatformResult Message::addSMSRecipientsToStruct(const std::vector& recipients, + msg_struct_t& msg) { + LoggerD("Entered"); + const unsigned size = recipients.size(); + for (unsigned int i = 0; i < size; ++i) { + char* address = const_cast(recipients.at(i).c_str()); + + LoggerD("[%d] address:[%s]", i, address); + msg_struct_t tmpAddr = NULL; + if (MSG_SUCCESS == msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr)) { + msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT, MSG_ADDRESS_TYPE_PLMN); + msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, MSG_RECIPIENTS_TYPE_TO); + msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, address, strlen(address)); + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "failed to add address", + ("failed to add address[%d] %s", i, address)); } - return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::addMMSRecipientsToStruct(const std::vector &recipients, - msg_struct_t &msg, int type) -{ - LoggerD("Entered"); - const unsigned size = recipients.size(); - for (unsigned int i = 0; i < size; ++i) { +PlatformResult Message::addMMSRecipientsToStruct(const std::vector& recipients, + msg_struct_t& msg, int type) { + LoggerD("Entered"); + const unsigned size = recipients.size(); + for (unsigned int i = 0; i < size; ++i) { + msg_struct_t tmpAddr = NULL; + int address_type = MSG_ADDRESS_TYPE_PLMN; + const std::size_t found = recipients[i].find("@"); + if (std::string::npos != found) { + address_type = MSG_ADDRESS_TYPE_EMAIL; + } - msg_struct_t tmpAddr = NULL; - int address_type = MSG_ADDRESS_TYPE_PLMN; - const std::size_t found = recipients[i].find("@"); - if (std::string::npos != found) { - address_type = MSG_ADDRESS_TYPE_EMAIL; - } + char* address = const_cast(recipients.at(i).c_str()); + LoggerD("[%d] address:[%s] address_type:%d type:%d", i, address, address_type, type); - char *address = const_cast(recipients.at(i).c_str()); - LoggerD("[%d] address:[%s] address_type:%d type:%d", i, address, address_type, type); - - int error = msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr); - if (MSG_SUCCESS == error) { - msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT, - address_type); - msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, - type); - msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, - address, strlen(address)); - } - else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add address", - ("[%d] failed to add address: [%s], error: %d", i, address, error)); - } + int error = msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr); + if (MSG_SUCCESS == error) { + msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT, address_type); + msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, type); + msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, address, strlen(address)); + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "failed to add address", + ("[%d] failed to add address: [%s], error: %d", i, address, error)); } - return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector &attach, - msg_struct_t &mms_struct, Message* message) -{ - LoggerD("Entered with %d attachments", attach.size()); - - int size = attach.size(); - for (int i = 0; i < size; i++) { +PlatformResult Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector& attach, + msg_struct_t& mms_struct, + Message* message) { + LoggerD("Entered with %d attachments", attach.size()); - msg_struct_t tmpAtt = NULL; - int error = msg_list_add_item(mms_struct, MSG_STRUCT_MMS_ATTACH, &tmpAtt); - if (MSG_SUCCESS == error) { - - //Ensure we have right id set - attach[i]->setId(i+1); - attach[i]->setMessageId(message->getId()); - - //------------------------------------------------------------------------- - // set file path, file name, file size - if (attach.at(i)->isFilePathSet()) { - // get the file path - std::string filepath = attach.at(i)->getFilePath(); - SLoggerD("att[%d]: org filepath: %s", i, filepath.c_str()); - filepath = common::FilesystemProvider::Create().GetRealPath(filepath); - SLoggerD("att[%d]: org virtual filepath: %s", i, filepath.c_str()); - - // check if file exists - struct stat st = {0}; - if (stat(const_cast(filepath.c_str()), &st)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Attachment file not found", + int size = attach.size(); + for (int i = 0; i < size; i++) { + msg_struct_t tmpAtt = NULL; + int error = msg_list_add_item(mms_struct, MSG_STRUCT_MMS_ATTACH, &tmpAtt); + if (MSG_SUCCESS == error) { + // Ensure we have right id set + attach[i]->setId(i + 1); + attach[i]->setMessageId(message->getId()); + + //------------------------------------------------------------------------- + // set file path, file name, file size + if (attach.at(i)->isFilePathSet()) { + // get the file path + std::string filepath = attach.at(i)->getFilePath(); + SLoggerD("att[%d]: org filepath: %s", i, filepath.c_str()); + filepath = common::FilesystemProvider::Create().GetRealPath(filepath); + SLoggerD("att[%d]: org virtual filepath: %s", i, filepath.c_str()); + + // check if file exists + struct stat st = {0}; + if (stat(const_cast(filepath.c_str()), &st)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Attachment file not found", ("att[%d]: attachment file not found", i)); - } - // set the attachment size - const int fsize = st.st_size; - msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_FILESIZE_INT, fsize); - LoggerD("att[%d]: filesize: %d", i, fsize); - - // set the attachment file path - msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILEPATH_STR, - const_cast(filepath.c_str()), filepath.size()); - - // get the file name, update the attachment structure - const size_t last_slash_idx = filepath.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - filepath.erase(0, last_slash_idx + 1); - } - - SLoggerD("att[%d] filename: %s", i, filepath.c_str()); - msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILENAME_STR, - const_cast(filepath.c_str()), filepath.size()); - } - - //------------------------------------------------------------------------- - //set mime type - if (attach.at(i)->isMimeTypeSet()) { - unsigned int type = MessageAttachment::MIMETypeStringToEnum( - attach.at(i)->getMimeType()); - msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_MIME_TYPE_INT, type); - msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_CONTENT_TYPE_STR, - const_cast(attach.at(i)->getMimeType().c_str()), - MSG_MSG_ID_LEN); - - LoggerD("att[%d]: setting mime type:0x%x (orignal:%s)", i, type, - attach.at(i)->getMimeType().c_str()); - } - } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add attachment", - ("att[%d]: failed to add attachment", i)); } + // set the attachment size + const int fsize = st.st_size; + msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_FILESIZE_INT, fsize); + LoggerD("att[%d]: filesize: %d", i, fsize); + + // set the attachment file path + msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILEPATH_STR, const_cast(filepath.c_str()), + filepath.size()); + + // get the file name, update the attachment structure + const size_t last_slash_idx = filepath.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + filepath.erase(0, last_slash_idx + 1); + } + + SLoggerD("att[%d] filename: %s", i, filepath.c_str()); + msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILENAME_STR, const_cast(filepath.c_str()), + filepath.size()); + } + + //------------------------------------------------------------------------- + // set mime type + if (attach.at(i)->isMimeTypeSet()) { + unsigned int type = MessageAttachment::MIMETypeStringToEnum(attach.at(i)->getMimeType()); + msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_MIME_TYPE_INT, type); + msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_CONTENT_TYPE_STR, + const_cast(attach.at(i)->getMimeType().c_str()), MSG_MSG_ID_LEN); + + LoggerD("att[%d]: setting mime type:0x%x (orignal:%s)", i, type, + attach.at(i)->getMimeType().c_str()); + } + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "failed to add attachment", + ("att[%d]: failed to add attachment", i)); } - return PlatformResult(ErrorCode::NO_ERROR); + } + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::convertPlatformShortMessageToStruct(Message* message, - msg_handle_t handle, msg_struct_t* result_msg) -{ - LoggerD("Entered"); +PlatformResult Message::convertPlatformShortMessageToStruct(Message* message, msg_handle_t handle, + msg_struct_t* result_msg) { + LoggerD("Entered"); + + int ntv_ret = 0; - int ntv_ret = 0; + if (message->getType() != SMS && message->getType() != MMS) { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid type", + ("Invalid type: %d", message->getType())); + } - if (message->getType() != SMS && message->getType() != MMS) { + msg_error_t err = MSG_SUCCESS; + + msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); + std::unique_ptr msg_ptr(&msg, msg_release_struct); + + if (message->is_id_set()) { // id is set - the message exists in database + msg_message_id_t id = (msg_message_id_t)message->getId(); + msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); + std::unique_ptr send_opt_ptr(&send_opt, + msg_release_struct); + err = msg_get_message(handle, id, msg, send_opt); + if (err != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "msg_get_message() Fail", + ("msg_get_message() Fail [%d] (%s)", err, get_error_message(err))); + } + LoggerD("Using existing msg for id: %d", id); + } else { // id is not set - the message does not exist in database + MessageType msgType = message->getType(); + if (msgType == MessageType::SMS) { + // Set message type to SMS + ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_SMS); + if (MSG_SUCCESS != ntv_ret) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Set SMS type error", + ("msg_set_int_value error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } + } else { + // Set message type to MMS + ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS); + if (MSG_SUCCESS != ntv_ret) { return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid type", - ("Invalid type: %d", message->getType())); + ErrorCode::UNKNOWN_ERR, "Set MMS type error", + ("msg_set_int_value error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } } + } - msg_error_t err = MSG_SUCCESS; - - msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); - std::unique_ptr msg_ptr(&msg, msg_release_struct); + int type; + msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &type); + LoggerD("Message(%p): MSG_MESSAGE_TYPE = %d", message, type); - if (message->is_id_set()) { // id is set - the message exists in database - msg_message_id_t id = (msg_message_id_t) message->getId(); - msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); - std::unique_ptr send_opt_ptr(&send_opt, msg_release_struct); - err = msg_get_message(handle, id, msg, send_opt); - if (err != MSG_SUCCESS) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "msg_get_message() Fail", - ("msg_get_message() Fail [%d] (%s)", err, get_error_message(err))); - } - LoggerD("Using existing msg for id: %d", id); - } else { // id is not set - the message does not exist in database - MessageType msgType = message->getType(); - if (msgType == MessageType::SMS) { - // Set message type to SMS - ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_SMS); - if (MSG_SUCCESS != ntv_ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set SMS type error", - ("msg_set_int_value error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } - } else { - // Set message type to MMS - ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS); - if (MSG_SUCCESS != ntv_ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set MMS type error", - ("msg_set_int_value error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } - } + if (type == MSG_TYPE_SMS) { + // Set SMS message body text + std::shared_ptr body; + body = message->getBody(); + if (!body->getPlainBody().empty()) { + msg_set_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, + const_cast(body->getPlainBody().c_str()), + body->getPlainBody().size()); } - int type; - msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &type); - LoggerD("Message(%p): MSG_MESSAGE_TYPE = %d", message, type); - - if (type == MSG_TYPE_SMS) { - // Set SMS message body text - std::shared_ptr body; - body = message->getBody(); - if (!body->getPlainBody().empty()) { - msg_set_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, const_cast - (body->getPlainBody().c_str()), body->getPlainBody().size()); - } - - // Reset SMS recipients - int error = msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND); - if( MSG_SUCCESS != error) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to clear address list", - ("msg_list_clear error: %d (%s)", error, get_error_message(error))); - } - - // Set SMS recipients - std::vector recp_list = message->getTO(); - if (!recp_list.empty()) { - PlatformResult ret = message->addSMSRecipientsToStruct(recp_list, msg); - if (ret.IsError()) return ret; + // Reset SMS recipients + int error = msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND); + if (MSG_SUCCESS != error) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to clear address list", + ("msg_list_clear error: %d (%s)", error, get_error_message(error))); + } + + // Set SMS recipients + std::vector recp_list = message->getTO(); + if (!recp_list.empty()) { + PlatformResult ret = message->addSMSRecipientsToStruct(recp_list, msg); + if (ret.IsError()) return ret; + } + + } else if (type == MSG_TYPE_MMS) { + // Set message type to MMS + ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS); + if (MSG_SUCCESS != ntv_ret) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set MMS type error", + ("Message(%p): Set MMS type error %d (%s)", message, ntv_ret, + get_error_message(ntv_ret))); + } + // Create MMS data + msg_struct_t mms_data = msg_create_struct(MSG_STRUCT_MMS); + if (mms_data == NULL) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set MMS data error", + ("Message(%p): Set MMS data error", message)); + } else { + std::unique_ptr mms_data_ptr(&mms_data, + msg_release_struct); + // Set MMS message subject + std::string subject = message->getSubject(); + if (subject != "") { + ntv_ret = msg_set_str_value(msg, MSG_MESSAGE_SUBJECT_STR, + const_cast(subject.c_str()), subject.size()); + if (ntv_ret != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set MMS subject error", + ("Message(%p): Set MMS subject error: %d (%s)", message, + ntv_ret, get_error_message(ntv_ret))); } + } + // Set MMS message text + std::shared_ptr body; + body = message->getBody(); + if (!body->getPlainBody().empty()) { + LoggerD("Message(%p): PlainBody is NOT empty", message); + + static const int ROOT_LAYOUT_WIDTH = 100; + static const int ROOT_LAYOUT_HEIGHT = 100; + static const int WHITE_COLOR = 0xffffff; + static const int BLACK_COLOR = 0x000000; + + //---------------------------------------------------------------------------- + // Region + msg_struct_t region; + msg_list_add_item(mms_data, MSG_STRUCT_MMS_REGION, ®ion); + msg_set_str_value(region, MSG_MMS_REGION_ID_STR, const_cast("Text"), 4); + + msg_set_int_value(region, MSG_MMS_REGION_LENGTH_LEFT_INT, 0); + msg_set_int_value(region, MSG_MMS_REGION_LENGTH_TOP_INT, 0); + msg_set_int_value(region, MSG_MMS_REGION_LENGTH_WIDTH_INT, ROOT_LAYOUT_WIDTH); + msg_set_int_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_INT, ROOT_LAYOUT_HEIGHT); + msg_set_int_value(region, MSG_MMS_REGION_BGCOLOR_INT, WHITE_COLOR); + + msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL, true); + msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL, true); + msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL, true); + msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL, true); + + //---------------------------------------------------------------------------- + // Page + msg_struct_t page; + msg_list_add_item(mms_data, MSG_STRUCT_MMS_PAGE, &page); + msg_set_int_value(page, MSG_MMS_PAGE_PAGE_DURATION_INT, 0); + + //---------------------------------------------------------------------------- + // Media + msg_struct_t media; + msg_list_add_item(page, MSG_STRUCT_MMS_MEDIA, &media); + msg_set_int_value(media, MSG_MMS_MEDIA_TYPE_INT, MMS_SMIL_MEDIA_TEXT); + msg_set_str_value(media, MSG_MMS_MEDIA_REGION_ID_STR, const_cast("Text"), 4); + + std::string body_file_path = ""; + PlatformResult ret = saveToTempFile(body->getPlainBody(), &body_file_path); + if (ret.IsError()) return ret; - } else if (type == MSG_TYPE_MMS) { - // Set message type to MMS - ntv_ret = msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS); - if (MSG_SUCCESS != ntv_ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set MMS type error", - ("Message(%p): Set MMS type error %d (%s)", message, ntv_ret, get_error_message(ntv_ret))); - } - // Create MMS data - msg_struct_t mms_data = msg_create_struct(MSG_STRUCT_MMS); - if (mms_data == NULL) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set MMS data error", - ("Message(%p): Set MMS data error", message)); - } else { - std::unique_ptr mms_data_ptr(&mms_data, msg_release_struct); - // Set MMS message subject - std::string subject = message->getSubject(); - if (subject != "") { - ntv_ret = msg_set_str_value(msg, MSG_MESSAGE_SUBJECT_STR, - const_cast(subject.c_str()), subject.size()); - if (ntv_ret != MSG_SUCCESS) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set MMS subject error", - ("Message(%p): Set MMS subject error: %d (%s)", message, ntv_ret, get_error_message(ntv_ret))); - } - } - // Set MMS message text - std::shared_ptr body; - body = message->getBody(); - if (!body->getPlainBody().empty()) { - LoggerD("Message(%p): PlainBody is NOT empty", message); - - static const int ROOT_LAYOUT_WIDTH = 100; - static const int ROOT_LAYOUT_HEIGHT = 100; - static const int WHITE_COLOR = 0xffffff; - static const int BLACK_COLOR = 0x000000; - - //---------------------------------------------------------------------------- - //Region - msg_struct_t region; - msg_list_add_item(mms_data, MSG_STRUCT_MMS_REGION, ®ion); - msg_set_str_value(region, MSG_MMS_REGION_ID_STR, const_cast("Text"), 4); - - msg_set_int_value(region, MSG_MMS_REGION_LENGTH_LEFT_INT, 0); - msg_set_int_value(region, MSG_MMS_REGION_LENGTH_TOP_INT, 0); - msg_set_int_value(region, MSG_MMS_REGION_LENGTH_WIDTH_INT, - ROOT_LAYOUT_WIDTH); - msg_set_int_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_INT, - ROOT_LAYOUT_HEIGHT); - msg_set_int_value(region, MSG_MMS_REGION_BGCOLOR_INT, WHITE_COLOR); - - msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL, true); - msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL, true); - msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL, true); - msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL, true); - - //---------------------------------------------------------------------------- - //Page - msg_struct_t page; - msg_list_add_item(mms_data, MSG_STRUCT_MMS_PAGE, &page); - msg_set_int_value(page, MSG_MMS_PAGE_PAGE_DURATION_INT, 0); - - //---------------------------------------------------------------------------- - //Media - msg_struct_t media; - msg_list_add_item(page, MSG_STRUCT_MMS_MEDIA, &media); - msg_set_int_value(media, MSG_MMS_MEDIA_TYPE_INT, MMS_SMIL_MEDIA_TEXT); - msg_set_str_value(media, MSG_MMS_MEDIA_REGION_ID_STR, - const_cast("Text"), 4); - - std::string body_file_path = ""; - PlatformResult ret = saveToTempFile(body->getPlainBody(), &body_file_path); - if (ret.IsError()) return ret; - - int error = msg_set_str_value(media, - MSG_MMS_MEDIA_FILEPATH_STR, - const_cast(body_file_path.c_str()), - body_file_path.size()); - if (error != MSG_SUCCESS) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to set mms body filepath", - ("Message(%p): Failed to set mms body filepath %d (%s)", - message, error, get_error_message(error))); - } - msg_set_str_value(media, MSG_MMS_MEDIA_CONTENT_TYPE_STR, - const_cast("text/plain"), 10); - - //---------------------------------------------------------------------------- - //Smile text - msg_struct_t smil_text; - msg_get_struct_handle(media, MSG_MMS_MEDIA_SMIL_TEXT_HND, &smil_text); - msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_COLOR_INT, BLACK_COLOR); - msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_SIZE_INT, - MMS_SMIL_FONT_SIZE_NORMAL); - msg_set_bool_value(smil_text, MSG_MMS_SMIL_TEXT_BOLD_BOOL, true); - } else { - LoggerD("Message(%p): PlainBody is EMPTY", message); - } - // Set MMS attachments - AttachmentPtrVector attach_list = message->getMessageAttachments(); - LoggerD("Message(%p): id:%d subject:[%s] plainBody:[%s] contains %d attachments", - message, message->getId(), message->getSubject().c_str(), - message->getBody()->getPlainBody().c_str(), attach_list.size()); - - msg_set_int_value(mms_data, MSG_MESSAGE_ATTACH_COUNT_INT, - attach_list.size()); - if (!attach_list.empty()) { - PlatformResult ret =addMMSBodyAndAttachmentsToStruct(attach_list, mms_data, message); - if (ret.IsError()) return ret; - } - // Set MMS body - ntv_ret = msg_set_mms_struct(msg, mms_data); - if (ntv_ret != MSG_SUCCESS) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Set MMS body error", - ("Message(%p): Set MMS body error: %d (%s)", - message, ntv_ret, get_error_message(ntv_ret))); - } + int error = + msg_set_str_value(media, MSG_MMS_MEDIA_FILEPATH_STR, + const_cast(body_file_path.c_str()), body_file_path.size()); + if (error != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set mms body filepath", + ("Message(%p): Failed to set mms body filepath %d (%s)", + message, error, get_error_message(error))); } + msg_set_str_value(media, MSG_MMS_MEDIA_CONTENT_TYPE_STR, const_cast("text/plain"), + 10); + + //---------------------------------------------------------------------------- + // Smile text + msg_struct_t smil_text; + msg_get_struct_handle(media, MSG_MMS_MEDIA_SMIL_TEXT_HND, &smil_text); + msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_COLOR_INT, BLACK_COLOR); + msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_SIZE_INT, MMS_SMIL_FONT_SIZE_NORMAL); + msg_set_bool_value(smil_text, MSG_MMS_SMIL_TEXT_BOLD_BOOL, true); + } else { + LoggerD("Message(%p): PlainBody is EMPTY", message); + } + // Set MMS attachments + AttachmentPtrVector attach_list = message->getMessageAttachments(); + LoggerD("Message(%p): id:%d subject:[%s] plainBody:[%s] contains %d attachments", message, + message->getId(), message->getSubject().c_str(), + message->getBody()->getPlainBody().c_str(), attach_list.size()); + + msg_set_int_value(mms_data, MSG_MESSAGE_ATTACH_COUNT_INT, attach_list.size()); + if (!attach_list.empty()) { + PlatformResult ret = addMMSBodyAndAttachmentsToStruct(attach_list, mms_data, message); + if (ret.IsError()) return ret; + } + // Set MMS body + ntv_ret = msg_set_mms_struct(msg, mms_data); + if (ntv_ret != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set MMS body error", + ("Message(%p): Set MMS body error: %d (%s)", message, ntv_ret, + get_error_message(ntv_ret))); + } + } - // Reset MMS recipients - msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND); + // Reset MMS recipients + msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND); - std::vector recp_list = message->getTO(); - PlatformResult ret = message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_TO); - if (ret.IsError()) return ret; + std::vector recp_list = message->getTO(); + PlatformResult ret = message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_TO); + if (ret.IsError()) return ret; - recp_list = message->getCC(); - ret = message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_CC); - if (ret.IsError()) return ret; + recp_list = message->getCC(); + ret = message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_CC); + if (ret.IsError()) return ret; - recp_list = message->getBCC(); - ret =message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_BCC); - if (ret.IsError()) return ret; - } - else { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid message type", - ("Message(%p): Invalid message type", message)); - } + recp_list = message->getBCC(); + ret = message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_BCC); + if (ret.IsError()) return ret; + } else { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid message type", + ("Message(%p): Invalid message type", message)); + } - // set common attributes for SMS and MMS - // Set message conversation id - if (message->is_conversation_id_set()) { - msg_set_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, message->getConversationId()); - } - // Set message folder id - if (message->is_folder_id_set()) { - msg_set_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, message->getFolderId()); - } - // Set message timestamp - if (message->is_timestamp_set()) { - msg_set_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, message->getTimestamp()); - } - // Set message from - if (message->is_from_set()) { - msg_set_str_value(msg, MSG_MESSAGE_REPLY_ADDR_STR, const_cast - (message->getFrom().c_str()), message->getFrom().size()); - } - // Set message if is response - if (message->is_in_response_set()) { - msg_set_int_value(msg, MSG_MESSAGE_DIRECTION_INT, message->getInResponseTo()); - } + // set common attributes for SMS and MMS + // Set message conversation id + if (message->is_conversation_id_set()) { + msg_set_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, message->getConversationId()); + } + // Set message folder id + if (message->is_folder_id_set()) { + msg_set_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, message->getFolderId()); + } + // Set message timestamp + if (message->is_timestamp_set()) { + msg_set_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, message->getTimestamp()); + } + // Set message from + if (message->is_from_set()) { + msg_set_str_value(msg, MSG_MESSAGE_REPLY_ADDR_STR, + const_cast(message->getFrom().c_str()), message->getFrom().size()); + } + // Set message if is response + if (message->is_in_response_set()) { + msg_set_int_value(msg, MSG_MESSAGE_DIRECTION_INT, message->getInResponseTo()); + } - // Set SIM index - // -1 means unknown - so do not set simindex in that case. - int sim_index = static_cast(message->getSimIndex()); - if (sim_index != -1) { - int error = msg_set_int_value(msg, MSG_MESSAGE_SIM_INDEX_INT, sim_index+1); - if (MSG_SUCCESS != error) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to set sim index", - ("msg_set_int_value error: %d (%s)", error, get_error_message(error))); - } + // Set SIM index + // -1 means unknown - so do not set simindex in that case. + int sim_index = static_cast(message->getSimIndex()); + if (sim_index != -1) { + int error = msg_set_int_value(msg, MSG_MESSAGE_SIM_INDEX_INT, sim_index + 1); + if (MSG_SUCCESS != error) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to set sim index", + ("msg_set_int_value error: %d (%s)", error, get_error_message(error))); } + } - // Set message if is read - msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, message->getIsRead()); + // Set message if is read + msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, message->getIsRead()); - LoggerD("End"); - *result_msg = msg; - msg_ptr.release(); // release ownership - return PlatformResult(ErrorCode::NO_ERROR); + LoggerD("End"); + *result_msg = msg; + msg_ptr.release(); // release ownership + return PlatformResult(ErrorCode::NO_ERROR); } -std::string Message::getShortMsgSenderFromStruct(msg_struct_t &msg) -{ - LoggerD("Entered"); - msg_list_handle_t addr_list = NULL; - msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list); - - char str_phone_number[MAX_ADDRESS_VAL_LEN]; - const int count = msg_list_length(addr_list); - LoggerD("Number of addresses: %d", count); +std::string Message::getShortMsgSenderFromStruct(msg_struct_t& msg) { + LoggerD("Entered"); + msg_list_handle_t addr_list = NULL; + msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); - for (int i = 0; i < count; ++i) - { - int tempInt = 0; - msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &tempInt); - const int type = tempInt; + char str_phone_number[MAX_ADDRESS_VAL_LEN]; + const int count = msg_list_length(addr_list); + LoggerD("Number of addresses: %d", count); - if (MSG_DIRECTION_TYPE_MT == type) - { - msg_struct_t cur_addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i); - msg_get_str_value(cur_addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, - str_phone_number, MAX_ADDRESS_VAL_LEN); + for (int i = 0; i < count; ++i) { + int tempInt = 0; + msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &tempInt); + const int type = tempInt; - LoggerD("[%d/%d] is TYPE_MT, phone number is: %s", i, count, str_phone_number); + if (MSG_DIRECTION_TYPE_MT == type) { + msg_struct_t cur_addr_info = (msg_struct_t)msg_list_nth_data(addr_list, i); + msg_get_str_value(cur_addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, str_phone_number, + MAX_ADDRESS_VAL_LEN); - if(0 != str_phone_number[0]) { - return std::string(str_phone_number); - } - } else { - LoggerD("[%d/%d] is NOT of TYPE_MT skipping, is:%d", i, count, type); - } - } + LoggerD("[%d/%d] is TYPE_MT, phone number is: %s", i, count, str_phone_number); - return std::string(); -} - -PlatformResult Message::getSMSRecipientsFromStruct(msg_struct_t &msg, - std::vector* result_address) -{ - LoggerD("Entered"); - std::vector address; - msg_list_handle_t addr_list = NULL; - int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void **) &addr_list); - if (MSG_SUCCESS == ntv_ret) { - int size = msg_list_length(addr_list); - for (int i = 0; i < size; i++) { - msg_struct_t addr_info = NULL; - char infoStr[MAX_ADDRESS_VAL_LEN]; - //get address - addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i); - msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, - infoStr, MAX_ADDRESS_VAL_LEN); - address.push_back(std::string(infoStr)); - } - } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add recipients", - ("msg_get_list_handle error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } - *result_address = address; - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Message::getMMSRecipientsFromStruct(msg_struct_t &msg, - int type, std::vector* result_address) -{ - LoggerD("Entered"); - std::vector address; - msg_list_handle_t addr_list = NULL; - int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void **) &addr_list); - if (MSG_SUCCESS == ntv_ret) { - int size = msg_list_length(addr_list); - for (int i = 0; i < size; i++) { - msg_struct_t addr_info = NULL; - char infoStr[MAX_ADDRESS_VAL_LEN]; - int tempInt; - //get address - addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i); - msg_get_int_value(addr_info, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, - &tempInt); - if (tempInt == type) { - msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, - infoStr, MAX_ADDRESS_VAL_LEN); - address.push_back(std::string(infoStr)); - } - } + if (0 != str_phone_number[0]) { + return std::string(str_phone_number); + } } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add recipients", - ("msg_get_list_handle error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + LoggerD("[%d/%d] is NOT of TYPE_MT skipping, is:%d", i, count, type); } - *result_address = address; - return PlatformResult(ErrorCode::NO_ERROR); + } + + return std::string(); } -PlatformResult Message::setMMSBodyAndAttachmentsFromStruct(Message* message, - msg_struct_t &msg) -{ - LoggerD("Entered message(%p)", message); - int tempInt = 0; - char infoStr[MSG_FILEPATH_LEN_MAX + 1]; +PlatformResult Message::getSMSRecipientsFromStruct(msg_struct_t& msg, + std::vector* result_address) { + LoggerD("Entered"); + std::vector address; + msg_list_handle_t addr_list = NULL; + int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); + if (MSG_SUCCESS == ntv_ret) { + int size = msg_list_length(addr_list); + for (int i = 0; i < size; i++) { + msg_struct_t addr_info = NULL; + char infoStr[MAX_ADDRESS_VAL_LEN]; + // get address + addr_info = (msg_struct_t)msg_list_nth_data(addr_list, i); + msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, infoStr, + MAX_ADDRESS_VAL_LEN); + address.push_back(std::string(infoStr)); + } + } else { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "failed to add recipients", + ("msg_get_list_handle error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } + *result_address = address; + return PlatformResult(ErrorCode::NO_ERROR); +} - msg_struct_t mms_struct = msg_create_struct(MSG_STRUCT_MMS); - int error = msg_get_mms_struct(msg, mms_struct); - if (MSG_SUCCESS != error) { - msg_release_struct(&mms_struct); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "cannot get mms struct", - ("msg_get_mms_struct error: %d (%s)", error, get_error_message(error))); - } +PlatformResult Message::getMMSRecipientsFromStruct(msg_struct_t& msg, int type, + std::vector* result_address) { + LoggerD("Entered"); + std::vector address; + msg_list_handle_t addr_list = NULL; + int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); + if (MSG_SUCCESS == ntv_ret) { + int size = msg_list_length(addr_list); + for (int i = 0; i < size; i++) { + msg_struct_t addr_info = NULL; + char infoStr[MAX_ADDRESS_VAL_LEN]; + int tempInt; + // get address + addr_info = (msg_struct_t)msg_list_nth_data(addr_list, i); + msg_get_int_value(addr_info, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, &tempInt); + if (tempInt == type) { + msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, infoStr, + MAX_ADDRESS_VAL_LEN); + address.push_back(std::string(infoStr)); + } + } + } else { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "failed to add recipients", + ("msg_get_list_handle error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } + *result_address = address; + return PlatformResult(ErrorCode::NO_ERROR); +} - bool body_has_been_set = false; - // if there are some pages in msg_struct_t - msg_list_handle_t page_list = NULL; - error = msg_get_list_handle(mms_struct, MSG_MMS_PAGE_LIST_HND, (void **) &page_list); - if (MSG_SUCCESS == error) { - int pageLen = msg_list_length(page_list); - LoggerD("MSG_MMS_PAGE_LIST length:%d", pageLen); - - for (int p = 0; p < pageLen; ++p) { - msg_struct_t page = (msg_struct_t) msg_list_nth_data(page_list, p); - if (!page) { - LoggerE("returned page is null, continue"); - continue; - } +PlatformResult Message::setMMSBodyAndAttachmentsFromStruct(Message* message, msg_struct_t& msg) { + LoggerD("Entered message(%p)", message); + int tempInt = 0; + char infoStr[MSG_FILEPATH_LEN_MAX + 1]; + + msg_struct_t mms_struct = msg_create_struct(MSG_STRUCT_MMS); + int error = msg_get_mms_struct(msg, mms_struct); + if (MSG_SUCCESS != error) { + msg_release_struct(&mms_struct); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "cannot get mms struct", + ("msg_get_mms_struct error: %d (%s)", error, get_error_message(error))); + } - msg_list_handle_t media_list = NULL; - error = msg_get_list_handle(page, MSG_MMS_PAGE_MEDIA_LIST_HND, - (void **) &media_list); - if (MSG_SUCCESS == error) { - int mediaLen = msg_list_length(media_list); - LoggerD("[p:%d] MSG_MMS_PAGE_MEDIA_LIST length:%d", p, mediaLen); - - for (int m = 0; m < mediaLen; ++m) { - msg_struct_t media = (msg_struct_t) msg_list_nth_data(media_list, m); - if (NULL == media) { - LoggerE("returned media is null, continue"); - continue; - } - // add media from pages to attachments vector - //set file path - memset(infoStr, 0, MSG_FILEPATH_LEN_MAX + 1); - msg_get_str_value(media, MSG_MMS_MEDIA_FILEPATH_STR, infoStr, - MSG_FILEPATH_LEN_MAX); - LoggerD("[p:%d, m:%d] attachment file path:%s", p, m, infoStr); - - msg_get_int_value(media, MSG_MMS_MEDIA_TYPE_INT, &tempInt); - const int msg_media_type = tempInt; - std::string msg_media_type_str = - MessageAttachment::MIMETypeEnumToString(msg_media_type); - - LoggerD("[p:%d, m:%d] MSG_MMS_MEDIA_TYPE: %d (%s)", p, m, msg_media_type, - msg_media_type_str.c_str()); - - //According to old implementation - // "text value on first page goes to body attribute" - if ((0 == p) && (MMS_SMIL_MEDIA_TEXT == msg_media_type)) { - LoggerD("Loading body from file: %s ", infoStr); - - std::string result = ""; - PlatformResult ret = MessagingUtil::loadFileContentToString(infoStr, &result); - if (ret.IsSuccess()) { - - message->getBody()->setPlainBody(result); - body_has_been_set = true; - - LoggerD("Loaded body: %s", - message->getBody()->getPlainBody().c_str()); - } else { - LoggerE("Unhandled error: %d (%s)!", - ret.error_code(), ret.message().c_str()); - LoggerD("[p:%d, m:%d] body is not set", p, m); - } - } else { - std::shared_ptr ma (new MessageAttachment()); - ma->setFilePath(infoStr); - - //set message id - msg_get_int_value(msg, MSG_MESSAGE_STORAGE_ID_INT, &tempInt); - ma->setMessageId(tempInt); - - //set id - ma->setId(message->m_attachments.size() + 1); - message->m_attachments.push_back(ma); - message->m_has_attachment = true; - - //set mime type - ma->setMimeType(msg_media_type_str); - - MessageAttachment* att = ma.get(); - LoggerD("[p:%d, m:%d] added attachment: %p " - "(mime:0x%x mime:%s messageId:%d)", p, m, att, - msg_media_type, msg_media_type_str.c_str(), - ma->getMessageId()); - } - - msg_release_struct(&media); - } + bool body_has_been_set = false; + // if there are some pages in msg_struct_t + msg_list_handle_t page_list = NULL; + error = msg_get_list_handle(mms_struct, MSG_MMS_PAGE_LIST_HND, (void**)&page_list); + if (MSG_SUCCESS == error) { + int pageLen = msg_list_length(page_list); + LoggerD("MSG_MMS_PAGE_LIST length:%d", pageLen); + + for (int p = 0; p < pageLen; ++p) { + msg_struct_t page = (msg_struct_t)msg_list_nth_data(page_list, p); + if (!page) { + LoggerE("returned page is null, continue"); + continue; + } + + msg_list_handle_t media_list = NULL; + error = msg_get_list_handle(page, MSG_MMS_PAGE_MEDIA_LIST_HND, (void**)&media_list); + if (MSG_SUCCESS == error) { + int mediaLen = msg_list_length(media_list); + LoggerD("[p:%d] MSG_MMS_PAGE_MEDIA_LIST length:%d", p, mediaLen); + + for (int m = 0; m < mediaLen; ++m) { + msg_struct_t media = (msg_struct_t)msg_list_nth_data(media_list, m); + if (NULL == media) { + LoggerE("returned media is null, continue"); + continue; + } + // add media from pages to attachments vector + // set file path + memset(infoStr, 0, MSG_FILEPATH_LEN_MAX + 1); + msg_get_str_value(media, MSG_MMS_MEDIA_FILEPATH_STR, infoStr, MSG_FILEPATH_LEN_MAX); + LoggerD("[p:%d, m:%d] attachment file path:%s", p, m, infoStr); + + msg_get_int_value(media, MSG_MMS_MEDIA_TYPE_INT, &tempInt); + const int msg_media_type = tempInt; + std::string msg_media_type_str = MessageAttachment::MIMETypeEnumToString(msg_media_type); + + LoggerD("[p:%d, m:%d] MSG_MMS_MEDIA_TYPE: %d (%s)", p, m, msg_media_type, + msg_media_type_str.c_str()); + + // According to old implementation + // "text value on first page goes to body attribute" + if ((0 == p) && (MMS_SMIL_MEDIA_TEXT == msg_media_type)) { + LoggerD("Loading body from file: %s ", infoStr); + + std::string result = ""; + PlatformResult ret = MessagingUtil::loadFileContentToString(infoStr, &result); + if (ret.IsSuccess()) { + message->getBody()->setPlainBody(result); + body_has_been_set = true; + + LoggerD("Loaded body: %s", message->getBody()->getPlainBody().c_str()); } else { - msg_release_struct(&mms_struct); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to get attachment", - ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); + LoggerE("Unhandled error: %d (%s)!", ret.error_code(), ret.message().c_str()); + LoggerD("[p:%d, m:%d] body is not set", p, m); } - msg_release_struct(&page); + } else { + std::shared_ptr ma(new MessageAttachment()); + ma->setFilePath(infoStr); + + // set message id + msg_get_int_value(msg, MSG_MESSAGE_STORAGE_ID_INT, &tempInt); + ma->setMessageId(tempInt); + + // set id + ma->setId(message->m_attachments.size() + 1); + message->m_attachments.push_back(ma); + message->m_has_attachment = true; + + // set mime type + ma->setMimeType(msg_media_type_str); + + MessageAttachment* att = ma.get(); + LoggerD( + "[p:%d, m:%d] added attachment: %p " + "(mime:0x%x mime:%s messageId:%d)", + p, m, att, msg_media_type, msg_media_type_str.c_str(), ma->getMessageId()); + } + + msg_release_struct(&media); } - } else { + } else { msg_release_struct(&mms_struct); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to get attachment", - ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); - } - - if(false == body_has_been_set) { - LoggerW("Warning: body has not been set!"); + ErrorCode::UNKNOWN_ERR, "failed to get attachment", + ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); + } + msg_release_struct(&page); } + } else { + msg_release_struct(&mms_struct); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "failed to get attachment", + ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); + } - LoggerD("after MSG_MMS_PAGE_LIST attachments count is:%d", - message->m_attachments.size()); + if (false == body_has_been_set) { + LoggerW("Warning: body has not been set!"); + } - // if there are some other attachments add it to attachments vector - msg_list_handle_t attach_list = NULL; - error = msg_get_list_handle(mms_struct, MSG_MMS_ATTACH_LIST_HND, (void **) - &attach_list); - if (MSG_SUCCESS == error) { + LoggerD("after MSG_MMS_PAGE_LIST attachments count is:%d", message->m_attachments.size()); - int size = msg_list_length(attach_list); - LoggerD("MSG_MMS_ATTACH_LIST length:%d", size); + // if there are some other attachments add it to attachments vector + msg_list_handle_t attach_list = NULL; + error = msg_get_list_handle(mms_struct, MSG_MMS_ATTACH_LIST_HND, (void**)&attach_list); + if (MSG_SUCCESS == error) { + int size = msg_list_length(attach_list); + LoggerD("MSG_MMS_ATTACH_LIST length:%d", size); - for (int i = 0; i < size; i++) { - msg_struct_t attach_info = NULL; - attach_info = (msg_struct_t) msg_list_nth_data(attach_list, i); - if(!attach_info) { - LoggerW("[att:%d] attach_info is NULL!", i); - continue; - } + for (int i = 0; i < size; i++) { + msg_struct_t attach_info = NULL; + attach_info = (msg_struct_t)msg_list_nth_data(attach_list, i); + if (!attach_info) { + LoggerW("[att:%d] attach_info is NULL!", i); + continue; + } - std::shared_ptr ma (new MessageAttachment()); + std::shared_ptr ma(new MessageAttachment()); - //set message id - msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &tempInt); - ma->setMessageId(tempInt); + // set message id + msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &tempInt); + ma->setMessageId(tempInt); - //set file path - msg_get_str_value(attach_info, MSG_MMS_ATTACH_FILEPATH_STR, infoStr, - MSG_FILEPATH_LEN_MAX); - ma->setFilePath(infoStr); + // set file path + msg_get_str_value(attach_info, MSG_MMS_ATTACH_FILEPATH_STR, infoStr, MSG_FILEPATH_LEN_MAX); + ma->setFilePath(infoStr); - //set attachment id - ma->setId(message->m_attachments.size() + 1); + // set attachment id + ma->setId(message->m_attachments.size() + 1); - //set mime type - msg_get_int_value(attach_info, MSG_MMS_ATTACH_MIME_TYPE_INT, &tempInt); - std::string type = MessageAttachment::MIMETypeEnumToString(tempInt); - ma->setMimeType(type); + // set mime type + msg_get_int_value(attach_info, MSG_MMS_ATTACH_MIME_TYPE_INT, &tempInt); + std::string type = MessageAttachment::MIMETypeEnumToString(tempInt); + ma->setMimeType(type); - MessageAttachment* att = ma.get(); - LoggerD("[att:%d] added attachement: %p (mime:0x%x mime:%s path:%s id:%d)", - i, att, tempInt, type.c_str(), infoStr, ma->getId()); + MessageAttachment* att = ma.get(); + LoggerD("[att:%d] added attachement: %p (mime:0x%x mime:%s path:%s id:%d)", i, att, tempInt, + type.c_str(), infoStr, ma->getId()); - message->m_attachments.push_back(ma); - message->m_has_attachment = true; + message->m_attachments.push_back(ma); + message->m_has_attachment = true; - msg_release_struct(&attach_info); - } - } else { - msg_release_struct(&mms_struct); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "failed to add attachment", - ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); + msg_release_struct(&attach_info); } - - LoggerD("after MSG_MMS_ATTACH_LIST attachments count is:%d", - message->m_attachments.size()); + } else { msg_release_struct(&mms_struct); - return PlatformResult(ErrorCode::NO_ERROR); -} - -PlatformResult Message::convertPlatformShortMessageToObject(msg_struct_t msg, Message** result_message){ - LoggerD("Entered"); - std::unique_ptr message; - int infoInt; - bool infoBool; - char infoStr[MAX_ADDRESS_VAL_LEN + 1]; - //get type - msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &infoInt); - if (infoInt == MSG_TYPE_SMS) { - message = std::unique_ptr(new MessageSMS()); - // get SMS body - std::shared_ptr body(new MessageBody()); - char msgInfoStr[MAX_MSG_TEXT_LEN + 1]; - msg_get_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, msgInfoStr, MAX_MSG_TEXT_LEN); - body->setPlainBody(std::string(msgInfoStr)); - message->setBody(body); - // get recipients - std::vector recp_list; - PlatformResult ret = message->getSMSRecipientsFromStruct(msg, &recp_list); - if (ret.IsError()) { - LoggerE("failed to get SMS recipients from struct (%s)", ret.message().c_str()); - return ret; - } - - message->setTO(recp_list); - } else if (infoInt == MSG_TYPE_MMS) { - message = std::unique_ptr(new MessageMMS()); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "failed to add attachment", + ("msg_get_list_handle error: %d (%s)", error, get_error_message(error))); + } - // get MMS body - msg_get_int_value(msg, MSG_MESSAGE_DATA_SIZE_INT, &infoInt); - const int mms_body_length = infoInt; + LoggerD("after MSG_MMS_ATTACH_LIST attachments count is:%d", message->m_attachments.size()); + msg_release_struct(&mms_struct); + return PlatformResult(ErrorCode::NO_ERROR); +} - if(mms_body_length > 0) { - std::unique_ptr mms_body_str(new char[mms_body_length + 1]); - memset(mms_body_str.get(), 0, (mms_body_length + 1) * sizeof(char)); +PlatformResult Message::convertPlatformShortMessageToObject(msg_struct_t msg, + Message** result_message) { + LoggerD("Entered"); + std::unique_ptr message; + int infoInt; + bool infoBool; + char infoStr[MAX_ADDRESS_VAL_LEN + 1]; + // get type + msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &infoInt); + if (infoInt == MSG_TYPE_SMS) { + message = std::unique_ptr(new MessageSMS()); + // get SMS body + std::shared_ptr body(new MessageBody()); + char msgInfoStr[MAX_MSG_TEXT_LEN + 1]; + msg_get_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, msgInfoStr, MAX_MSG_TEXT_LEN); + body->setPlainBody(std::string(msgInfoStr)); + message->setBody(body); + // get recipients + std::vector recp_list; + PlatformResult ret = message->getSMSRecipientsFromStruct(msg, &recp_list); + if (ret.IsError()) { + LoggerE("failed to get SMS recipients from struct (%s)", ret.message().c_str()); + return ret; + } - int error = msg_get_str_value(msg, MSG_MESSAGE_MMS_TEXT_STR, - mms_body_str.get(), mms_body_length); - if(MSG_SUCCESS != error) { - LoggerE("Error:%d occured during: " - "msg_get_str_value(...,MSG_MESSAGE_MMS_TEXT_STR,...)", error); - } else { - //Check if fetched string is not empty - if((mms_body_str.get())[0] != 0) { - LoggerD("Fetched plain body (with MSG_MESSAGE_MMS_TEXT_STR):" - "[%s] length:%d", mms_body_str.get(), mms_body_length); - - std::shared_ptr body (new MessageBody()); - std::string infoString; - infoString.assign(mms_body_str.get()); - body->setPlainBody(infoString); - message->setBody(body); - } else { - LoggerW("Warning: fetched plain body is empty " - "despite reported length is:%d!", mms_body_length); - } - - LoggerD("Set plain body: [%s]", message->getBody()->getPlainBody().c_str()); - } + message->setTO(recp_list); + } else if (infoInt == MSG_TYPE_MMS) { + message = std::unique_ptr(new MessageMMS()); + + // get MMS body + msg_get_int_value(msg, MSG_MESSAGE_DATA_SIZE_INT, &infoInt); + const int mms_body_length = infoInt; + + if (mms_body_length > 0) { + std::unique_ptr mms_body_str(new char[mms_body_length + 1]); + memset(mms_body_str.get(), 0, (mms_body_length + 1) * sizeof(char)); + + int error = + msg_get_str_value(msg, MSG_MESSAGE_MMS_TEXT_STR, mms_body_str.get(), mms_body_length); + if (MSG_SUCCESS != error) { + LoggerE( + "Error:%d occured during: " + "msg_get_str_value(...,MSG_MESSAGE_MMS_TEXT_STR,...)", + error); + } else { + // Check if fetched string is not empty + if ((mms_body_str.get())[0] != 0) { + LoggerD( + "Fetched plain body (with MSG_MESSAGE_MMS_TEXT_STR):" + "[%s] length:%d", + mms_body_str.get(), mms_body_length); + + std::shared_ptr body(new MessageBody()); + std::string infoString; + infoString.assign(mms_body_str.get()); + body->setPlainBody(infoString); + message->setBody(body); } else { - LoggerW("Warning: mms plain body length is 0!"); + LoggerW( + "Warning: fetched plain body is empty " + "despite reported length is:%d!", + mms_body_length); } - // get recipients - std::vector recp_list; - PlatformResult ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_TO, &recp_list); - if (ret.IsError()) { - LoggerE("failed to get MMS recipients from struct"); - return ret; - } - message->setTO(recp_list); - ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_CC, &recp_list); - if (ret.IsError()) { - LoggerE("failed to get MMS recipients from struct"); - return ret; - } - message->setCC(recp_list); - ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_BCC, &recp_list); - if (ret.IsError()) { - LoggerE("failed to get MMS recipients from struct"); - return ret; - } - message->setBCC(recp_list); - // get subject - memset(infoStr, 0, MAX_ADDRESS_VAL_LEN + 1); - msg_get_str_value(msg, MSG_MESSAGE_SUBJECT_STR, infoStr, MAX_SUBJECT_LEN); - message->setSubject(infoStr); - //set attachments - ret = setMMSBodyAndAttachmentsFromStruct(message.get(), msg); - if (ret.IsError()) { - LoggerE("failed to set body attachments from struct"); - return ret; - } + LoggerD("Set plain body: [%s]", message->getBody()->getPlainBody().c_str()); + } } else { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Invalid Message type", - ("Invalid Message type: %d", infoInt)); + LoggerW("Warning: mms plain body length is 0!"); } - // get id - msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &infoInt); - message->setId(infoInt); - // get conversation id - msg_get_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, &infoInt); - message->setConversationId(infoInt); - // get folder id - msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt); - message->setFolderId(infoInt); - // get timestamp - msg_get_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, &infoInt); - message->setTimeStamp(infoInt); - // get from - const std::string& from = Message::getShortMsgSenderFromStruct(msg); - message->setFrom(from); - LoggerD("Message(%p) from is: %s", message.get(), message->getFrom().c_str()); - // get if is in response - msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &infoInt); - LoggerD("Message(%p) direction is: %d", message.get(), infoInt); - message->setInResponseTo(infoInt); - // get is read - msg_get_bool_value(msg, MSG_MESSAGE_READ_BOOL, &infoBool); - message->setIsRead(infoBool); - - // get status - - // This "strange" fix has been taken from old implementation: - // void Mms::readMessageStatus(msg_struct_t& messageData) - // - int error = msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt); - if(MSG_SUCCESS == error) { - MessageStatus msg_status; - switch (infoInt) { - case MSG_INBOX_ID: msg_status = MessageStatus::STATUS_LOADED; break; - case MSG_OUTBOX_ID: msg_status = MessageStatus::STATUS_SENDING; break; - case MSG_SENTBOX_ID: msg_status = MessageStatus::STATUS_SENT; break; - case MSG_DRAFT_ID: msg_status = MessageStatus::STATUS_DRAFT; break; - default: msg_status = MessageStatus::STATUS_LOADED; break; - } - message->setMessageStatus(msg_status); - - LoggerD("MSG_MESSAGE_FOLDER_ID:%d -> messageStatus:%s", infoInt, - MessagingUtil::messageStatusToString(msg_status).c_str()); + // get recipients + std::vector recp_list; + PlatformResult ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_TO, &recp_list); + if (ret.IsError()) { + LoggerE("failed to get MMS recipients from struct"); + return ret; } - else - { - LoggerE("Couldn't get MSG_MESSAGE_FOLDER_ID_INT, error:%d", error); - error = msg_get_int_value(msg, MSG_SENT_STATUS_NETWORK_STATUS_INT, &infoInt); - - if(MSG_SUCCESS == error) { - MessageStatus msg_status; - if (infoInt == MSG_NETWORK_SEND_SUCCESS) { - msg_status = MessageStatus::STATUS_SENT; - } else if (infoInt == MSG_NETWORK_SENDING) { - msg_status = MessageStatus::STATUS_SENDING; - } else if (infoInt == MSG_NETWORK_SEND_FAIL) { - msg_status = MessageStatus::STATUS_FAILED; - } else if (infoInt == MSG_NETWORK_NOT_SEND) { - msg_status = MessageStatus::STATUS_DRAFT; - } else { - LoggerW("warning undefined messageStatus: %d!", infoInt); - msg_status = MessageStatus::STATUS_UNDEFINED; - } - message->setMessageStatus(msg_status); + message->setTO(recp_list); + ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_CC, &recp_list); + if (ret.IsError()) { + LoggerE("failed to get MMS recipients from struct"); + return ret; + } + message->setCC(recp_list); + ret = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_BCC, &recp_list); + if (ret.IsError()) { + LoggerE("failed to get MMS recipients from struct"); + return ret; + } + message->setBCC(recp_list); + // get subject + memset(infoStr, 0, MAX_ADDRESS_VAL_LEN + 1); + msg_get_str_value(msg, MSG_MESSAGE_SUBJECT_STR, infoStr, MAX_SUBJECT_LEN); + message->setSubject(infoStr); + // set attachments + ret = setMMSBodyAndAttachmentsFromStruct(message.get(), msg); + if (ret.IsError()) { + LoggerE("failed to set body attachments from struct"); + return ret; + } + } else { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid Message type", + ("Invalid Message type: %d", infoInt)); + } - LoggerD("MSG_SENT_STATUS_NETWORK_STATUS:%d MessageStatus:%s", infoInt, - MessagingUtil::messageStatusToString(msg_status).c_str()); - } else { - LoggerE("Couldn't get MSG_SENT_STATUS_NETWORK_STATUS_INT, error:%d", error); + // get id + msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &infoInt); + message->setId(infoInt); + // get conversation id + msg_get_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, &infoInt); + message->setConversationId(infoInt); + // get folder id + msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt); + message->setFolderId(infoInt); + // get timestamp + msg_get_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, &infoInt); + message->setTimeStamp(infoInt); + // get from + const std::string& from = Message::getShortMsgSenderFromStruct(msg); + message->setFrom(from); + LoggerD("Message(%p) from is: %s", message.get(), message->getFrom().c_str()); + // get if is in response + msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &infoInt); + LoggerD("Message(%p) direction is: %d", message.get(), infoInt); + message->setInResponseTo(infoInt); + // get is read + msg_get_bool_value(msg, MSG_MESSAGE_READ_BOOL, &infoBool); + message->setIsRead(infoBool); + + // get status + + // This "strange" fix has been taken from old implementation: + // void Mms::readMessageStatus(msg_struct_t& messageData) + // + int error = msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt); + if (MSG_SUCCESS == error) { + MessageStatus msg_status; + switch (infoInt) { + case MSG_INBOX_ID: + msg_status = MessageStatus::STATUS_LOADED; + break; + case MSG_OUTBOX_ID: + msg_status = MessageStatus::STATUS_SENDING; + break; + case MSG_SENTBOX_ID: + msg_status = MessageStatus::STATUS_SENT; + break; + case MSG_DRAFT_ID: + msg_status = MessageStatus::STATUS_DRAFT; + break; + default: + msg_status = MessageStatus::STATUS_LOADED; + break; + } + message->setMessageStatus(msg_status); + + LoggerD("MSG_MESSAGE_FOLDER_ID:%d -> messageStatus:%s", infoInt, + MessagingUtil::messageStatusToString(msg_status).c_str()); + } else { + LoggerE("Couldn't get MSG_MESSAGE_FOLDER_ID_INT, error:%d", error); + error = msg_get_int_value(msg, MSG_SENT_STATUS_NETWORK_STATUS_INT, &infoInt); - if(0 == message->getId()) { - LoggerW("Both MSG_SENT_STATUS_NETWORK_STATUS_INT and " - "MSG_MESSAGE_FOLDER_ID_INT failed, messageId == 0 ASSUMING that" - "this message is in DRAFT"); - message->setMessageStatus(MessageStatus::STATUS_DRAFT); - } - } + if (MSG_SUCCESS == error) { + MessageStatus msg_status; + if (infoInt == MSG_NETWORK_SEND_SUCCESS) { + msg_status = MessageStatus::STATUS_SENT; + } else if (infoInt == MSG_NETWORK_SENDING) { + msg_status = MessageStatus::STATUS_SENDING; + } else if (infoInt == MSG_NETWORK_SEND_FAIL) { + msg_status = MessageStatus::STATUS_FAILED; + } else if (infoInt == MSG_NETWORK_NOT_SEND) { + msg_status = MessageStatus::STATUS_DRAFT; + } else { + LoggerW("warning undefined messageStatus: %d!", infoInt); + msg_status = MessageStatus::STATUS_UNDEFINED; + } + message->setMessageStatus(msg_status); + + LoggerD("MSG_SENT_STATUS_NETWORK_STATUS:%d MessageStatus:%s", infoInt, + MessagingUtil::messageStatusToString(msg_status).c_str()); + } else { + LoggerE("Couldn't get MSG_SENT_STATUS_NETWORK_STATUS_INT, error:%d", error); + + if (0 == message->getId()) { + LoggerW( + "Both MSG_SENT_STATUS_NETWORK_STATUS_INT and " + "MSG_MESSAGE_FOLDER_ID_INT failed, messageId == 0 ASSUMING that" + "this message is in DRAFT"); + message->setMessageStatus(MessageStatus::STATUS_DRAFT); + } } + } - LoggerD("End"); - *result_message = message.release(); // release ownership - return PlatformResult(ErrorCode::NO_ERROR); + LoggerD("End"); + *result_message = message.release(); // release ownership + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult Message::findShortMessageById(const int id, MessagePtr* message) { - LoggerD("Entered"); - msg_struct_t msg; - PlatformResult ret = ShortMsgManager::getInstance().getMessage(id, &msg); - if (ret.IsError()) { - return ret; - } - Message* message_ptr = nullptr; - ret = Message::convertPlatformShortMessageToObject(msg, &message_ptr); - msg_release_struct(&msg); - if (ret.IsError()) { - return ret; - } - message->reset(message_ptr); - return PlatformResult(ErrorCode::NO_ERROR); -} - -std::vector Message::split(const std::string& input, - char delimiter) -{ - LoggerD("Entered"); - std::vector ret; - std::stringstream stream(input); - std::string item; - while (getline(stream, item, delimiter)) { - ret.push_back(item); - } + LoggerD("Entered"); + msg_struct_t msg; + PlatformResult ret = ShortMsgManager::getInstance().getMessage(id, &msg); + if (ret.IsError()) { + return ret; + } + Message* message_ptr = nullptr; + ret = Message::convertPlatformShortMessageToObject(msg, &message_ptr); + msg_release_struct(&msg); + if (ret.IsError()) { return ret; + } + message->reset(message_ptr); + return PlatformResult(ErrorCode::NO_ERROR); } -std::vector Message::getEmailRecipientsFromStruct(const char *recipients) -{ - LoggerD("Entered"); - std::vector tmp = Message::split(recipients, ';'); - for (std::vector::iterator it = tmp.begin(); it != tmp.end(); ++it) { - *it = MessagingUtil::ltrim(*it); - } +std::vector Message::split(const std::string& input, char delimiter) { + LoggerD("Entered"); + std::vector ret; + std::stringstream stream(input); + std::string item; + while (getline(stream, item, delimiter)) { + ret.push_back(item); + } + return ret; +} - if (tmp.begin() != tmp.end()) { - if (*(tmp.begin()) == "") { - tmp.erase(tmp.begin()); - } +std::vector Message::getEmailRecipientsFromStruct(const char* recipients) { + LoggerD("Entered"); + std::vector tmp = Message::split(recipients, ';'); + for (std::vector::iterator it = tmp.begin(); it != tmp.end(); ++it) { + *it = MessagingUtil::ltrim(*it); + } - if (*(tmp.end() - 1) == "") { - tmp.erase(tmp.end() - 1); - } + if (tmp.begin() != tmp.end()) { + if (*(tmp.begin()) == "") { + tmp.erase(tmp.begin()); + } + + if (*(tmp.end() - 1) == "") { + tmp.erase(tmp.end() - 1); } + } - // remove '<' and '>' - tmp = MessagingUtil::extractEmailAddresses(tmp); - return tmp; + // remove '<' and '>' + tmp = MessagingUtil::extractEmailAddresses(tmp); + return tmp; } -std::shared_ptr Message::convertEmailToMessageBody( - email_mail_data_t& mail) -{ - LoggerD("Entered"); - std::shared_ptr body (new MessageBody()); - body->updateBody(mail); - return body; +std::shared_ptr Message::convertEmailToMessageBody(email_mail_data_t& mail) { + LoggerD("Entered"); + std::shared_ptr body(new MessageBody()); + body->updateBody(mail); + return body; } PlatformResult Message::convertEmailToMessageAttachment(email_mail_data_t& mail, - AttachmentPtrVector* att) -{ + AttachmentPtrVector* att) { LoggerD("Entered"); email_attachment_data_t* attachment = NULL; int attachmentCount = 0; - int ntv_ret = email_get_attachment_data_list( - mail.mail_id, - &attachment, - &attachmentCount); + int ntv_ret = email_get_attachment_data_list(mail.mail_id, &attachment, &attachmentCount); if (EMAIL_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't get attachment.", - ("email_get_attachment_data_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Couldn't get attachment.", + ("email_get_attachment_data_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - if ( attachment && attachmentCount > 0) { + if (attachment && attachmentCount > 0) { for (int i = 0; i < attachmentCount; i++) { - std::shared_ptr tmp_att (new MessageAttachment()); + std::shared_ptr tmp_att(new MessageAttachment()); tmp_att->updateWithAttachmentData(attachment[i]); att->push_back(tmp_att); } @@ -1660,24 +1566,22 @@ PlatformResult Message::convertEmailToMessageAttachment(email_mail_data_t& mail, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::convertPlatformEmailToObject( - email_mail_data_t& mail, std::shared_ptr* result) -{ - LoggerD("Entered"); - Message* message = new MessageEmail(); - PlatformResult ret = message->updateEmailMessage(mail); - if (ret.IsError()) { - delete message; - return ret; - } - (*result).reset(message); - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult Message::convertPlatformEmailToObject(email_mail_data_t& mail, + std::shared_ptr* result) { + LoggerD("Entered"); + Message* message = new MessageEmail(); + PlatformResult ret = message->updateEmailMessage(mail); + if (ret.IsError()) { + delete message; + return ret; + } + (*result).reset(message); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::updateEmailMessage(email_mail_data_t& mail) -{ - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "This should be called on MessageEmail instance"); +PlatformResult Message::updateEmailMessage(email_mail_data_t& mail) { + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "This should be called on MessageEmail instance"); } /** @@ -1721,95 +1625,69 @@ const std::string HAS_ATTACHMENT = MESSAGE_ATTRIBUTE_HAS_ATTACHMENT; const std::string IS_HIGH_PRIORITY = MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY; const std::string SUBJECT = MESSAGE_ATTRIBUTE_SUBJECT; -} //namespace MESSAGE_FILTER_ATTRIBUTE +} // namespace MESSAGE_FILTER_ATTRIBUTE bool Message::isMatchingAttribute(const std::string& attribute_name, - const FilterMatchFlag match_flag, - AnyPtr match_value) const -{ - LoggerD("Entered"); - auto key = match_value->toString(); - LoggerD("attribute_name:%s match_flag:%d matchValue:%s", attribute_name.c_str(), - match_flag, key.c_str()); - - using namespace MESSAGE_FILTER_ATTRIBUTE; - - if (ID == attribute_name) { - return FilterUtils::isStringMatching(key, std::to_string(getId()), - match_flag); - } - else if (SERVICE_ID == attribute_name) { - if(is_service_is_set()) { - return FilterUtils::isStringMatching(key, std::to_string(getServiceId()), - match_flag); - } - } - else if (FOLDER_ID == attribute_name) { - return FilterUtils::isStringMatching(key, std::to_string(getFolderIdForUser()), - match_flag); - } - else if (TYPE == attribute_name) { - return FilterUtils::isStringMatching(key, getTypeString(), match_flag); - } - else if (FROM == attribute_name) { - return FilterUtils::isStringMatching(key, getFrom() , match_flag); - } - else if (TO == attribute_name) { - return FilterUtils::isAnyStringMatching(key, getTO(), match_flag); - } - else if (CC == attribute_name) { - return FilterUtils::isAnyStringMatching(key, getCC(), match_flag); - } - else if (BCC == attribute_name) { - return FilterUtils::isAnyStringMatching(key, getBCC(), match_flag); - } - else if (BODY_PLAIN_BODY == attribute_name) { - if(getBody()) { - return FilterUtils::isStringMatching(key, getBody()->getPlainBody(), - match_flag); - } - } - else if (IS_READ == attribute_name) { - return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getIsRead()), - match_flag); - } - else if (HAS_ATTACHMENT == attribute_name) { - return FilterUtils::isStringMatching(key, - FilterUtils::boolToString(getHasAttachment()), - match_flag); - } - else if (IS_HIGH_PRIORITY == attribute_name) { - return FilterUtils::isStringMatching(key, - FilterUtils::boolToString(getIsHighPriority()), - match_flag); - } - else if (SUBJECT == attribute_name) { - return FilterUtils::isStringMatching(key, getSubject(), match_flag); - } - else { - LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); - } + const FilterMatchFlag match_flag, AnyPtr match_value) const { + LoggerD("Entered"); + auto key = match_value->toString(); + LoggerD("attribute_name:%s match_flag:%d matchValue:%s", attribute_name.c_str(), match_flag, + key.c_str()); + + using namespace MESSAGE_FILTER_ATTRIBUTE; + + if (ID == attribute_name) { + return FilterUtils::isStringMatching(key, std::to_string(getId()), match_flag); + } else if (SERVICE_ID == attribute_name) { + if (is_service_is_set()) { + return FilterUtils::isStringMatching(key, std::to_string(getServiceId()), match_flag); + } + } else if (FOLDER_ID == attribute_name) { + return FilterUtils::isStringMatching(key, std::to_string(getFolderIdForUser()), match_flag); + } else if (TYPE == attribute_name) { + return FilterUtils::isStringMatching(key, getTypeString(), match_flag); + } else if (FROM == attribute_name) { + return FilterUtils::isStringMatching(key, getFrom(), match_flag); + } else if (TO == attribute_name) { + return FilterUtils::isAnyStringMatching(key, getTO(), match_flag); + } else if (CC == attribute_name) { + return FilterUtils::isAnyStringMatching(key, getCC(), match_flag); + } else if (BCC == attribute_name) { + return FilterUtils::isAnyStringMatching(key, getBCC(), match_flag); + } else if (BODY_PLAIN_BODY == attribute_name) { + if (getBody()) { + return FilterUtils::isStringMatching(key, getBody()->getPlainBody(), match_flag); + } + } else if (IS_READ == attribute_name) { + return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getIsRead()), match_flag); + } else if (HAS_ATTACHMENT == attribute_name) { + return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getHasAttachment()), + match_flag); + } else if (IS_HIGH_PRIORITY == attribute_name) { + return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getIsHighPriority()), + match_flag); + } else if (SUBJECT == attribute_name) { + return FilterUtils::isStringMatching(key, getSubject(), match_flag); + } else { + LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); + } - return false; + return false; } -bool Message::isMatchingAttributeRange(const std::string& attribute_name, - AnyPtr initial_value, - AnyPtr end_value) const -{ - LoggerD("Entered attribute_name: %s", attribute_name.c_str()); +bool Message::isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, + AnyPtr end_value) const { + LoggerD("Entered attribute_name: %s", attribute_name.c_str()); - using namespace MESSAGE_FILTER_ATTRIBUTE; - if(TIMESTAMP == attribute_name) { - return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, - end_value); - } - else { - LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); - } + using namespace MESSAGE_FILTER_ATTRIBUTE; + if (TIMESTAMP == attribute_name) { + return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, end_value); + } else { + LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); + } - return false; + return false; } -} //messaging -} //extension +} // messaging +} // extension diff --git a/src/messaging/message.h b/src/messaging/message.h index 7bccf99..87578ea 100644 --- a/src/messaging/message.h +++ b/src/messaging/message.h @@ -13,26 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_H_ #define MESSAGING_MESSAGE_H_ -#include +#include +#include +#include +#include #include +#include #include +#include #include #include -#include -#include -#include -#include -#include -#include "message_attachment.h" -#include "messaging_util.h" -#include "message_body.h" #include "MsgCommon/AbstractFilter.h" #include "common/platform_result.h" +#include "message_attachment.h" +#include "message_body.h" +#include "messaging_util.h" namespace extension { namespace messaging { @@ -40,202 +40,197 @@ namespace messaging { class Message; struct MessageHolder { - std::shared_ptr ptr; + std::shared_ptr ptr; }; typedef std::shared_ptr MessagePtr; typedef std::vector MessagePtrVector; -enum AttachmentType { - EXTERNAL = 0, INLINE = 1 -}; +enum AttachmentType { EXTERNAL = 0, INLINE = 1 }; using namespace tizen; class Message : public FilterableObject { -public: -// constructor - Message(); - virtual ~Message(); - -// attributes getters - int getId() const; - int getOldId() const; - int getConversationId() const; - int getFolderId() const; - virtual int getFolderIdForUser() const; - MessageType getType() const; - std::string getTypeString() const; - time_t getTimestamp() const; - std::string getFrom() const; - std::vector getTO() const; - std::vector getCC() const; - std::vector getBCC() const; - std::shared_ptr getBody() const; - bool getIsRead() const; - // getHasAttachment() is virtual to support MMS and email differently - virtual bool getHasAttachment() const; - bool getIsHighPriority() const; - std::string getSubject() const; - int getInResponseTo() const; - MessageStatus getMessageStatus() const; - AttachmentPtrVector getMessageAttachments() const; - int getServiceId() const; - TelNetworkDefaultDataSubs_t getSimIndex() const; - -// attributes setters (virtual because some of them can be overriden in sub classes) - virtual void setId(int id); - virtual void setOldId(int id); - virtual void setConversationId(int id); - virtual void setFolderId(int id); - // type setting not allowed so no setter provided - virtual void setTimeStamp(time_t timestamp); - virtual void setFrom(std::string from); - virtual void setTO(std::vector &to); - virtual void setCC(std::vector &cc); - virtual void setBCC(std::vector &bcc); - virtual void setBody(std::shared_ptr& body); - virtual void setIsRead(bool read); - // has attachment can't be set explicity -> no setter for this flag - virtual void setIsHighPriority(bool highpriority); - virtual void setSubject(std::string subject); - virtual void setInResponseTo(int inresp); - virtual void setMessageStatus(MessageStatus status); - virtual void setMessageAttachments(AttachmentPtrVector &attachments); - virtual void setServiceId(int service_id); - virtual void setSimIndex(TelNetworkDefaultDataSubs_t sim_index); - -// support for optional, nullable (at JS layer) attibutes - // message id - bool is_id_set() const; - // conversation id - bool is_conversation_id_set() const; - // folder id - bool is_folder_id_set() const; - // timestamp - bool is_timestamp_set() const; - // message sender - bool is_from_set() const; - // related message ("parent" message) - bool is_in_response_set() const; - // service id - bool is_service_is_set() const; - // gets recipients list for SMS message - common::PlatformResult addSMSRecipientsToStruct(const std::vector &recipients, - msg_struct_t &msg); - // gets recipients list for SMS message - common::PlatformResult addMMSRecipientsToStruct(const std::vector &recipients, - msg_struct_t &msg, - int type); - /** - * Updates message with data from email_mail_data_t structure. - * @param mail - */ - virtual common::PlatformResult updateEmailMessage(email_mail_data_t& mail); - - // gets from(sender) address from short msg struct - static std::string getShortMsgSenderFromStruct(msg_struct_t &msg); - // function for filling msg_struct_t fields - static common::PlatformResult convertPlatformShortMessageToStruct(Message* message, - msg_handle_t handle, msg_struct_t* result); - // gets recipients list for SMS message - common::PlatformResult getSMSRecipientsFromStruct(msg_struct_t &msg, - std::vector* result_address); - // gets recipients list for MMS message - static common::PlatformResult getMMSRecipientsFromStruct(msg_struct_t &msg, - int type, std::vector* result_address); - // function for filling Message attributes - static common::PlatformResult convertPlatformShortMessageToObject(msg_struct_t msg, Message** message); - static common::PlatformResult findShortMessageById(const int id, MessagePtr* message); - static common::PlatformResult addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector &attach, - msg_struct_t &mms_struct, - Message* message); - static common::PlatformResult setMMSBodyAndAttachmentsFromStruct(Message *message, - msg_struct_t &msg); - - static common::PlatformResult convertPlatformEmail(std::shared_ptr message, - email_mail_data_t** result); - static common::PlatformResult addEmailAttachments(std::shared_ptr message); - static std::string convertEmailRecipients(const std::vector &recipients); - static std::vector getEmailRecipientsFromStruct(const char *recipients); - static common::PlatformResult convertPlatformEmailToObject(email_mail_data_t& mail, - std::shared_ptr* result); - static std::shared_ptr convertEmailToMessageBody(email_mail_data_t& mail); - static common::PlatformResult convertEmailToMessageAttachment(email_mail_data_t& mail, - AttachmentPtrVector* result); - - // tizen::FilterableObject - virtual bool isMatchingAttribute(const std::string& attribute_name, - const FilterMatchFlag match_flag, - AnyPtr match_value) const; - - virtual bool isMatchingAttributeRange(const std::string& attribute_name, - AnyPtr initial_value, - AnyPtr end_value) const; - -protected: - //! Message id - int m_id; - //! Old Message id - for email update hack - int m_old_id; - //! Flag for checking if id is set (false means: not set) - bool m_id_set; - //! Conversation id - int m_conversation_id; - //! Flag for checking if conversation id is set (false means: not set) - bool m_conversation_id_set; - //! Folder id - int m_folder_id; - //! Flag for checking if folder id is set (false means: not set) - bool m_folder_id_set; - //! Message type (messaging.sms, messaging.mms, messaging.email) - MessageType m_type; - //! Timestamp - time when message has been sent/received - time_t m_timestamp; - //! Flag for checking if timestamp is set (false means: not set) - bool m_timestamp_set; - //! Message sender address (email) or number (SMS, MMS) - std::string m_from; - //! Flag for checking if sender is set (false means: not set) - bool m_from_set; - //! Message recipients - std::vector m_to; - //! Message CarbonCopy recipients (used only for email) - std::vector m_cc; - //! Message BlindCarbonCopy recipients (used only for email) - std::vector m_bcc; - //! MessageBody (object containg plainBody and htmlBody for emails) - std::shared_ptr m_body; - //! Service id - int m_service_id; - //! Message isRead flag - bool m_is_read; - //! Message hasAttachment flag - bool m_has_attachment; - //! Message isHighPriority flag - bool m_high_priority; - //! Message subject (used in MMS and email) - std::string m_subject; - //! Id of original message when message is a reply or forward - int m_in_response; - //! Flag for checking if id of related message is set (false means: not set) - bool m_in_response_set; - //! Flag for checking if service id is set - bool m_service_id_set; - //! Outgoing Message status (SENT, SENDING, DRAFT etc) - MessageStatus m_status; - //! Attachments attached to this message - AttachmentPtrVector m_attachments; - //! SIM index which indicate a sim to send message. - TelNetworkDefaultDataSubs_t m_sim_index; - -private: - static std::vector split(const std::string& input, - char delimiter); + public: + // constructor + Message(); + virtual ~Message(); + + // attributes getters + int getId() const; + int getOldId() const; + int getConversationId() const; + int getFolderId() const; + virtual int getFolderIdForUser() const; + MessageType getType() const; + std::string getTypeString() const; + time_t getTimestamp() const; + std::string getFrom() const; + std::vector getTO() const; + std::vector getCC() const; + std::vector getBCC() const; + std::shared_ptr getBody() const; + bool getIsRead() const; + // getHasAttachment() is virtual to support MMS and email differently + virtual bool getHasAttachment() const; + bool getIsHighPriority() const; + std::string getSubject() const; + int getInResponseTo() const; + MessageStatus getMessageStatus() const; + AttachmentPtrVector getMessageAttachments() const; + int getServiceId() const; + TelNetworkDefaultDataSubs_t getSimIndex() const; + + // attributes setters (virtual because some of them can be overriden in sub classes) + virtual void setId(int id); + virtual void setOldId(int id); + virtual void setConversationId(int id); + virtual void setFolderId(int id); + // type setting not allowed so no setter provided + virtual void setTimeStamp(time_t timestamp); + virtual void setFrom(std::string from); + virtual void setTO(std::vector& to); + virtual void setCC(std::vector& cc); + virtual void setBCC(std::vector& bcc); + virtual void setBody(std::shared_ptr& body); + virtual void setIsRead(bool read); + // has attachment can't be set explicity -> no setter for this flag + virtual void setIsHighPriority(bool highpriority); + virtual void setSubject(std::string subject); + virtual void setInResponseTo(int inresp); + virtual void setMessageStatus(MessageStatus status); + virtual void setMessageAttachments(AttachmentPtrVector& attachments); + virtual void setServiceId(int service_id); + virtual void setSimIndex(TelNetworkDefaultDataSubs_t sim_index); + + // support for optional, nullable (at JS layer) attibutes + // message id + bool is_id_set() const; + // conversation id + bool is_conversation_id_set() const; + // folder id + bool is_folder_id_set() const; + // timestamp + bool is_timestamp_set() const; + // message sender + bool is_from_set() const; + // related message ("parent" message) + bool is_in_response_set() const; + // service id + bool is_service_is_set() const; + // gets recipients list for SMS message + common::PlatformResult addSMSRecipientsToStruct(const std::vector& recipients, + msg_struct_t& msg); + // gets recipients list for SMS message + common::PlatformResult addMMSRecipientsToStruct(const std::vector& recipients, + msg_struct_t& msg, int type); + /** + * Updates message with data from email_mail_data_t structure. + * @param mail + */ + virtual common::PlatformResult updateEmailMessage(email_mail_data_t& mail); + + // gets from(sender) address from short msg struct + static std::string getShortMsgSenderFromStruct(msg_struct_t& msg); + // function for filling msg_struct_t fields + static common::PlatformResult convertPlatformShortMessageToStruct(Message* message, + msg_handle_t handle, + msg_struct_t* result); + // gets recipients list for SMS message + common::PlatformResult getSMSRecipientsFromStruct(msg_struct_t& msg, + std::vector* result_address); + // gets recipients list for MMS message + static common::PlatformResult getMMSRecipientsFromStruct( + msg_struct_t& msg, int type, std::vector* result_address); + // function for filling Message attributes + static common::PlatformResult convertPlatformShortMessageToObject(msg_struct_t msg, + Message** message); + static common::PlatformResult findShortMessageById(const int id, MessagePtr* message); + static common::PlatformResult addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector& attach, + msg_struct_t& mms_struct, + Message* message); + static common::PlatformResult setMMSBodyAndAttachmentsFromStruct(Message* message, + msg_struct_t& msg); + + static common::PlatformResult convertPlatformEmail(std::shared_ptr message, + email_mail_data_t** result); + static common::PlatformResult addEmailAttachments(std::shared_ptr message); + static std::string convertEmailRecipients(const std::vector& recipients); + static std::vector getEmailRecipientsFromStruct(const char* recipients); + static common::PlatformResult convertPlatformEmailToObject(email_mail_data_t& mail, + std::shared_ptr* result); + static std::shared_ptr convertEmailToMessageBody(email_mail_data_t& mail); + static common::PlatformResult convertEmailToMessageAttachment(email_mail_data_t& mail, + AttachmentPtrVector* result); + + // tizen::FilterableObject + virtual bool isMatchingAttribute(const std::string& attribute_name, + const FilterMatchFlag match_flag, AnyPtr match_value) const; + + virtual bool isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, + AnyPtr end_value) const; + + protected: + //! Message id + int m_id; + //! Old Message id - for email update hack + int m_old_id; + //! Flag for checking if id is set (false means: not set) + bool m_id_set; + //! Conversation id + int m_conversation_id; + //! Flag for checking if conversation id is set (false means: not set) + bool m_conversation_id_set; + //! Folder id + int m_folder_id; + //! Flag for checking if folder id is set (false means: not set) + bool m_folder_id_set; + //! Message type (messaging.sms, messaging.mms, messaging.email) + MessageType m_type; + //! Timestamp - time when message has been sent/received + time_t m_timestamp; + //! Flag for checking if timestamp is set (false means: not set) + bool m_timestamp_set; + //! Message sender address (email) or number (SMS, MMS) + std::string m_from; + //! Flag for checking if sender is set (false means: not set) + bool m_from_set; + //! Message recipients + std::vector m_to; + //! Message CarbonCopy recipients (used only for email) + std::vector m_cc; + //! Message BlindCarbonCopy recipients (used only for email) + std::vector m_bcc; + //! MessageBody (object containg plainBody and htmlBody for emails) + std::shared_ptr m_body; + //! Service id + int m_service_id; + //! Message isRead flag + bool m_is_read; + //! Message hasAttachment flag + bool m_has_attachment; + //! Message isHighPriority flag + bool m_high_priority; + //! Message subject (used in MMS and email) + std::string m_subject; + //! Id of original message when message is a reply or forward + int m_in_response; + //! Flag for checking if id of related message is set (false means: not set) + bool m_in_response_set; + //! Flag for checking if service id is set + bool m_service_id_set; + //! Outgoing Message status (SENT, SENDING, DRAFT etc) + MessageStatus m_status; + //! Attachments attached to this message + AttachmentPtrVector m_attachments; + //! SIM index which indicate a sim to send message. + TelNetworkDefaultDataSubs_t m_sim_index; + + private: + static std::vector split(const std::string& input, char delimiter); }; -} //messaging -} //extension +} // messaging +} // extension #endif /* MESSAGING_MESSAGE_H_ */ - diff --git a/src/messaging/message_attachment.cc b/src/messaging/message_attachment.cc old mode 100755 new mode 100644 index 9d1fc23..07972e9 --- a/src/messaging/message_attachment.cc +++ b/src/messaging/message_attachment.cc @@ -13,585 +13,575 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include #include #include "message_attachment.h" -#include "common/logger.h" #include "common/filesystem/filesystem_provider.h" +#include "common/logger.h" namespace extension { namespace messaging { -std::map& MessageAttachment::MIMETypeStringToEnumMap = initializeMIMETypeStringToEnumMap(); -std::map& MessageAttachment::MIMETypeEnumToStringMap = initializeMIMETypeEnumToStringMap(); - -MessageAttachment::MessageAttachment() -{ - LoggerD("MessageAttachment constructor (%p)", this); - m_id = -1; - m_isIdSet = false; - m_messageId = -1; - m_isMessageIdSet = false; - m_mimeType = ""; - m_isMimeTypeSet = false; - m_filePath = ""; - m_isFilePathSet = false; - m_isSaved = true; +std::map& MessageAttachment::MIMETypeStringToEnumMap = + initializeMIMETypeStringToEnumMap(); +std::map& MessageAttachment::MIMETypeEnumToStringMap = + initializeMIMETypeEnumToStringMap(); + +MessageAttachment::MessageAttachment() { + LoggerD("MessageAttachment constructor (%p)", this); + m_id = -1; + m_isIdSet = false; + m_messageId = -1; + m_isMessageIdSet = false; + m_mimeType = ""; + m_isMimeTypeSet = false; + m_filePath = ""; + m_isFilePathSet = false; + m_isSaved = true; } -MessageAttachment::~MessageAttachment() -{ - LoggerD("MessageAttachment destructor (%p)", this); +MessageAttachment::~MessageAttachment() { + LoggerD("MessageAttachment destructor (%p)", this); } // id -int MessageAttachment::getId() -{ - return m_id; +int MessageAttachment::getId() { + return m_id; } -void MessageAttachment::setId(int value) -{ - m_id = value; - m_isIdSet = true; +void MessageAttachment::setId(int value) { + m_id = value; + m_isIdSet = true; } -bool MessageAttachment::isIdSet() -{ - return m_isIdSet; +bool MessageAttachment::isIdSet() { + return m_isIdSet; } -void MessageAttachment::unsetId() -{ - m_isIdSet = false; +void MessageAttachment::unsetId() { + m_isIdSet = false; } // messageId -int MessageAttachment::getMessageId() -{ - return m_messageId; +int MessageAttachment::getMessageId() { + return m_messageId; } -void MessageAttachment::setMessageId(int value) -{ - m_messageId = value; - m_isMessageIdSet = true; +void MessageAttachment::setMessageId(int value) { + m_messageId = value; + m_isMessageIdSet = true; } -bool MessageAttachment::isMessageIdSet() -{ - return m_isMessageIdSet; +bool MessageAttachment::isMessageIdSet() { + return m_isMessageIdSet; } -void MessageAttachment::unsetMessageId() -{ - m_isMessageIdSet = false; +void MessageAttachment::unsetMessageId() { + m_isMessageIdSet = false; } // mimeType -std::string MessageAttachment::getMimeType() -{ - return m_mimeType; +std::string MessageAttachment::getMimeType() { + return m_mimeType; } -void MessageAttachment::setMimeType(const std::string &value) -{ - m_mimeType = value; - m_isMimeTypeSet = true; +void MessageAttachment::setMimeType(const std::string& value) { + m_mimeType = value; + m_isMimeTypeSet = true; } -bool MessageAttachment::isMimeTypeSet() -{ - return m_isMimeTypeSet; +bool MessageAttachment::isMimeTypeSet() { + return m_isMimeTypeSet; } -void MessageAttachment::unsetMimeType() -{ - m_isMimeTypeSet = false; +void MessageAttachment::unsetMimeType() { + m_isMimeTypeSet = false; } // filePath -std::string MessageAttachment::getFilePath() -{ - return m_filePath; +std::string MessageAttachment::getFilePath() { + return m_filePath; } -std::string MessageAttachment::getShortFileName() const -{ - LoggerD("Entered"); - if (!m_isFilePathSet) { - return ""; - } - size_t pos; - // find position of last occurence of / sign (get only file name from all path - pos = m_filePath.find_last_of("/"); - - if ((pos + 1) >= m_filePath.size() || pos == std::string::npos) { - return m_filePath; - } - return m_filePath.substr(pos + 1); +std::string MessageAttachment::getShortFileName() const { + LoggerD("Entered"); + if (!m_isFilePathSet) { + return ""; + } + size_t pos; + // find position of last occurence of / sign (get only file name from all path + pos = m_filePath.find_last_of("/"); + + if ((pos + 1) >= m_filePath.size() || pos == std::string::npos) { + return m_filePath; + } + return m_filePath.substr(pos + 1); } -void MessageAttachment::setFilePath(const std::string &value) -{ - LoggerD("Entered"); +void MessageAttachment::setFilePath(const std::string& value) { + LoggerD("Entered"); - m_filePath = common::FilesystemProvider::Create().GetRealPath(value); - m_isFilePathSet = true; + m_filePath = common::FilesystemProvider::Create().GetRealPath(value); + m_isFilePathSet = true; } -bool MessageAttachment::isFilePathSet() -{ - return m_isFilePathSet; +bool MessageAttachment::isFilePathSet() { + return m_isFilePathSet; } -void MessageAttachment::unsetFilePath() -{ - m_isFilePathSet = false; +void MessageAttachment::unsetFilePath() { + m_isFilePathSet = false; } -void MessageAttachment::setIsSaved(bool isSaved) -{ - m_isSaved = isSaved; +void MessageAttachment::setIsSaved(bool isSaved) { + m_isSaved = isSaved; } -bool MessageAttachment::isSaved() const -{ - return m_isSaved; +bool MessageAttachment::isSaved() const { + return m_isSaved; } -std::map& MessageAttachment::initializeMIMETypeEnumToStringMap() -{ - LoggerD("Entered"); - static std::map enumToString; - //0 - enumToString[MIME_ASTERISK] = "*/*"; - //1 - enumToString[MIME_APPLICATION_XML] = "application/xml"; - enumToString[MIME_APPLICATION_WML_XML] = "application/wml+xml"; - enumToString[MIME_APPLICATION_XHTML_XML] = "application/xhtml+xml"; - enumToString[MIME_APPLICATION_JAVA_VM] = "application/java-vm"; - enumToString[MIME_APPLICATION_SMIL] = "application/smil"; - enumToString[MIME_APPLICATION_JAVA_ARCHIVE] = "application/java-archive"; - enumToString[MIME_APPLICATION_JAVA] = "application/java"; - enumToString[MIME_APPLICATION_OCTET_STREAM] = "application/octet-stream"; - enumToString[MIME_APPLICATION_STUDIOM] = "application/studiom"; - enumToString[MIME_APPLICATION_FUNMEDIA] = "application/funMedia"; - enumToString[MIME_APPLICATION_MSWORD] = "application/msword"; - enumToString[MIME_APPLICATION_PDF] = "application/pdf"; - enumToString[MIME_APPLICATION_SDP] = "application/sdp"; - enumToString[MIME_APPLICATION_RAM] = "application/ram"; - enumToString[MIME_APPLICATION_ASTERIC] = "application/*"; - //16 - enumToString[MIME_APPLICATION_VND_WAP_XHTMLXML] = "application/vnd.wap.xhtml+xml"; - enumToString[MIME_APPLICATION_VND_WAP_WMLC] = "application/vnd.wap.wmlc"; - enumToString[MIME_APPLICATION_VND_WAP_WMLSCRIPTC] = "application/vnd.wap.wmlscriptc"; - enumToString[MIME_APPLICATION_VND_WAP_WTA_EVENTC] = "application/vnd.wap.wta-eventc"; - enumToString[MIME_APPLICATION_VND_WAP_UAPROF] = "application/vnd.wap.uaprof"; - enumToString[MIME_APPLICATION_VND_WAP_SIC] = "application/vnd.wap.sic"; - enumToString[MIME_APPLICATION_VND_WAP_SLC] = "application/vnd.wap.slc"; - enumToString[MIME_APPLICATION_VND_WAP_COC] = "application/vnd.wap.coc"; - enumToString[MIME_APPLICATION_VND_WAP_SIA] = "application/vnd.wap.sia"; - enumToString[MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML] = "application/vnd.wap.connectivity-wbxml"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA] = "application/vnd.wap.multipart.form-data"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES] = "application/vnd.wap.multipart.byteranges"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_MIXED] = "application/vnd.wap.multipart.mixed"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_RELATED] = "application/vnd.wap.multipart.related"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE] = "application/vnd.wap.multipart.alternative"; - enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC] = "application/vnd.wap.multipart.*"; - enumToString[MIME_APPLICATION_VND_WAP_WBXML] = "application/vnd.wap.wbxml"; - enumToString[MIME_APPLICATION_VND_OMA_DD_XML] = "application/vnd.oma.dd+xml"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_MESSAGE] = "application/vnd.oma.drm.message"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_CONTENT] = "application/vnd.oma.drm.content"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML] = "application/vnd.oma.drm.rights+xml"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML] = "application/vnd.oma.drm.rights+wbxml"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_RO_XML] = "application/vnd.oma.drm.ro+xml"; - enumToString[MIME_APPLICATION_VND_OMA_DRM_DCF] = "application/vnd.oma.drm.dcf"; - enumToString[MIME_APPLICATION_VND_OMA_ROAPPDU_XML] = "application/vnd.oma.drm.roap-pdu+xml"; - enumToString[MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML] = "application/vnd.oma.drm.roap-trigger+xml"; - enumToString[MIME_APPLICATION_VND_SMAF] = "application/vnd.smaf"; - enumToString[MIME_APPLICATION_VND_RN_REALMEDIA] = "application/vnd.rn-realmedia"; - enumToString[MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE] = "application/vnd.sun.j2me.java-archive"; - enumToString[MIME_APPLICATION_VND_SAMSUNG_THEME] = "application/vnd.samsung.theme"; - enumToString[MIME_APPLICATION_VND_EXCEL] = "application/vnd.ms-excel"; - enumToString[MIME_APPLICATION_VND_POWERPOINT] = "application/vnd.ms-powerpoint"; - enumToString[MIME_APPLICATION_VND_MSWORD] = "applcation/vnd.ms-word"; - //49 - enumToString[MIME_APPLICATION_X_HDMLC] = "application/x-hdmlc"; - enumToString[MIME_APPLICATION_X_X968_USERCERT] = "application/x-x968-user-cert"; - enumToString[MIME_APPLICATION_X_WWW_FORM_URLENCODED] = "application/x-www-form-urlencoded"; - enumToString[MIME_APPLICATION_X_SMAF] = "application/x-smaf"; - enumToString[MIME_APPLICATION_X_FLASH] = "application/x-shockwave-flash"; - enumToString[MIME_APPLICATION_X_EXCEL] = "application/x-msexcel"; - enumToString[MIME_APPLICATION_X_POWERPOINT] = "application/x-mspowerpoint"; - //56 - enumToString[MIME_AUDIO_BASIC] = "audio/basic"; - enumToString[MIME_AUDIO_MPEG] = "audio/mpeg"; - enumToString[MIME_AUDIO_MP3] = "audio/mp3"; - enumToString[MIME_AUDIO_MPG3] = "audio/mpg3"; - enumToString[MIME_AUDIO_MPEG3] = "audio/mpeg3"; - enumToString[MIME_AUDIO_MPG] = "audio/mpg"; - enumToString[MIME_AUDIO_AAC] = "audio/aac"; - enumToString[MIME_AUDIO_G72] = "audio/g72"; - enumToString[MIME_AUDIO_AMR] = "audio/amr"; - enumToString[MIME_AUDIO_AMR_WB] = "audio/amr-wb"; - enumToString[MIME_AUDIO_MMF] = "audio/mmf"; - enumToString[MIME_AUDIO_SMAF] = "audio/smaf"; - enumToString[MIME_AUDIO_IMELODY] = "audio/iMelody"; - enumToString[MIME_AUDIO_IMELODY2] = "audio/imelody"; - enumToString[MIME_AUDIO_MELODY] = "audio/melody"; - enumToString[MIME_AUDIO_MID] = "audio/mid"; - enumToString[MIME_AUDIO_MIDI] = "audio/midi"; - enumToString[MIME_AUDIO_SP_MIDI] = "audio/sp-midi"; - enumToString[MIME_AUDIO_WAVE] = "audio/wave"; - enumToString[MIME_AUDIO_WAV] = "audio/wav"; - enumToString[MIME_AUDIO_3GPP] = "audio/3gpp"; - enumToString[MIME_AUDIO_MP4] = "audio/mp4"; - enumToString[MIME_AUDIO_MP4A_LATM] = "audio/MP4A-LATM"; - enumToString[MIME_AUDIO_M4A] = "audio/m4a"; - enumToString[MIME_AUDIO_MPEG4] = "audio/mpeg4"; - enumToString[MIME_AUDIO_WMA] = "audio/wma"; - enumToString[MIME_AUDIO_XMF] = "audio/xmf"; - enumToString[MIME_AUDIO_IMY] = "audio/imy"; - enumToString[MIME_AUDIO_MOBILE_XMF] = "audio/mobile-xmf"; - //85 - enumToString[MIME_AUDIO_VND_RN_REALAUDIO] = "audio/vnd.rn-realaudio"; - //86 - enumToString[MIME_AUDIO_X_MPEG] = "audio/x-mpeg"; - enumToString[MIME_AUDIO_X_MP3] = "audio/x-mp3"; - enumToString[MIME_AUDIO_X_MPEG3] = "audio/x-mpeg3"; - enumToString[MIME_AUDIO_X_MPG] = "audio/x-mpg"; - enumToString[MIME_AUDIO_X_AMR] = "audio/x-amr"; - enumToString[MIME_AUDIO_X_MMF] = "audio/x-mmf"; - enumToString[MIME_AUDIO_X_SMAF] = "audio/x-smaf"; - enumToString[MIME_AUDIO_X_IMELODY] = "audio/x-iMelody"; - enumToString[MIME_AUDIO_X_MIDI] = "audio/x-midi"; - enumToString[MIME_AUDIO_X_MPEGAUDIO] = "audio/x-mpegaudio"; - enumToString[MIME_AUDIO_X_PN_REALAUDIO] = "audio/x-pn-realaudio"; - enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO] = "audio/x-pn-multirate-realaudio"; - enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE] = "audio/x-pn-multirate-realaudio-live"; - enumToString[MIME_AUDIO_X_WAVE] = "audio/x-wave"; - enumToString[MIME_AUDIO_X_WAV] = "audio/x-wav"; - enumToString[MIME_AUDIO_X_MS_WMA] = "audio/x-ms-wma"; - enumToString[MIME_AUDIO_X_MID] = "audio/x-mid"; - enumToString[MIME_AUDIO_X_MS_ASF] = "audio/x-ms-asf"; - enumToString[MIME_AUDIO_X_XMF] = "audio/x-xmf"; - //105 - enumToString[MIME_IMAGE_GIF] = "image/gif"; - enumToString[MIME_IMAGE_JPEG] = "image/jpeg"; - enumToString[MIME_IMAGE_JPG] = "image/jpg"; - enumToString[MIME_IMAGE_TIFF] = "image/tiff"; - enumToString[MIME_IMAGE_TIF] = "image/tif"; - enumToString[MIME_IMAGE_PNG] = "image/png"; - enumToString[MIME_IMAGE_WBMP] = "image/wbmp"; - enumToString[MIME_IMAGE_PJPEG] = "image/pjpeg"; - enumToString[MIME_IMAGE_BMP] = "image/bmp"; - enumToString[MIME_IMAGE_SVG] = "image/svg+xml"; - enumToString[MIME_IMAGE_SVG1] = "image/svg-xml"; - //116 - enumToString[MIME_IMAGE_VND_WAP_WBMP] = "image/vnd.wap.wbmp"; - enumToString[MIME_IMAGE_VND_TMO_GIF] = "image/vnd.tmo.my5-gif"; - enumToString[MIME_IMAGE_VND_TMO_JPG] = "image/vnd.tmo.my5-jpg"; - //119 - enumToString[MIME_IMAGE_X_BMP] = "image/x-bmp"; - //120 - enumToString[MIME_MESSAGE_RFC822] = "message/rfc822"; - //121 - enumToString[MIME_MULTIPART_MIXED] = "multipart/mixed"; - enumToString[MIME_MULTIPART_RELATED] = "multipart/related"; - enumToString[MIME_MULTIPART_ALTERNATIVE] = "multipart/alternative"; - enumToString[MIME_MULTIPART_FORM_DATA] = "multipart/form-data"; - enumToString[MIME_MULTIPART_BYTERANGE] = "multipart/byterange"; - enumToString[MIME_MULTIPART_REPORT] = "multipart/report"; - enumToString[MIME_MULTIPART_VOICE_MESSAGE] = "multipart/voice-message"; - //128 - enumToString[MIME_TEXT_TXT] = "text/txt"; - enumToString[MIME_TEXT_HTML] = "text/html"; - enumToString[MIME_TEXT_PLAIN] = "text/plain"; - enumToString[MIME_TEXT_CSS] = "text/css"; - enumToString[MIME_TEXT_XML] = "text/xml"; - enumToString[MIME_TEXT_IMELODY] = "text/iMelody"; - //134 - enumToString[MIME_TEXT_VND_WAP_WMLSCRIPT] = "text/vnd.wap.wmlscript"; - enumToString[MIME_TEXT_VND_WAP_WML] = "text/vnd.wap.wml"; - enumToString[MIME_TEXT_VND_WAP_WTA_EVENT] = "text/vnd.wap.wta-event"; - enumToString[MIME_TEXT_VND_WAP_CONNECTIVITY_XML] = "text/vnd.wap.connectivity-xml"; - enumToString[MIME_TEXT_VND_WAP_SI] = "text/vnd.wap.si"; - enumToString[MIME_TEXT_VND_WAP_SL] = "text/vnd.wap.sl"; - enumToString[MIME_TEXT_VND_WAP_CO] = "text/vnd.wap.co"; - enumToString[MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR] = "text/vnd.sun.j2me.app-descriptor"; - //142 - enumToString[MIME_TEXT_X_HDML] = "text/x-hdml"; - enumToString[MIME_TEXT_X_VCALENDAR] = "text/x-vCalendar"; - enumToString[MIME_TEXT_X_VCARD] = "text/x-vCard"; - enumToString[MIME_TEXT_X_IMELODY] = "text/x-iMelody"; - enumToString[MIME_TEXT_X_IMELODY2] = "text/x-imelody"; - enumToString[MIME_TEXT_X_VNOTE] = "text/x-vnote"; - //148 - enumToString[MIME_VIDEO_MPEG4] = "video/mpeg4"; - enumToString[MIME_VIDEO_MP4] = "video/mp4"; - enumToString[MIME_VIDEO_H263] = "video/h263"; - enumToString[MIME_VIDEO_3GPP] = "video/3gpp"; - enumToString[MIME_VIDEO_3GP] = "video/3gp"; - enumToString[MIME_VIDEO_AVI] = "video/avi"; - enumToString[MIME_VIDEO_SDP] = "video/sdp"; - enumToString[MIME_VIDEO_MP4_ES] = "video/mp4v-es"; - enumToString[MIME_VIDEO_MPEG] = "video/mpeg"; - //157 - enumToString[MIME_VIDEO_VND_RN_REALVIDEO] = "video/vnd.rn-realvideo"; - enumToString[MIME_VIDEO_VND_RN_REALMEDIA] = "video/vnd.rn-realmedia"; - //159 - enumToString[MIME_VIDEO_X_MP4] = "video/x-mp4"; - enumToString[MIME_VIDEO_X_PV_MP4] = "video/x-pv-mp4"; - enumToString[MIME_VIDEO_X_PN_REALVIDEO] = "video/x-pn-realvideo"; - enumToString[MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO] = "video/x-pn-multirate-realvideo"; - enumToString[MIME_VIDEO_X_MS_WMV] = "video/x-ms-wmv"; - enumToString[MIME_VIDEO_X_MS_ASF] = "video/x-ms-asf"; - enumToString[MIME_VIDEO_X_PV_PVX] = "video/x-pv-pvx"; - - return enumToString; +std::map& MessageAttachment::initializeMIMETypeEnumToStringMap() { + LoggerD("Entered"); + static std::map enumToString; + // 0 + enumToString[MIME_ASTERISK] = "*/*"; + // 1 + enumToString[MIME_APPLICATION_XML] = "application/xml"; + enumToString[MIME_APPLICATION_WML_XML] = "application/wml+xml"; + enumToString[MIME_APPLICATION_XHTML_XML] = "application/xhtml+xml"; + enumToString[MIME_APPLICATION_JAVA_VM] = "application/java-vm"; + enumToString[MIME_APPLICATION_SMIL] = "application/smil"; + enumToString[MIME_APPLICATION_JAVA_ARCHIVE] = "application/java-archive"; + enumToString[MIME_APPLICATION_JAVA] = "application/java"; + enumToString[MIME_APPLICATION_OCTET_STREAM] = "application/octet-stream"; + enumToString[MIME_APPLICATION_STUDIOM] = "application/studiom"; + enumToString[MIME_APPLICATION_FUNMEDIA] = "application/funMedia"; + enumToString[MIME_APPLICATION_MSWORD] = "application/msword"; + enumToString[MIME_APPLICATION_PDF] = "application/pdf"; + enumToString[MIME_APPLICATION_SDP] = "application/sdp"; + enumToString[MIME_APPLICATION_RAM] = "application/ram"; + enumToString[MIME_APPLICATION_ASTERIC] = "application/*"; + // 16 + enumToString[MIME_APPLICATION_VND_WAP_XHTMLXML] = "application/vnd.wap.xhtml+xml"; + enumToString[MIME_APPLICATION_VND_WAP_WMLC] = "application/vnd.wap.wmlc"; + enumToString[MIME_APPLICATION_VND_WAP_WMLSCRIPTC] = "application/vnd.wap.wmlscriptc"; + enumToString[MIME_APPLICATION_VND_WAP_WTA_EVENTC] = "application/vnd.wap.wta-eventc"; + enumToString[MIME_APPLICATION_VND_WAP_UAPROF] = "application/vnd.wap.uaprof"; + enumToString[MIME_APPLICATION_VND_WAP_SIC] = "application/vnd.wap.sic"; + enumToString[MIME_APPLICATION_VND_WAP_SLC] = "application/vnd.wap.slc"; + enumToString[MIME_APPLICATION_VND_WAP_COC] = "application/vnd.wap.coc"; + enumToString[MIME_APPLICATION_VND_WAP_SIA] = "application/vnd.wap.sia"; + enumToString[MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML] = + "application/vnd.wap.connectivity-wbxml"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA] = + "application/vnd.wap.multipart.form-data"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES] = + "application/vnd.wap.multipart.byteranges"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_MIXED] = "application/vnd.wap.multipart.mixed"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_RELATED] = + "application/vnd.wap.multipart.related"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE] = + "application/vnd.wap.multipart.alternative"; + enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC] = "application/vnd.wap.multipart.*"; + enumToString[MIME_APPLICATION_VND_WAP_WBXML] = "application/vnd.wap.wbxml"; + enumToString[MIME_APPLICATION_VND_OMA_DD_XML] = "application/vnd.oma.dd+xml"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_MESSAGE] = "application/vnd.oma.drm.message"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_CONTENT] = "application/vnd.oma.drm.content"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML] = "application/vnd.oma.drm.rights+xml"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML] = "application/vnd.oma.drm.rights+wbxml"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_RO_XML] = "application/vnd.oma.drm.ro+xml"; + enumToString[MIME_APPLICATION_VND_OMA_DRM_DCF] = "application/vnd.oma.drm.dcf"; + enumToString[MIME_APPLICATION_VND_OMA_ROAPPDU_XML] = "application/vnd.oma.drm.roap-pdu+xml"; + enumToString[MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML] = + "application/vnd.oma.drm.roap-trigger+xml"; + enumToString[MIME_APPLICATION_VND_SMAF] = "application/vnd.smaf"; + enumToString[MIME_APPLICATION_VND_RN_REALMEDIA] = "application/vnd.rn-realmedia"; + enumToString[MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE] = + "application/vnd.sun.j2me.java-archive"; + enumToString[MIME_APPLICATION_VND_SAMSUNG_THEME] = "application/vnd.samsung.theme"; + enumToString[MIME_APPLICATION_VND_EXCEL] = "application/vnd.ms-excel"; + enumToString[MIME_APPLICATION_VND_POWERPOINT] = "application/vnd.ms-powerpoint"; + enumToString[MIME_APPLICATION_VND_MSWORD] = "applcation/vnd.ms-word"; + // 49 + enumToString[MIME_APPLICATION_X_HDMLC] = "application/x-hdmlc"; + enumToString[MIME_APPLICATION_X_X968_USERCERT] = "application/x-x968-user-cert"; + enumToString[MIME_APPLICATION_X_WWW_FORM_URLENCODED] = "application/x-www-form-urlencoded"; + enumToString[MIME_APPLICATION_X_SMAF] = "application/x-smaf"; + enumToString[MIME_APPLICATION_X_FLASH] = "application/x-shockwave-flash"; + enumToString[MIME_APPLICATION_X_EXCEL] = "application/x-msexcel"; + enumToString[MIME_APPLICATION_X_POWERPOINT] = "application/x-mspowerpoint"; + // 56 + enumToString[MIME_AUDIO_BASIC] = "audio/basic"; + enumToString[MIME_AUDIO_MPEG] = "audio/mpeg"; + enumToString[MIME_AUDIO_MP3] = "audio/mp3"; + enumToString[MIME_AUDIO_MPG3] = "audio/mpg3"; + enumToString[MIME_AUDIO_MPEG3] = "audio/mpeg3"; + enumToString[MIME_AUDIO_MPG] = "audio/mpg"; + enumToString[MIME_AUDIO_AAC] = "audio/aac"; + enumToString[MIME_AUDIO_G72] = "audio/g72"; + enumToString[MIME_AUDIO_AMR] = "audio/amr"; + enumToString[MIME_AUDIO_AMR_WB] = "audio/amr-wb"; + enumToString[MIME_AUDIO_MMF] = "audio/mmf"; + enumToString[MIME_AUDIO_SMAF] = "audio/smaf"; + enumToString[MIME_AUDIO_IMELODY] = "audio/iMelody"; + enumToString[MIME_AUDIO_IMELODY2] = "audio/imelody"; + enumToString[MIME_AUDIO_MELODY] = "audio/melody"; + enumToString[MIME_AUDIO_MID] = "audio/mid"; + enumToString[MIME_AUDIO_MIDI] = "audio/midi"; + enumToString[MIME_AUDIO_SP_MIDI] = "audio/sp-midi"; + enumToString[MIME_AUDIO_WAVE] = "audio/wave"; + enumToString[MIME_AUDIO_WAV] = "audio/wav"; + enumToString[MIME_AUDIO_3GPP] = "audio/3gpp"; + enumToString[MIME_AUDIO_MP4] = "audio/mp4"; + enumToString[MIME_AUDIO_MP4A_LATM] = "audio/MP4A-LATM"; + enumToString[MIME_AUDIO_M4A] = "audio/m4a"; + enumToString[MIME_AUDIO_MPEG4] = "audio/mpeg4"; + enumToString[MIME_AUDIO_WMA] = "audio/wma"; + enumToString[MIME_AUDIO_XMF] = "audio/xmf"; + enumToString[MIME_AUDIO_IMY] = "audio/imy"; + enumToString[MIME_AUDIO_MOBILE_XMF] = "audio/mobile-xmf"; + // 85 + enumToString[MIME_AUDIO_VND_RN_REALAUDIO] = "audio/vnd.rn-realaudio"; + // 86 + enumToString[MIME_AUDIO_X_MPEG] = "audio/x-mpeg"; + enumToString[MIME_AUDIO_X_MP3] = "audio/x-mp3"; + enumToString[MIME_AUDIO_X_MPEG3] = "audio/x-mpeg3"; + enumToString[MIME_AUDIO_X_MPG] = "audio/x-mpg"; + enumToString[MIME_AUDIO_X_AMR] = "audio/x-amr"; + enumToString[MIME_AUDIO_X_MMF] = "audio/x-mmf"; + enumToString[MIME_AUDIO_X_SMAF] = "audio/x-smaf"; + enumToString[MIME_AUDIO_X_IMELODY] = "audio/x-iMelody"; + enumToString[MIME_AUDIO_X_MIDI] = "audio/x-midi"; + enumToString[MIME_AUDIO_X_MPEGAUDIO] = "audio/x-mpegaudio"; + enumToString[MIME_AUDIO_X_PN_REALAUDIO] = "audio/x-pn-realaudio"; + enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO] = "audio/x-pn-multirate-realaudio"; + enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE] = "audio/x-pn-multirate-realaudio-live"; + enumToString[MIME_AUDIO_X_WAVE] = "audio/x-wave"; + enumToString[MIME_AUDIO_X_WAV] = "audio/x-wav"; + enumToString[MIME_AUDIO_X_MS_WMA] = "audio/x-ms-wma"; + enumToString[MIME_AUDIO_X_MID] = "audio/x-mid"; + enumToString[MIME_AUDIO_X_MS_ASF] = "audio/x-ms-asf"; + enumToString[MIME_AUDIO_X_XMF] = "audio/x-xmf"; + // 105 + enumToString[MIME_IMAGE_GIF] = "image/gif"; + enumToString[MIME_IMAGE_JPEG] = "image/jpeg"; + enumToString[MIME_IMAGE_JPG] = "image/jpg"; + enumToString[MIME_IMAGE_TIFF] = "image/tiff"; + enumToString[MIME_IMAGE_TIF] = "image/tif"; + enumToString[MIME_IMAGE_PNG] = "image/png"; + enumToString[MIME_IMAGE_WBMP] = "image/wbmp"; + enumToString[MIME_IMAGE_PJPEG] = "image/pjpeg"; + enumToString[MIME_IMAGE_BMP] = "image/bmp"; + enumToString[MIME_IMAGE_SVG] = "image/svg+xml"; + enumToString[MIME_IMAGE_SVG1] = "image/svg-xml"; + // 116 + enumToString[MIME_IMAGE_VND_WAP_WBMP] = "image/vnd.wap.wbmp"; + enumToString[MIME_IMAGE_VND_TMO_GIF] = "image/vnd.tmo.my5-gif"; + enumToString[MIME_IMAGE_VND_TMO_JPG] = "image/vnd.tmo.my5-jpg"; + // 119 + enumToString[MIME_IMAGE_X_BMP] = "image/x-bmp"; + // 120 + enumToString[MIME_MESSAGE_RFC822] = "message/rfc822"; + // 121 + enumToString[MIME_MULTIPART_MIXED] = "multipart/mixed"; + enumToString[MIME_MULTIPART_RELATED] = "multipart/related"; + enumToString[MIME_MULTIPART_ALTERNATIVE] = "multipart/alternative"; + enumToString[MIME_MULTIPART_FORM_DATA] = "multipart/form-data"; + enumToString[MIME_MULTIPART_BYTERANGE] = "multipart/byterange"; + enumToString[MIME_MULTIPART_REPORT] = "multipart/report"; + enumToString[MIME_MULTIPART_VOICE_MESSAGE] = "multipart/voice-message"; + // 128 + enumToString[MIME_TEXT_TXT] = "text/txt"; + enumToString[MIME_TEXT_HTML] = "text/html"; + enumToString[MIME_TEXT_PLAIN] = "text/plain"; + enumToString[MIME_TEXT_CSS] = "text/css"; + enumToString[MIME_TEXT_XML] = "text/xml"; + enumToString[MIME_TEXT_IMELODY] = "text/iMelody"; + // 134 + enumToString[MIME_TEXT_VND_WAP_WMLSCRIPT] = "text/vnd.wap.wmlscript"; + enumToString[MIME_TEXT_VND_WAP_WML] = "text/vnd.wap.wml"; + enumToString[MIME_TEXT_VND_WAP_WTA_EVENT] = "text/vnd.wap.wta-event"; + enumToString[MIME_TEXT_VND_WAP_CONNECTIVITY_XML] = "text/vnd.wap.connectivity-xml"; + enumToString[MIME_TEXT_VND_WAP_SI] = "text/vnd.wap.si"; + enumToString[MIME_TEXT_VND_WAP_SL] = "text/vnd.wap.sl"; + enumToString[MIME_TEXT_VND_WAP_CO] = "text/vnd.wap.co"; + enumToString[MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR] = "text/vnd.sun.j2me.app-descriptor"; + // 142 + enumToString[MIME_TEXT_X_HDML] = "text/x-hdml"; + enumToString[MIME_TEXT_X_VCALENDAR] = "text/x-vCalendar"; + enumToString[MIME_TEXT_X_VCARD] = "text/x-vCard"; + enumToString[MIME_TEXT_X_IMELODY] = "text/x-iMelody"; + enumToString[MIME_TEXT_X_IMELODY2] = "text/x-imelody"; + enumToString[MIME_TEXT_X_VNOTE] = "text/x-vnote"; + // 148 + enumToString[MIME_VIDEO_MPEG4] = "video/mpeg4"; + enumToString[MIME_VIDEO_MP4] = "video/mp4"; + enumToString[MIME_VIDEO_H263] = "video/h263"; + enumToString[MIME_VIDEO_3GPP] = "video/3gpp"; + enumToString[MIME_VIDEO_3GP] = "video/3gp"; + enumToString[MIME_VIDEO_AVI] = "video/avi"; + enumToString[MIME_VIDEO_SDP] = "video/sdp"; + enumToString[MIME_VIDEO_MP4_ES] = "video/mp4v-es"; + enumToString[MIME_VIDEO_MPEG] = "video/mpeg"; + // 157 + enumToString[MIME_VIDEO_VND_RN_REALVIDEO] = "video/vnd.rn-realvideo"; + enumToString[MIME_VIDEO_VND_RN_REALMEDIA] = "video/vnd.rn-realmedia"; + // 159 + enumToString[MIME_VIDEO_X_MP4] = "video/x-mp4"; + enumToString[MIME_VIDEO_X_PV_MP4] = "video/x-pv-mp4"; + enumToString[MIME_VIDEO_X_PN_REALVIDEO] = "video/x-pn-realvideo"; + enumToString[MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO] = "video/x-pn-multirate-realvideo"; + enumToString[MIME_VIDEO_X_MS_WMV] = "video/x-ms-wmv"; + enumToString[MIME_VIDEO_X_MS_ASF] = "video/x-ms-asf"; + enumToString[MIME_VIDEO_X_PV_PVX] = "video/x-pv-pvx"; + + return enumToString; } -std::map& MessageAttachment::initializeMIMETypeStringToEnumMap() -{ - LoggerD("Entered"); - static std::map stringToEnum; - //0 - stringToEnum["*/*"] = MIME_ASTERISK; - //1 - stringToEnum["application/xml"] = MIME_APPLICATION_XML; - stringToEnum["application/wml+xml"] = MIME_APPLICATION_WML_XML; - stringToEnum["application/xhtml+xml"] = MIME_APPLICATION_XHTML_XML; - stringToEnum["application/java-vm"] = MIME_APPLICATION_JAVA_VM; - stringToEnum["application/smil"] = MIME_APPLICATION_SMIL; - stringToEnum["application/java-archive"] = MIME_APPLICATION_JAVA_ARCHIVE; - stringToEnum["application"] = MIME_APPLICATION_JAVA; - stringToEnum["application/octet-stream"] = MIME_APPLICATION_OCTET_STREAM; - stringToEnum["application/studiom"] = MIME_APPLICATION_STUDIOM; - stringToEnum["application/funMedia"] = MIME_APPLICATION_FUNMEDIA; - stringToEnum["application/msword"] = MIME_APPLICATION_MSWORD; - stringToEnum["application/pdf"] = MIME_APPLICATION_PDF; - stringToEnum["application/sdp"] = MIME_APPLICATION_SDP; - stringToEnum["application/ram"] = MIME_APPLICATION_RAM; - stringToEnum["application/*"] = MIME_APPLICATION_ASTERIC; - //16 - stringToEnum["application/vnd.wap.xhtml+xml"] = MIME_APPLICATION_VND_WAP_XHTMLXML; - stringToEnum["application/vnd.wap.wmlc"] = MIME_APPLICATION_VND_WAP_WMLC; - stringToEnum["application/vnd.wap.wmlscriptc"] = MIME_APPLICATION_VND_WAP_WMLSCRIPTC; - stringToEnum["application/vnd.wap.wta-eventc"] = MIME_APPLICATION_VND_WAP_WTA_EVENTC; - stringToEnum["application/vnd.wap.uaprof"] = MIME_APPLICATION_VND_WAP_UAPROF; - stringToEnum["application/vnd.wap.sic"] = MIME_APPLICATION_VND_WAP_SIC; - stringToEnum["application/vnd.wap.slc"] = MIME_APPLICATION_VND_WAP_SLC; - stringToEnum["application/vnd.wap.coc"] = MIME_APPLICATION_VND_WAP_COC; - stringToEnum["application/vnd.wap.sia"] = MIME_APPLICATION_VND_WAP_SIA; - stringToEnum["application/vnd.wap.connectivity-wbxml"] = MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML; - stringToEnum["application/vnd.wap.multipart.form-data"] = MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA; - stringToEnum["application/vnd.wap.multipart.byteranges"] = MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES; - stringToEnum["application/vnd.wap.multipart.mixed"] = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED; - stringToEnum["application/vnd.wap.multipart.related"] = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED; - stringToEnum["application/vnd.wap.multipart.alternative"] = MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE; - stringToEnum["application/vnd.wap.multipart.*"] = MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC; - stringToEnum["application/vnd.wap.wbxml"] = MIME_APPLICATION_VND_WAP_WBXML; - stringToEnum["application/vnd.oma.dd+xml"] = MIME_APPLICATION_VND_OMA_DD_XML; - stringToEnum["application/vnd.oma.drm.message"] = MIME_APPLICATION_VND_OMA_DRM_MESSAGE; - stringToEnum["application/vnd.oma.drm.content"] = MIME_APPLICATION_VND_OMA_DRM_CONTENT; - stringToEnum["application/vnd.oma.drm.rights+xml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML; - stringToEnum["application/vnd.oma.drm.rights+wbxml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML; - stringToEnum["application/vnd.oma.drm.ro+xml"] = MIME_APPLICATION_VND_OMA_DRM_RO_XML; - stringToEnum["application/vnd.oma.drm.dcf"] = MIME_APPLICATION_VND_OMA_DRM_DCF; - stringToEnum["application/vnd.oma.drm.roap-pdu+xml"] = MIME_APPLICATION_VND_OMA_ROAPPDU_XML; - stringToEnum["application/vnd.oma.drm.roap-trigger+xml"] = MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML; - stringToEnum["application/vnd.smaf"] = MIME_APPLICATION_VND_SMAF; - stringToEnum["application/vnd.rn-realmedia"] = MIME_APPLICATION_VND_RN_REALMEDIA; - stringToEnum["application/vnd.sun.j2me.java-archive"] = MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE; - stringToEnum["application/vnd.samsung.theme"] = MIME_APPLICATION_VND_SAMSUNG_THEME; - stringToEnum["application/vnd.ms-excel"] = MIME_APPLICATION_VND_EXCEL; - stringToEnum["application/vnd.ms-powerpoint"] = MIME_APPLICATION_VND_POWERPOINT; - stringToEnum["applcation/vnd.ms-word"] = MIME_APPLICATION_VND_MSWORD; - //49 - stringToEnum["application/x-hdmlc"] = MIME_APPLICATION_X_HDMLC; - stringToEnum["application/x-x968-user-cert"] = MIME_APPLICATION_X_X968_USERCERT; - stringToEnum["application/x-www-form-urlencoded"] = MIME_APPLICATION_X_WWW_FORM_URLENCODED; - stringToEnum["application/x-smaf"] = MIME_APPLICATION_X_SMAF; - stringToEnum["application/x-shockwave-flash"] = MIME_APPLICATION_X_FLASH; - stringToEnum["application/x-msexcel"] = MIME_APPLICATION_X_EXCEL; - stringToEnum["application/x-mspowerpoint"] = MIME_APPLICATION_X_POWERPOINT; - //56 - stringToEnum["audio/basic"] = MIME_AUDIO_BASIC; - stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG; - stringToEnum["audio/mp3"] = MIME_AUDIO_MP3; - stringToEnum["audio/mpg3"] = MIME_AUDIO_MPG3; - stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG3; - stringToEnum["audio/mpg"] = MIME_AUDIO_MPG; - stringToEnum["audio/aac"] = MIME_AUDIO_AAC; - stringToEnum["audio/g72"] = MIME_AUDIO_G72; - stringToEnum["audio/amr"] = MIME_AUDIO_AMR; - stringToEnum["audio/amr-wb"] = MIME_AUDIO_AMR_WB; - stringToEnum["audio/mmf"] = MIME_AUDIO_MMF; - stringToEnum["audio/smaf"] = MIME_AUDIO_SMAF; - stringToEnum["audio/iMelody"] = MIME_AUDIO_IMELODY; - stringToEnum["audio/imelody"] = MIME_AUDIO_IMELODY2; - stringToEnum["audio/melody"] = MIME_AUDIO_MELODY; - stringToEnum["audio/mid"] = MIME_AUDIO_MID; - stringToEnum["audio/midi"] = MIME_AUDIO_MIDI; - stringToEnum["audio/sp-midi"] = MIME_AUDIO_SP_MIDI; - stringToEnum["audio/wave"] = MIME_AUDIO_WAVE; - stringToEnum["audio/wav"] = MIME_AUDIO_WAV; - stringToEnum["audio/3gpp"] = MIME_AUDIO_3GPP; - stringToEnum["audio/mp4"] = MIME_AUDIO_MP4; - stringToEnum["audio/MP4A-LATM"] = MIME_AUDIO_MP4A_LATM; - stringToEnum["audio/m4a"] = MIME_AUDIO_M4A; - stringToEnum["audio/mpeg4"] = MIME_AUDIO_MPEG4; - stringToEnum["audio/wma"] = MIME_AUDIO_WMA; - stringToEnum["audio/xmf"] = MIME_AUDIO_XMF; - stringToEnum["audio/imy"] = MIME_AUDIO_IMY; - stringToEnum["audio/mobile-xmf"] = MIME_AUDIO_MOBILE_XMF; - //85 - stringToEnum["audio/vnd.rn-realaudio"] = MIME_AUDIO_VND_RN_REALAUDIO; - //86 - stringToEnum["audio/x-mpeg"] = MIME_AUDIO_X_MPEG; - stringToEnum["audio/x-mp3"] = MIME_AUDIO_X_MP3; - stringToEnum["audio/x-mpeg3"] = MIME_AUDIO_X_MPEG3; - stringToEnum["audio/x-mpg"] = MIME_AUDIO_X_MPG; - stringToEnum["audio/x-amr"] = MIME_AUDIO_X_AMR; - stringToEnum["audio/x-mmf"] = MIME_AUDIO_X_MMF; - stringToEnum["audio/x-smaf"] = MIME_AUDIO_X_SMAF; - stringToEnum["audio/x-iMelody"] = MIME_AUDIO_X_IMELODY; - stringToEnum["audio/x-midi"] = MIME_AUDIO_X_MIDI; - stringToEnum["audio/x-mpegaudio"] = MIME_AUDIO_X_MPEGAUDIO; - stringToEnum["audio/x-pn-realaudio"] = MIME_AUDIO_X_PN_REALAUDIO; - stringToEnum["audio/x-pn-multirate-realaudio"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO; - stringToEnum["audio/x-pn-multirate-realaudio-live"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE; - stringToEnum["audio/x-wave"] = MIME_AUDIO_X_WAVE; - stringToEnum["audio/x-wav"] = MIME_AUDIO_X_WAV; - stringToEnum["audio/x-ms-wma"] = MIME_AUDIO_X_MS_WMA; - stringToEnum["audio/x-mid"] = MIME_AUDIO_X_MID; - stringToEnum["audio/x-ms-asf"] = MIME_AUDIO_X_MS_ASF; - stringToEnum["audio/x-xmf"] = MIME_AUDIO_X_XMF; - //105 - stringToEnum["image/gif"] = MIME_IMAGE_GIF; - stringToEnum["image/jpeg"] = MIME_IMAGE_JPEG; - stringToEnum["image/jpga"] = MIME_IMAGE_JPG; - stringToEnum["image/tiff"] = MIME_IMAGE_TIFF; - stringToEnum["image/tif"] = MIME_IMAGE_TIF; - stringToEnum["image/png"] = MIME_IMAGE_PNG; - stringToEnum["image/wbmp"] = MIME_IMAGE_WBMP; - stringToEnum["image/pjpeg"] = MIME_IMAGE_PJPEG; - stringToEnum["image/bmp"] = MIME_IMAGE_BMP; - stringToEnum["image/svg+xml"] = MIME_IMAGE_SVG; - stringToEnum["image/svg-xml"] = MIME_IMAGE_SVG1; - //116 - stringToEnum["image/vnd.wap.wbmp"] = MIME_IMAGE_VND_WAP_WBMP; - stringToEnum["image/vnd.tmo.my5-gif"] = MIME_IMAGE_VND_TMO_GIF; - stringToEnum["image/vnd.tmo.my5-jpg"] = MIME_IMAGE_VND_TMO_JPG; - //119 - stringToEnum["image/x-bmp"] = MIME_IMAGE_X_BMP; - //120 - stringToEnum["message/rfc822"] = MIME_MESSAGE_RFC822; - //121 - stringToEnum["multipart/mixed"] = MIME_MULTIPART_MIXED; - stringToEnum["multipart/related"] = MIME_MULTIPART_RELATED; - stringToEnum["multipart/alternative"] = MIME_MULTIPART_ALTERNATIVE; - stringToEnum["multipart/form-data"] = MIME_MULTIPART_FORM_DATA; - stringToEnum["multipart/byterange"] = MIME_MULTIPART_BYTERANGE; - stringToEnum["multipart/report"] = MIME_MULTIPART_REPORT; - stringToEnum["multipart/voice-message"] = MIME_MULTIPART_VOICE_MESSAGE; - //128 - stringToEnum["text/txt"] = MIME_TEXT_TXT; - stringToEnum["text/html"] = MIME_TEXT_HTML; - stringToEnum["text/plain"] = MIME_TEXT_PLAIN; - stringToEnum["text/css"] = MIME_TEXT_CSS; - stringToEnum["text/xml"] = MIME_TEXT_XML; - stringToEnum["text/iMelody"] = MIME_TEXT_IMELODY; - //134 - stringToEnum["text/vnd.wap.wmlscript"] = MIME_TEXT_VND_WAP_WMLSCRIPT; - stringToEnum["text/vnd.wap.wml"] = MIME_TEXT_VND_WAP_WML; - stringToEnum["text/vnd.wap.wta-event"] = MIME_TEXT_VND_WAP_WTA_EVENT; - stringToEnum["text/vnd.wap.connectivity-xml"] = MIME_TEXT_VND_WAP_CONNECTIVITY_XML; - stringToEnum["text/vnd.wap.si"] = MIME_TEXT_VND_WAP_SI; - stringToEnum["text/vnd.wap.sl"] = MIME_TEXT_VND_WAP_SL; - stringToEnum["text/vnd.wap.co"] = MIME_TEXT_VND_WAP_CO; - stringToEnum["text/vnd.sun.j2me.app-descriptor"] = MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR; - //142 - stringToEnum["text/x-hdml"] = MIME_TEXT_X_HDML; - stringToEnum["text/x-vCalendar"] = MIME_TEXT_X_VCALENDAR; - stringToEnum["text/x-vCard"] = MIME_TEXT_X_VCARD; - stringToEnum["text/x-iMelody"] = MIME_TEXT_X_IMELODY; - stringToEnum["text/x-imelody"] = MIME_TEXT_X_IMELODY2; - stringToEnum["text/x-vnote"] = MIME_TEXT_X_VNOTE; - //148 - stringToEnum["video/mpeg4"] = MIME_VIDEO_MPEG4; - stringToEnum["video/mp4"] = MIME_VIDEO_MP4; - stringToEnum["video/h263"] = MIME_VIDEO_H263; - stringToEnum["video/3gpp"] = MIME_VIDEO_3GPP; - stringToEnum["video/3gp"] = MIME_VIDEO_3GP; - stringToEnum["video/avi"] = MIME_VIDEO_AVI; - stringToEnum["video/sdp"] = MIME_VIDEO_SDP; - stringToEnum["video/mp4v-es"] = MIME_VIDEO_MP4_ES; - stringToEnum["video/mpeg"] = MIME_VIDEO_MPEG; - //157 - stringToEnum["video/vnd.rn-realvideo"] = MIME_VIDEO_VND_RN_REALVIDEO; - stringToEnum["video/vnd.rn-realmedia"] = MIME_VIDEO_VND_RN_REALMEDIA; - //159 - stringToEnum["video/x-mp4"] = MIME_VIDEO_X_MP4; - stringToEnum["video/x-pv-mp4"] = MIME_VIDEO_X_PV_MP4; - stringToEnum["video/x-pn-realvideo"] = MIME_VIDEO_X_PN_REALVIDEO; - stringToEnum["video/x-pn-multirate-realvideo"] = MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO; - stringToEnum["video/x-ms-wmv"] = MIME_VIDEO_X_MS_WMV; - stringToEnum["video/x-ms-asf"] = MIME_VIDEO_X_MS_ASF; - stringToEnum["video/x-pv-pvx"] = MIME_VIDEO_X_PV_PVX; - stringToEnum[""] = MIME_UNKNOWN; - - return stringToEnum; +std::map& MessageAttachment::initializeMIMETypeStringToEnumMap() { + LoggerD("Entered"); + static std::map stringToEnum; + // 0 + stringToEnum["*/*"] = MIME_ASTERISK; + // 1 + stringToEnum["application/xml"] = MIME_APPLICATION_XML; + stringToEnum["application/wml+xml"] = MIME_APPLICATION_WML_XML; + stringToEnum["application/xhtml+xml"] = MIME_APPLICATION_XHTML_XML; + stringToEnum["application/java-vm"] = MIME_APPLICATION_JAVA_VM; + stringToEnum["application/smil"] = MIME_APPLICATION_SMIL; + stringToEnum["application/java-archive"] = MIME_APPLICATION_JAVA_ARCHIVE; + stringToEnum["application"] = MIME_APPLICATION_JAVA; + stringToEnum["application/octet-stream"] = MIME_APPLICATION_OCTET_STREAM; + stringToEnum["application/studiom"] = MIME_APPLICATION_STUDIOM; + stringToEnum["application/funMedia"] = MIME_APPLICATION_FUNMEDIA; + stringToEnum["application/msword"] = MIME_APPLICATION_MSWORD; + stringToEnum["application/pdf"] = MIME_APPLICATION_PDF; + stringToEnum["application/sdp"] = MIME_APPLICATION_SDP; + stringToEnum["application/ram"] = MIME_APPLICATION_RAM; + stringToEnum["application/*"] = MIME_APPLICATION_ASTERIC; + // 16 + stringToEnum["application/vnd.wap.xhtml+xml"] = MIME_APPLICATION_VND_WAP_XHTMLXML; + stringToEnum["application/vnd.wap.wmlc"] = MIME_APPLICATION_VND_WAP_WMLC; + stringToEnum["application/vnd.wap.wmlscriptc"] = MIME_APPLICATION_VND_WAP_WMLSCRIPTC; + stringToEnum["application/vnd.wap.wta-eventc"] = MIME_APPLICATION_VND_WAP_WTA_EVENTC; + stringToEnum["application/vnd.wap.uaprof"] = MIME_APPLICATION_VND_WAP_UAPROF; + stringToEnum["application/vnd.wap.sic"] = MIME_APPLICATION_VND_WAP_SIC; + stringToEnum["application/vnd.wap.slc"] = MIME_APPLICATION_VND_WAP_SLC; + stringToEnum["application/vnd.wap.coc"] = MIME_APPLICATION_VND_WAP_COC; + stringToEnum["application/vnd.wap.sia"] = MIME_APPLICATION_VND_WAP_SIA; + stringToEnum["application/vnd.wap.connectivity-wbxml"] = + MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML; + stringToEnum["application/vnd.wap.multipart.form-data"] = + MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA; + stringToEnum["application/vnd.wap.multipart.byteranges"] = + MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES; + stringToEnum["application/vnd.wap.multipart.mixed"] = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED; + stringToEnum["application/vnd.wap.multipart.related"] = + MIME_APPLICATION_VND_WAP_MULTIPART_RELATED; + stringToEnum["application/vnd.wap.multipart.alternative"] = + MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE; + stringToEnum["application/vnd.wap.multipart.*"] = MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC; + stringToEnum["application/vnd.wap.wbxml"] = MIME_APPLICATION_VND_WAP_WBXML; + stringToEnum["application/vnd.oma.dd+xml"] = MIME_APPLICATION_VND_OMA_DD_XML; + stringToEnum["application/vnd.oma.drm.message"] = MIME_APPLICATION_VND_OMA_DRM_MESSAGE; + stringToEnum["application/vnd.oma.drm.content"] = MIME_APPLICATION_VND_OMA_DRM_CONTENT; + stringToEnum["application/vnd.oma.drm.rights+xml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML; + stringToEnum["application/vnd.oma.drm.rights+wbxml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML; + stringToEnum["application/vnd.oma.drm.ro+xml"] = MIME_APPLICATION_VND_OMA_DRM_RO_XML; + stringToEnum["application/vnd.oma.drm.dcf"] = MIME_APPLICATION_VND_OMA_DRM_DCF; + stringToEnum["application/vnd.oma.drm.roap-pdu+xml"] = MIME_APPLICATION_VND_OMA_ROAPPDU_XML; + stringToEnum["application/vnd.oma.drm.roap-trigger+xml"] = + MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML; + stringToEnum["application/vnd.smaf"] = MIME_APPLICATION_VND_SMAF; + stringToEnum["application/vnd.rn-realmedia"] = MIME_APPLICATION_VND_RN_REALMEDIA; + stringToEnum["application/vnd.sun.j2me.java-archive"] = + MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE; + stringToEnum["application/vnd.samsung.theme"] = MIME_APPLICATION_VND_SAMSUNG_THEME; + stringToEnum["application/vnd.ms-excel"] = MIME_APPLICATION_VND_EXCEL; + stringToEnum["application/vnd.ms-powerpoint"] = MIME_APPLICATION_VND_POWERPOINT; + stringToEnum["applcation/vnd.ms-word"] = MIME_APPLICATION_VND_MSWORD; + // 49 + stringToEnum["application/x-hdmlc"] = MIME_APPLICATION_X_HDMLC; + stringToEnum["application/x-x968-user-cert"] = MIME_APPLICATION_X_X968_USERCERT; + stringToEnum["application/x-www-form-urlencoded"] = MIME_APPLICATION_X_WWW_FORM_URLENCODED; + stringToEnum["application/x-smaf"] = MIME_APPLICATION_X_SMAF; + stringToEnum["application/x-shockwave-flash"] = MIME_APPLICATION_X_FLASH; + stringToEnum["application/x-msexcel"] = MIME_APPLICATION_X_EXCEL; + stringToEnum["application/x-mspowerpoint"] = MIME_APPLICATION_X_POWERPOINT; + // 56 + stringToEnum["audio/basic"] = MIME_AUDIO_BASIC; + stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG; + stringToEnum["audio/mp3"] = MIME_AUDIO_MP3; + stringToEnum["audio/mpg3"] = MIME_AUDIO_MPG3; + stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG3; + stringToEnum["audio/mpg"] = MIME_AUDIO_MPG; + stringToEnum["audio/aac"] = MIME_AUDIO_AAC; + stringToEnum["audio/g72"] = MIME_AUDIO_G72; + stringToEnum["audio/amr"] = MIME_AUDIO_AMR; + stringToEnum["audio/amr-wb"] = MIME_AUDIO_AMR_WB; + stringToEnum["audio/mmf"] = MIME_AUDIO_MMF; + stringToEnum["audio/smaf"] = MIME_AUDIO_SMAF; + stringToEnum["audio/iMelody"] = MIME_AUDIO_IMELODY; + stringToEnum["audio/imelody"] = MIME_AUDIO_IMELODY2; + stringToEnum["audio/melody"] = MIME_AUDIO_MELODY; + stringToEnum["audio/mid"] = MIME_AUDIO_MID; + stringToEnum["audio/midi"] = MIME_AUDIO_MIDI; + stringToEnum["audio/sp-midi"] = MIME_AUDIO_SP_MIDI; + stringToEnum["audio/wave"] = MIME_AUDIO_WAVE; + stringToEnum["audio/wav"] = MIME_AUDIO_WAV; + stringToEnum["audio/3gpp"] = MIME_AUDIO_3GPP; + stringToEnum["audio/mp4"] = MIME_AUDIO_MP4; + stringToEnum["audio/MP4A-LATM"] = MIME_AUDIO_MP4A_LATM; + stringToEnum["audio/m4a"] = MIME_AUDIO_M4A; + stringToEnum["audio/mpeg4"] = MIME_AUDIO_MPEG4; + stringToEnum["audio/wma"] = MIME_AUDIO_WMA; + stringToEnum["audio/xmf"] = MIME_AUDIO_XMF; + stringToEnum["audio/imy"] = MIME_AUDIO_IMY; + stringToEnum["audio/mobile-xmf"] = MIME_AUDIO_MOBILE_XMF; + // 85 + stringToEnum["audio/vnd.rn-realaudio"] = MIME_AUDIO_VND_RN_REALAUDIO; + // 86 + stringToEnum["audio/x-mpeg"] = MIME_AUDIO_X_MPEG; + stringToEnum["audio/x-mp3"] = MIME_AUDIO_X_MP3; + stringToEnum["audio/x-mpeg3"] = MIME_AUDIO_X_MPEG3; + stringToEnum["audio/x-mpg"] = MIME_AUDIO_X_MPG; + stringToEnum["audio/x-amr"] = MIME_AUDIO_X_AMR; + stringToEnum["audio/x-mmf"] = MIME_AUDIO_X_MMF; + stringToEnum["audio/x-smaf"] = MIME_AUDIO_X_SMAF; + stringToEnum["audio/x-iMelody"] = MIME_AUDIO_X_IMELODY; + stringToEnum["audio/x-midi"] = MIME_AUDIO_X_MIDI; + stringToEnum["audio/x-mpegaudio"] = MIME_AUDIO_X_MPEGAUDIO; + stringToEnum["audio/x-pn-realaudio"] = MIME_AUDIO_X_PN_REALAUDIO; + stringToEnum["audio/x-pn-multirate-realaudio"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO; + stringToEnum["audio/x-pn-multirate-realaudio-live"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE; + stringToEnum["audio/x-wave"] = MIME_AUDIO_X_WAVE; + stringToEnum["audio/x-wav"] = MIME_AUDIO_X_WAV; + stringToEnum["audio/x-ms-wma"] = MIME_AUDIO_X_MS_WMA; + stringToEnum["audio/x-mid"] = MIME_AUDIO_X_MID; + stringToEnum["audio/x-ms-asf"] = MIME_AUDIO_X_MS_ASF; + stringToEnum["audio/x-xmf"] = MIME_AUDIO_X_XMF; + // 105 + stringToEnum["image/gif"] = MIME_IMAGE_GIF; + stringToEnum["image/jpeg"] = MIME_IMAGE_JPEG; + stringToEnum["image/jpga"] = MIME_IMAGE_JPG; + stringToEnum["image/tiff"] = MIME_IMAGE_TIFF; + stringToEnum["image/tif"] = MIME_IMAGE_TIF; + stringToEnum["image/png"] = MIME_IMAGE_PNG; + stringToEnum["image/wbmp"] = MIME_IMAGE_WBMP; + stringToEnum["image/pjpeg"] = MIME_IMAGE_PJPEG; + stringToEnum["image/bmp"] = MIME_IMAGE_BMP; + stringToEnum["image/svg+xml"] = MIME_IMAGE_SVG; + stringToEnum["image/svg-xml"] = MIME_IMAGE_SVG1; + // 116 + stringToEnum["image/vnd.wap.wbmp"] = MIME_IMAGE_VND_WAP_WBMP; + stringToEnum["image/vnd.tmo.my5-gif"] = MIME_IMAGE_VND_TMO_GIF; + stringToEnum["image/vnd.tmo.my5-jpg"] = MIME_IMAGE_VND_TMO_JPG; + // 119 + stringToEnum["image/x-bmp"] = MIME_IMAGE_X_BMP; + // 120 + stringToEnum["message/rfc822"] = MIME_MESSAGE_RFC822; + // 121 + stringToEnum["multipart/mixed"] = MIME_MULTIPART_MIXED; + stringToEnum["multipart/related"] = MIME_MULTIPART_RELATED; + stringToEnum["multipart/alternative"] = MIME_MULTIPART_ALTERNATIVE; + stringToEnum["multipart/form-data"] = MIME_MULTIPART_FORM_DATA; + stringToEnum["multipart/byterange"] = MIME_MULTIPART_BYTERANGE; + stringToEnum["multipart/report"] = MIME_MULTIPART_REPORT; + stringToEnum["multipart/voice-message"] = MIME_MULTIPART_VOICE_MESSAGE; + // 128 + stringToEnum["text/txt"] = MIME_TEXT_TXT; + stringToEnum["text/html"] = MIME_TEXT_HTML; + stringToEnum["text/plain"] = MIME_TEXT_PLAIN; + stringToEnum["text/css"] = MIME_TEXT_CSS; + stringToEnum["text/xml"] = MIME_TEXT_XML; + stringToEnum["text/iMelody"] = MIME_TEXT_IMELODY; + // 134 + stringToEnum["text/vnd.wap.wmlscript"] = MIME_TEXT_VND_WAP_WMLSCRIPT; + stringToEnum["text/vnd.wap.wml"] = MIME_TEXT_VND_WAP_WML; + stringToEnum["text/vnd.wap.wta-event"] = MIME_TEXT_VND_WAP_WTA_EVENT; + stringToEnum["text/vnd.wap.connectivity-xml"] = MIME_TEXT_VND_WAP_CONNECTIVITY_XML; + stringToEnum["text/vnd.wap.si"] = MIME_TEXT_VND_WAP_SI; + stringToEnum["text/vnd.wap.sl"] = MIME_TEXT_VND_WAP_SL; + stringToEnum["text/vnd.wap.co"] = MIME_TEXT_VND_WAP_CO; + stringToEnum["text/vnd.sun.j2me.app-descriptor"] = MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR; + // 142 + stringToEnum["text/x-hdml"] = MIME_TEXT_X_HDML; + stringToEnum["text/x-vCalendar"] = MIME_TEXT_X_VCALENDAR; + stringToEnum["text/x-vCard"] = MIME_TEXT_X_VCARD; + stringToEnum["text/x-iMelody"] = MIME_TEXT_X_IMELODY; + stringToEnum["text/x-imelody"] = MIME_TEXT_X_IMELODY2; + stringToEnum["text/x-vnote"] = MIME_TEXT_X_VNOTE; + // 148 + stringToEnum["video/mpeg4"] = MIME_VIDEO_MPEG4; + stringToEnum["video/mp4"] = MIME_VIDEO_MP4; + stringToEnum["video/h263"] = MIME_VIDEO_H263; + stringToEnum["video/3gpp"] = MIME_VIDEO_3GPP; + stringToEnum["video/3gp"] = MIME_VIDEO_3GP; + stringToEnum["video/avi"] = MIME_VIDEO_AVI; + stringToEnum["video/sdp"] = MIME_VIDEO_SDP; + stringToEnum["video/mp4v-es"] = MIME_VIDEO_MP4_ES; + stringToEnum["video/mpeg"] = MIME_VIDEO_MPEG; + // 157 + stringToEnum["video/vnd.rn-realvideo"] = MIME_VIDEO_VND_RN_REALVIDEO; + stringToEnum["video/vnd.rn-realmedia"] = MIME_VIDEO_VND_RN_REALMEDIA; + // 159 + stringToEnum["video/x-mp4"] = MIME_VIDEO_X_MP4; + stringToEnum["video/x-pv-mp4"] = MIME_VIDEO_X_PV_MP4; + stringToEnum["video/x-pn-realvideo"] = MIME_VIDEO_X_PN_REALVIDEO; + stringToEnum["video/x-pn-multirate-realvideo"] = MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO; + stringToEnum["video/x-ms-wmv"] = MIME_VIDEO_X_MS_WMV; + stringToEnum["video/x-ms-asf"] = MIME_VIDEO_X_MS_ASF; + stringToEnum["video/x-pv-pvx"] = MIME_VIDEO_X_PV_PVX; + stringToEnum[""] = MIME_UNKNOWN; + + return stringToEnum; } -unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str) -{ - LoggerD("Entered"); - std::map::iterator it = MIMETypeStringToEnumMap.find(str); - if (it != MIMETypeStringToEnumMap.end()) { - return it->second; - } - return MIME_UNKNOWN; +unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str) { + LoggerD("Entered"); + std::map::iterator it = MIMETypeStringToEnumMap.find(str); + if (it != MIMETypeStringToEnumMap.end()) { + return it->second; + } + return MIME_UNKNOWN; } -std::string MessageAttachment::MIMETypeEnumToString(unsigned int num) -{ - LoggerD("Entered"); - std::map::iterator it = MIMETypeEnumToStringMap.find(num); - if (it != MIMETypeEnumToStringMap.end()) { - return it->second; - } - return std::string(); +std::string MessageAttachment::MIMETypeEnumToString(unsigned int num) { + LoggerD("Entered"); + std::map::iterator it = MIMETypeEnumToStringMap.find(num); + if (it != MIMETypeEnumToStringMap.end()) { + return it->second; + } + return std::string(); } -void MessageAttachment::updateWithAttachmentData(const email_attachment_data_t& attachment_data) -{ - LoggerD("Entered"); - setId(attachment_data.attachment_id); - setMessageId(attachment_data.mail_id); - if (attachment_data.attachment_mime_type) { - setMimeType(attachment_data.attachment_mime_type); - } - - bool isSaved = false; - if (attachment_data.attachment_path) { - setFilePath(attachment_data.attachment_path); - - LoggerD("save status: %d", attachment_data.save_status); - LoggerD("attachment_size : %d", attachment_data.attachment_size); - isSaved = attachment_data.save_status; - } - - setIsSaved(isSaved); +void MessageAttachment::updateWithAttachmentData(const email_attachment_data_t& attachment_data) { + LoggerD("Entered"); + setId(attachment_data.attachment_id); + setMessageId(attachment_data.mail_id); + if (attachment_data.attachment_mime_type) { + setMimeType(attachment_data.attachment_mime_type); + } + + bool isSaved = false; + if (attachment_data.attachment_path) { + setFilePath(attachment_data.attachment_path); + + LoggerD("save status: %d", attachment_data.save_status); + LoggerD("attachment_size : %d", attachment_data.attachment_size); + isSaved = attachment_data.save_status; + } + + setIsSaved(isSaved); } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_attachment.h b/src/messaging/message_attachment.h index 77e44b1..78fb9c1 100644 --- a/src/messaging/message_attachment.h +++ b/src/messaging/message_attachment.h @@ -17,12 +17,12 @@ #ifndef MESSAGING_MESSAGE_ATTACHMENT_H_ #define MESSAGING_MESSAGE_ATTACHMENT_H_ -#include +#include +#include +#include #include +#include #include -#include -#include -#include namespace extension { namespace messaging { @@ -30,63 +30,64 @@ namespace messaging { class MessageAttachment; struct MessageAttachmentHolder { - std::shared_ptr ptr; + std::shared_ptr ptr; }; typedef std::vector> AttachmentPtrVector; class MessageAttachment { -private: - static std::map& MIMETypeStringToEnumMap; - static std::map& MIMETypeEnumToStringMap; - static std::map& initializeMIMETypeStringToEnumMap(); - static std::map& initializeMIMETypeEnumToStringMap(); - int m_id; - bool m_isIdSet; - int m_messageId; - bool m_isMessageIdSet; - std::string m_mimeType; - bool m_isMimeTypeSet; - std::string m_filePath; - bool m_isFilePathSet; - bool m_isSaved; -public: - MessageAttachment(); - ~MessageAttachment(); + private: + static std::map& MIMETypeStringToEnumMap; + static std::map& MIMETypeEnumToStringMap; + static std::map& initializeMIMETypeStringToEnumMap(); + static std::map& initializeMIMETypeEnumToStringMap(); + int m_id; + bool m_isIdSet; + int m_messageId; + bool m_isMessageIdSet; + std::string m_mimeType; + bool m_isMimeTypeSet; + std::string m_filePath; + bool m_isFilePathSet; + bool m_isSaved; + + public: + MessageAttachment(); + ~MessageAttachment(); - int getId(); - void setId(int value); - bool isIdSet(); - void unsetId(); - int getMessageId(); - void setMessageId(int value); - bool isMessageIdSet(); - void unsetMessageId(); - std::string getMimeType(); - void setMimeType(const std::string &value); - bool isMimeTypeSet(); - void unsetMimeType(); - std::string getFilePath(); - std::string getShortFileName() const; - void setFilePath(const std::string &value); - bool isFilePathSet(); - void unsetFilePath(); - void setIsSaved(const bool isSaved); - bool isSaved() const; - static unsigned int MIMETypeStringToEnum(std::string str); - static std::string MIMETypeEnumToString(unsigned int num); + int getId(); + void setId(int value); + bool isIdSet(); + void unsetId(); + int getMessageId(); + void setMessageId(int value); + bool isMessageIdSet(); + void unsetMessageId(); + std::string getMimeType(); + void setMimeType(const std::string& value); + bool isMimeTypeSet(); + void unsetMimeType(); + std::string getFilePath(); + std::string getShortFileName() const; + void setFilePath(const std::string& value); + bool isFilePathSet(); + void unsetFilePath(); + void setIsSaved(const bool isSaved); + bool isSaved() const; + static unsigned int MIMETypeStringToEnum(std::string str); + static std::string MIMETypeEnumToString(unsigned int num); - /** - * This methods updates: - * setId(attachment_data.attachment_id); - * setMessageId(attachment_data.mail_id); - * setMimeType(attachment_data.attachment_mime_type); - * setFilePath(attachment_data.attachment_path); - */ - void updateWithAttachmentData(const email_attachment_data_t& attachment_data); + /** + * This methods updates: + * setId(attachment_data.attachment_id); + * setMessageId(attachment_data.mail_id); + * setMimeType(attachment_data.attachment_mime_type); + * setFilePath(attachment_data.attachment_path); + */ + void updateWithAttachmentData(const email_attachment_data_t& attachment_data); }; -} // messaging -} // extension +} // messaging +} // extension -#endif // MESSAGING_MESSAGE_ATTACHMENT_H_ +#endif // MESSAGING_MESSAGE_ATTACHMENT_H_ diff --git a/src/messaging/message_body.cc b/src/messaging/message_body.cc old mode 100755 new mode 100644 index 50181e8..8349d8e --- a/src/messaging/message_body.cc +++ b/src/messaging/message_body.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_body.h" #include "common/logger.h" @@ -26,121 +26,99 @@ namespace messaging { using namespace common; -MessageBody::MessageBody() : m_messageId(1), - m_messageId_set(false), - m_loaded(false), - m_plainBody(""), - m_htmlBody("") -{ - LoggerD("Entered"); +MessageBody::MessageBody() + : m_messageId(1), m_messageId_set(false), m_loaded(false), m_plainBody(""), m_htmlBody("") { + LoggerD("Entered"); } -MessageBody::~MessageBody() -{ - LoggerD("Entered"); +MessageBody::~MessageBody() { + LoggerD("Entered"); } // messageId -int MessageBody::getMessageId() const -{ - - return m_messageId; +int MessageBody::getMessageId() const { + return m_messageId; } -void MessageBody::setMessageId(int value) -{ - m_messageId = value; - m_messageId_set = true; +void MessageBody::setMessageId(int value) { + m_messageId = value; + m_messageId_set = true; } // loaded -bool MessageBody::getLoaded() const -{ - return m_loaded; +bool MessageBody::getLoaded() const { + return m_loaded; } -void MessageBody::setLoaded(bool value) -{ - m_loaded = value; +void MessageBody::setLoaded(bool value) { + m_loaded = value; } // plainBody -std::string MessageBody::getPlainBody() const -{ - return m_plainBody; +std::string MessageBody::getPlainBody() const { + return m_plainBody; } -void MessageBody::setPlainBody(const std::string &value) -{ - m_plainBody = value; +void MessageBody::setPlainBody(const std::string& value) { + m_plainBody = value; } // htmlBody -std::string MessageBody::getHtmlBody() const -{ - return m_htmlBody; +std::string MessageBody::getHtmlBody() const { + return m_htmlBody; } -void MessageBody::setHtmlBody(const std::string &value) -{ - m_htmlBody = value; +void MessageBody::setHtmlBody(const std::string& value) { + m_htmlBody = value; } // inlineAttachments -AttachmentPtrVector MessageBody::getInlineAttachments() const -{ - return m_inlineAttachments; +AttachmentPtrVector MessageBody::getInlineAttachments() const { + return m_inlineAttachments; } -void MessageBody::setInlineAttachments(const AttachmentPtrVector& attachments) -{ - m_inlineAttachments = attachments; +void MessageBody::setInlineAttachments(const AttachmentPtrVector& attachments) { + m_inlineAttachments = attachments; } // *** support for optional, nullable (at JS layer) attibutes -bool MessageBody::is_message_id_set() const -{ - return m_messageId_set; +bool MessageBody::is_message_id_set() const { + return m_messageId_set; } -PlatformResult MessageBody::updateBody(email_mail_data_t& mail) -{ - LoggerD("Entered"); - setMessageId(mail.mail_id); - setLoaded(mail.body_download_status); - - if (mail.file_path_plain) { - SLoggerD("Plain body: %s", mail.file_path_plain); - std::string result = ""; - PlatformResult ret = MessagingUtil::loadFileContentToString(mail.file_path_plain, - &result); - if (ret.IsError()) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Fail to open plain body.", - ("%s", ret.message().c_str())); - } - setPlainBody(result); +PlatformResult MessageBody::updateBody(email_mail_data_t& mail) { + LoggerD("Entered"); + setMessageId(mail.mail_id); + setLoaded(mail.body_download_status); + + if (mail.file_path_plain) { + SLoggerD("Plain body: %s", mail.file_path_plain); + std::string result = ""; + PlatformResult ret = MessagingUtil::loadFileContentToString(mail.file_path_plain, &result); + if (ret.IsError()) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to open plain body.", + ("%s", ret.message().c_str())); } - - if (mail.file_path_html) { - SLoggerD("HTML body: %s", mail.file_path_html); - std::string result = ""; - PlatformResult ret = MessagingUtil::loadFileContentToString(mail.file_path_html, - &result); - if (ret.IsError()) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Fail to open html body.", - ("%s", ret.message().c_str())); - } - setHtmlBody(result); + setPlainBody(result); + } + + if (mail.file_path_html) { + SLoggerD("HTML body: %s", mail.file_path_html); + std::string result = ""; + PlatformResult ret = MessagingUtil::loadFileContentToString(mail.file_path_html, &result); + if (ret.IsError()) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Fail to open html body.", + ("%s", ret.message().c_str())); } - return PlatformResult(ErrorCode::NO_ERROR); + setHtmlBody(result); + } + return PlatformResult(ErrorCode::NO_ERROR); } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_body.h b/src/messaging/message_body.h index 1e8164a..8af51ab 100644 --- a/src/messaging/message_body.h +++ b/src/messaging/message_body.h @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_BODY_H_ #define MESSAGING_MESSAGE_BODY_H_ #include -#include #include +#include -#include "message_attachment.h" #include "common/platform_result.h" +#include "message_attachment.h" namespace extension { namespace messaging { @@ -30,42 +30,42 @@ namespace messaging { class MessageBody; struct MessageBodyHolder { - std::shared_ptr ptr; + std::shared_ptr ptr; }; class MessageBody { -public: - explicit MessageBody(); - ~MessageBody(); - int getMessageId() const; - void setMessageId(int value); - bool getLoaded() const; - void setLoaded(bool value); - std::string getPlainBody() const; - void setPlainBody(const std::string &value); - std::string getHtmlBody() const; - void setHtmlBody(const std::string &value); - AttachmentPtrVector getInlineAttachments() const; - void setInlineAttachments(const AttachmentPtrVector& attachments); + public: + explicit MessageBody(); + ~MessageBody(); + int getMessageId() const; + void setMessageId(int value); + bool getLoaded() const; + void setLoaded(bool value); + std::string getPlainBody() const; + void setPlainBody(const std::string& value); + std::string getHtmlBody() const; + void setHtmlBody(const std::string& value); + AttachmentPtrVector getInlineAttachments() const; + void setInlineAttachments(const AttachmentPtrVector& attachments); - // support for optional, nullable (at JS layer) attibutes - bool is_message_id_set() const; - /** - * Updates body with data from email_mail_data_t structure. - * @param mail - */ - common::PlatformResult updateBody(email_mail_data_t& mail); + // support for optional, nullable (at JS layer) attibutes + bool is_message_id_set() const; + /** + * Updates body with data from email_mail_data_t structure. + * @param mail + */ + common::PlatformResult updateBody(email_mail_data_t& mail); -private: - int m_messageId; - bool m_messageId_set; - bool m_loaded; - std::string m_plainBody; - std::string m_htmlBody; - AttachmentPtrVector m_inlineAttachments; + private: + int m_messageId; + bool m_messageId_set; + bool m_loaded; + std::string m_plainBody; + std::string m_htmlBody; + AttachmentPtrVector m_inlineAttachments; }; -} // messaging -} // extension +} // messaging +} // extension -#endif // MESSAGING_MESSAGE_BODY_H_ +#endif // MESSAGING_MESSAGE_BODY_H_ diff --git a/src/messaging/message_callback_user_data.cc b/src/messaging/message_callback_user_data.cc old mode 100755 new mode 100644 index 82d521f..c7479bd --- a/src/messaging/message_callback_user_data.cc +++ b/src/messaging/message_callback_user_data.cc @@ -13,39 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_callback_user_data.h" #include "messaging_util.h" namespace extension { namespace messaging { -MessageCallbackUserData::MessageCallbackUserData(PostQueue& queue, long cid) : - CallbackUserData(queue, cid), - m_account_id(0) { +MessageCallbackUserData::MessageCallbackUserData(PostQueue& queue, long cid) + : CallbackUserData(queue, cid), m_account_id(0) { LoggerD("Entered"); } MessageCallbackUserData::~MessageCallbackUserData() { - LoggerD("Entered"); + LoggerD("Entered"); } void MessageCallbackUserData::setMessage(std::shared_ptr message) { - m_message = message; + m_message = message; } std::shared_ptr MessageCallbackUserData::getMessage() const { - return m_message; + return m_message; } -void MessageCallbackUserData::setAccountId(int account_id){ - m_account_id = account_id; +void MessageCallbackUserData::setAccountId(int account_id) { + m_account_id = account_id; } -int MessageCallbackUserData::getAccountId() const -{ - return m_account_id; +int MessageCallbackUserData::getAccountId() const { + return m_account_id; } -}//messaging -}//extension +} // messaging +} // extension diff --git a/src/messaging/message_callback_user_data.h b/src/messaging/message_callback_user_data.h index 098c8cd..c1f7c1a 100644 --- a/src/messaging/message_callback_user_data.h +++ b/src/messaging/message_callback_user_data.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_CALLBACK_USER_DATA_H_ #define MESSAGING_MESSAGE_CALLBACK_USER_DATA_H_ @@ -30,23 +30,22 @@ class Message; class PostQueue; class MessageCallbackUserData : public CallbackUserData { -public: - MessageCallbackUserData(PostQueue& queue, long cid); - virtual ~MessageCallbackUserData(); + public: + MessageCallbackUserData(PostQueue& queue, long cid); + virtual ~MessageCallbackUserData(); - void setMessage(std::shared_ptr message); - std::shared_ptr getMessage() const; + void setMessage(std::shared_ptr message); + std::shared_ptr getMessage() const; - void setAccountId(int account_id); - int getAccountId() const; + void setAccountId(int account_id); + int getAccountId() const; -private: - std::shared_ptr m_message; - int m_account_id; + private: + std::shared_ptr m_message; + int m_account_id; }; -}//messaging -}//extension +} // messaging +} // extension #endif /* MESSAGING_MESSAGE_CALLBACK_USER_DATA_H_ */ - diff --git a/src/messaging/message_conversation.cc b/src/messaging/message_conversation.cc old mode 100755 new mode 100644 index a02b8e6..ed2b475 --- a/src/messaging/message_conversation.cc +++ b/src/messaging/message_conversation.cc @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "common/logger.h" #include "common/platform_exception.h" -#include "messaging_util.h" #include "message.h" #include "message_conversation.h" +#include "messaging_util.h" #define MAX_THREAD_DATA_LEN 128 @@ -32,444 +32,381 @@ namespace messaging { using namespace tizen; // *** constructor -MessageConversation::MessageConversation(): - m_conversation_id(-1), - m_conversation_type(UNDEFINED), - m_timestamp(-1), - m_count(0), - m_unread_messages(0), - m_is_read(false), - m_last_message_id(-1) -{ - LoggerD("Message Conversation constructor."); -} - -MessageConversation::~MessageConversation() -{ - LoggerD("Message Conversation destructor."); +MessageConversation::MessageConversation() + : m_conversation_id(-1), + m_conversation_type(UNDEFINED), + m_timestamp(-1), + m_count(0), + m_unread_messages(0), + m_is_read(false), + m_last_message_id(-1) { + LoggerD("Message Conversation constructor."); +} + +MessageConversation::~MessageConversation() { + LoggerD("Message Conversation destructor."); } // *** attributes getters -int MessageConversation::getConversationId() const -{ - return m_conversation_id; +int MessageConversation::getConversationId() const { + return m_conversation_id; } -MessageType MessageConversation::getType() const -{ - return m_conversation_type; +MessageType MessageConversation::getType() const { + return m_conversation_type; } std::string MessageConversation::getTypeString() const { return MessagingUtil::messageTypeToString(getType()); } -time_t MessageConversation::getTimestamp() const -{ - return m_timestamp; +time_t MessageConversation::getTimestamp() const { + return m_timestamp; } -unsigned long MessageConversation::getMessageCount() const -{ - return m_count; +unsigned long MessageConversation::getMessageCount() const { + return m_count; } -unsigned long MessageConversation::getUnreadMessages() const -{ - return m_unread_messages; +unsigned long MessageConversation::getUnreadMessages() const { + return m_unread_messages; } -std::string MessageConversation::getPreview() const -{ - return m_preview; +std::string MessageConversation::getPreview() const { + return m_preview; } -std::string MessageConversation::getSubject() const -{ - return m_conversation_subject; +std::string MessageConversation::getSubject() const { + return m_conversation_subject; } -bool MessageConversation::getIsRead() const -{ - return m_is_read; +bool MessageConversation::getIsRead() const { + return m_is_read; } -std::string MessageConversation::getFrom() const -{ - return m_from; +std::string MessageConversation::getFrom() const { + return m_from; } -std::vector MessageConversation::getTo() const -{ - return m_to; +std::vector MessageConversation::getTo() const { + return m_to; } -std::vector MessageConversation::getCC() const -{ - return m_cc; +std::vector MessageConversation::getCC() const { + return m_cc; } -std::vector MessageConversation::getBCC() const -{ - return m_bcc; +std::vector MessageConversation::getBCC() const { + return m_bcc; } -int MessageConversation::getLastMessageId() const -{ - return m_last_message_id; +int MessageConversation::getLastMessageId() const { + return m_last_message_id; } PlatformResult MessageConversation::convertMsgConversationToObject( - unsigned int threadId, msg_handle_t handle, std::shared_ptr* result) -{ - LoggerD("Entered"); - std::shared_ptr conversation (new MessageConversation()); - - msg_struct_t msgInfo = NULL; - msg_struct_t sendOpt = NULL; - - msg_struct_t msg_thread = NULL; - - msg_struct_list_s convViewList; - msg_list_handle_t addr_list = NULL; - msg_struct_t addr_info = NULL; - - int tempInt; - bool tempBool; - int nToCnt; - unsigned int lastMsgIndex = 0; - char msgData[MAX_THREAD_DATA_LEN] = {0,}; - - msgInfo = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); - std::unique_ptr::type, int(*)(msg_struct_t*)> - msg_info_ptr(&msgInfo, &msg_release_struct); - // automatically release the memory - sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); - std::unique_ptr::type, int(*)(msg_struct_t*)> - send_opt_ptr(&sendOpt, &msg_release_struct); - // automatically release the memory + unsigned int threadId, msg_handle_t handle, std::shared_ptr* result) { + LoggerD("Entered"); + std::shared_ptr conversation(new MessageConversation()); + + msg_struct_t msgInfo = NULL; + msg_struct_t sendOpt = NULL; + + msg_struct_t msg_thread = NULL; + + msg_struct_list_s convViewList; + msg_list_handle_t addr_list = NULL; + msg_struct_t addr_info = NULL; + + int tempInt; + bool tempBool; + int nToCnt; + unsigned int lastMsgIndex = 0; + char msgData[MAX_THREAD_DATA_LEN] = { + 0, + }; + + msgInfo = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); + std::unique_ptr::type, int (*)(msg_struct_t*)> msg_info_ptr( + &msgInfo, &msg_release_struct); + // automatically release the memory + sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); + std::unique_ptr::type, int (*)(msg_struct_t*)> send_opt_ptr( + &sendOpt, &msg_release_struct); + // automatically release the memory + + conversation->m_conversation_id = threadId; + + msg_thread = msg_create_struct(MSG_STRUCT_THREAD_INFO); + std::unique_ptr::type, int (*)(msg_struct_t*)> msg_thread_ptr( + &msg_thread, &msg_release_struct); + // automatically release the memory + msg_error_t err = msg_get_thread(handle, conversation->m_conversation_id, msg_thread); + if (err != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to retrieve thread.", + ("msg_get_thread error: %d (%s)", err, get_error_message(err))); + } + msg_get_int_value(msg_thread, MSG_THREAD_MSG_TYPE_INT, &tempInt); + switch (tempInt) { + 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: + conversation->m_conversation_type = SMS; + break; + case MSG_TYPE_MMS: + case MSG_TYPE_MMS_JAVA: + case MSG_TYPE_MMS_NOTI: + conversation->m_conversation_type = MMS; + break; + } - conversation->m_conversation_id = threadId; + msg_get_int_value(msg_thread, MSG_THREAD_MSG_TIME_INT, &tempInt); + conversation->m_timestamp = tempInt; - msg_thread = msg_create_struct(MSG_STRUCT_THREAD_INFO); - std::unique_ptr::type, int(*)(msg_struct_t*)> - msg_thread_ptr(&msg_thread, &msg_release_struct); - // automatically release the memory - msg_error_t err = msg_get_thread(handle, conversation->m_conversation_id, msg_thread); - if (err != MSG_SUCCESS) - { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to retrieve thread.", - ("msg_get_thread error: %d (%s)", err, get_error_message(err))); + msg_get_int_value(msg_thread, MSG_THREAD_UNREAD_COUNT_INT, &tempInt); + conversation->m_unread_messages = tempInt; + + msg_get_str_value(msg_thread, MSG_THREAD_MSG_DATA_STR, msgData, MAX_THREAD_DATA_LEN); + + conversation->setPreview(msgData); + + err = msg_get_conversation_view_list(handle, conversation->m_conversation_id, &convViewList); + std::unique_ptr::type, int (*)(msg_struct_list_s*)> + conv_view_list_ptr(&convViewList, &msg_release_list_struct); + // automatically release the memory + if (err != MSG_SUCCESS) { + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Get conversation(msg) view list fail.", + ("msg_get_conversation_view_list error: %d (%s)", err, get_error_message(err))); + } + + lastMsgIndex = convViewList.nCount - 1; + conversation->m_count = convViewList.nCount; + + msg_get_bool_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_READ_BOOL, &tempBool); + conversation->m_is_read = tempBool; + + msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_ID_INT, &tempInt); + conversation->m_last_message_id = tempInt; + + err = msg_get_message(handle, conversation->m_last_message_id, msgInfo, sendOpt); + if (err != MSG_SUCCESS) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "get message fail.", + ("msg_get_message error: %d (%s)", err, get_error_message(err))); + } + + msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_DIRECTION_INT, + &tempInt); + + msg_get_list_handle(msgInfo, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); + nToCnt = msg_list_length(addr_list); + + if (MSG_DIRECTION_TYPE_MT == tempInt) { + if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT) { + char strNumber[MAX_ADDRESS_VAL_LEN] = { + 0, + }; + addr_info = (msg_struct_t)msg_list_nth_data(addr_list, nToCnt - 1); + msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, + MAX_ADDRESS_VAL_LEN); + + if (strNumber[0] != '\0') { + conversation->m_from = strNumber; + } else { + LoggerD("address is null "); + } + } else { + LoggerD("address count index fail"); } - msg_get_int_value(msg_thread, MSG_THREAD_MSG_TYPE_INT, &tempInt); - switch(tempInt) - { - 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: - conversation->m_conversation_type = SMS; - break; - case MSG_TYPE_MMS: - case MSG_TYPE_MMS_JAVA: - case MSG_TYPE_MMS_NOTI: - conversation->m_conversation_type = MMS; - break; + } else { + if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT) { + for (int index = 0; index < nToCnt; index++) { + addr_info = (msg_struct_t)msg_list_nth_data(addr_list, index); + char strNumber[MAX_ADDRESS_VAL_LEN] = { + 0, + }; + msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, + MAX_ADDRESS_VAL_LEN); + + conversation->m_to.push_back(strNumber); + } + } else { + LoggerD("address fetch fail"); } + } + + char strTemp[MAX_SUBJECT_LEN] = {0}; + msg_get_str_value(msgInfo, MSG_MESSAGE_SUBJECT_STR, strTemp, MAX_SUBJECT_LEN); + + conversation->setSubject(strTemp); - msg_get_int_value(msg_thread, MSG_THREAD_MSG_TIME_INT, &tempInt); - conversation->m_timestamp = tempInt; + *result = conversation; + return PlatformResult(ErrorCode::NO_ERROR); +} - msg_get_int_value(msg_thread, MSG_THREAD_UNREAD_COUNT_INT, &tempInt); - conversation->m_unread_messages = tempInt; +PlatformResult MessageConversation::convertEmailConversationToObject( + unsigned int threadId, std::shared_ptr* result) { + LoggerD("Entered"); + std::shared_ptr conversation(new MessageConversation()); - msg_get_str_value(msg_thread, MSG_THREAD_MSG_DATA_STR, msgData, MAX_THREAD_DATA_LEN); + email_mail_list_item_t* resultMail = NULL; - conversation->setPreview(msgData); + int ntv_ret = email_get_thread_information_ex(threadId, &resultMail); + if (ntv_ret != EMAIL_ERROR_NONE) { + if (resultMail) { + if (resultMail->eas_data) { + free(resultMail->eas_data); + } + free(resultMail); + } - err = msg_get_conversation_view_list(handle, conversation->m_conversation_id, - &convViewList); - std::unique_ptr::type, int(*)(msg_struct_list_s*)> - conv_view_list_ptr(&convViewList, &msg_release_list_struct); - // automatically release the memory - if (err != MSG_SUCCESS) - { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get conversation(msg) view list fail.", - ("msg_get_conversation_view_list error: %d (%s)", err, get_error_message(err))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Couldn't get conversation.", + ("email_get_thread_information_ex error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } else { + if (!resultMail) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get email data fail.", ("Data is null")); } - lastMsgIndex = convViewList.nCount - 1; - conversation->m_count = convViewList.nCount; + email_mail_data_t* mailData = NULL; - msg_get_bool_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_READ_BOOL, &tempBool); - conversation->m_is_read = tempBool; + ntv_ret = email_get_mail_data(resultMail->mail_id, &mailData); + if (ntv_ret != EMAIL_ERROR_NONE) { + free(resultMail); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Get email data fail.", + ("email_get_mail_data error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + } - msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_ID_INT, &tempInt); - conversation->m_last_message_id = tempInt; + if (!mailData) { + free(resultMail); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get email data fail."); + } - err = msg_get_message(handle, conversation->m_last_message_id, msgInfo, sendOpt); - if (err != MSG_SUCCESS) - { + int index = 0; + int count = 0; + conversation->m_unread_messages = 0; + email_mail_list_item_t* mailList = NULL; + + ntv_ret = + email_get_mail_list(mailData->account_id, 0, threadId, 0, resultMail->thread_item_count, + EMAIL_SORT_DATETIME_HIGH, &mailList, &count); + if (ntv_ret != EMAIL_ERROR_NONE) { + email_free_mail_data(&mailData, 1); + free(resultMail); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "get message fail.", - ("msg_get_message error: %d (%s)", err, get_error_message(err))); + ErrorCode::UNKNOWN_ERR, "Get email data list fail.", + ("email_get_mail_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_DIRECTION_INT, &tempInt); - - msg_get_list_handle(msgInfo, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list); - nToCnt = msg_list_length(addr_list); - - if (MSG_DIRECTION_TYPE_MT == tempInt) - { - if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT ) - { - char strNumber[MAX_ADDRESS_VAL_LEN] = {0,}; - addr_info = (msg_struct_t)msg_list_nth_data(addr_list, nToCnt-1); - msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN); - - if (strNumber[0] != '\0') - { - conversation->m_from = strNumber; - } - else - { - LoggerD("address is null "); - } - } - else - { - LoggerD("address count index fail"); + for (index = 0; index < count; index++) { + if (mailList[index].flags_seen_field) { + conversation->m_unread_messages++; } } - else - { - if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT ) - { - for (int index = 0; index < nToCnt; index++) - { - addr_info = (msg_struct_t)msg_list_nth_data(addr_list, index); - char strNumber[MAX_ADDRESS_VAL_LEN] = {0,}; - msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN); - - conversation->m_to.push_back(strNumber); - } - } - else - { - LoggerD("address fetch fail"); - } + conversation->m_count = resultMail->thread_item_count; + + conversation->m_conversation_id = threadId; + + conversation->m_conversation_type = MessageType::EMAIL; + + conversation->m_timestamp = resultMail->date_time; + + if (resultMail->preview_text[0] != '\0') { + conversation->setPreview(resultMail->preview_text); + } + + if (resultMail->subject[0] != '\0') { + conversation->setSubject(resultMail->subject); } - char strTemp[MAX_SUBJECT_LEN] = {0}; - msg_get_str_value(msgInfo, MSG_MESSAGE_SUBJECT_STR, strTemp, MAX_SUBJECT_LEN); + conversation->m_is_read = (bool)resultMail->flags_seen_field; - conversation->setSubject(strTemp); + if (resultMail->full_address_from[0] != '\0') { + conversation->m_from = + MessagingUtil::extractSingleEmailAddress(resultMail->full_address_from); + } - *result = conversation; - return PlatformResult(ErrorCode::NO_ERROR); -} + if (mailData->full_address_to != NULL) { + conversation->m_to = Message::getEmailRecipientsFromStruct(mailData->full_address_to); + } -PlatformResult MessageConversation::convertEmailConversationToObject( - unsigned int threadId, std::shared_ptr* result) -{ - LoggerD("Entered"); - std::shared_ptr conversation (new MessageConversation()); - - email_mail_list_item_t *resultMail = NULL; - - int ntv_ret = email_get_thread_information_ex(threadId, &resultMail); - if(ntv_ret != EMAIL_ERROR_NONE) - { - if (resultMail) - { - if(resultMail->eas_data) - { - free(resultMail->eas_data); - } - free(resultMail); - } - - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't get conversation.", - ("email_get_thread_information_ex error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } else { - if (!resultMail) - { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get email data fail.", - ("Data is null")); - } - - email_mail_data_t* mailData = NULL; - - ntv_ret = email_get_mail_data(resultMail->mail_id, &mailData); - if (ntv_ret != EMAIL_ERROR_NONE) - { - free(resultMail); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get email data fail.", - ("email_get_mail_data error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } - - if (!mailData) { - free(resultMail); - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get email data fail."); - } - - int index = 0; - int count = 0; - conversation->m_unread_messages = 0; - email_mail_list_item_t *mailList = NULL; - - ntv_ret = email_get_mail_list( - mailData->account_id, 0, threadId, 0, - resultMail->thread_item_count, EMAIL_SORT_DATETIME_HIGH, &mailList, - &count); - if (ntv_ret != EMAIL_ERROR_NONE) - { - email_free_mail_data(&mailData , 1); - free(resultMail); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Get email data list fail.", - ("email_get_mail_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); - } - - for (index = 0; index < count; index++) - { - if (mailList[index].flags_seen_field) - { - conversation->m_unread_messages++; - } - } - conversation->m_count = resultMail->thread_item_count; - - conversation->m_conversation_id = threadId; - - conversation->m_conversation_type = MessageType::EMAIL; - - conversation->m_timestamp = resultMail->date_time; - - if (resultMail->preview_text[0] != '\0') - { - conversation->setPreview(resultMail->preview_text); - } - - if (resultMail->subject[0] != '\0') - { - conversation->setSubject(resultMail->subject); - } - - conversation->m_is_read = (bool)resultMail->flags_seen_field; - - if (resultMail->full_address_from[0] != '\0') - { - conversation->m_from = MessagingUtil::extractSingleEmailAddress( - resultMail->full_address_from); - } - - if (mailData->full_address_to != NULL) - { - conversation->m_to = Message::getEmailRecipientsFromStruct( - mailData->full_address_to); - } - - if (mailData->full_address_cc != NULL) - { - conversation->m_cc = Message::getEmailRecipientsFromStruct( - mailData->full_address_cc); - } - - if (mailData->full_address_bcc != NULL) - { - conversation->m_bcc = Message::getEmailRecipientsFromStruct( - mailData->full_address_bcc); - } - - conversation->m_last_message_id = resultMail->mail_id; - - if (mailData != NULL) - { - email_free_mail_data(&mailData , 1); - } + if (mailData->full_address_cc != NULL) { + conversation->m_cc = Message::getEmailRecipientsFromStruct(mailData->full_address_cc); } - if (resultMail != NULL) - { - free(resultMail); + if (mailData->full_address_bcc != NULL) { + conversation->m_bcc = Message::getEmailRecipientsFromStruct(mailData->full_address_bcc); } - *result = conversation; - return PlatformResult(ErrorCode::NO_ERROR); + conversation->m_last_message_id = resultMail->mail_id; + + if (mailData != NULL) { + email_free_mail_data(&mailData, 1); + } + } + + if (resultMail != NULL) { + free(resultMail); + } + + *result = conversation; + return PlatformResult(ErrorCode::NO_ERROR); } -void MessageConversation::setConversationId(int id) -{ - m_conversation_id = id; +void MessageConversation::setConversationId(int id) { + m_conversation_id = id; } -void MessageConversation::setType(MessageType type) -{ - m_conversation_type = type; +void MessageConversation::setType(MessageType type) { + m_conversation_type = type; } -void MessageConversation::setTimestamp(time_t timestamp) -{ - m_timestamp = timestamp; +void MessageConversation::setTimestamp(time_t timestamp) { + m_timestamp = timestamp; } -void MessageConversation::setMessageCount(int count) -{ - m_count = count; +void MessageConversation::setMessageCount(int count) { + m_count = count; } -void MessageConversation::setUnreadMessages(int unread_messages) -{ - m_unread_messages = unread_messages; +void MessageConversation::setUnreadMessages(int unread_messages) { + m_unread_messages = unread_messages; } -void MessageConversation::setPreview(std::string preview) -{ - m_preview = SanitizeUtf8String(preview); +void MessageConversation::setPreview(std::string preview) { + m_preview = SanitizeUtf8String(preview); } -void MessageConversation::setSubject(std::string conversation_subject) -{ - m_conversation_subject = SanitizeUtf8String(conversation_subject); +void MessageConversation::setSubject(std::string conversation_subject) { + m_conversation_subject = SanitizeUtf8String(conversation_subject); } -void MessageConversation::setIsRead(bool is_read) -{ - m_is_read = is_read; +void MessageConversation::setIsRead(bool is_read) { + m_is_read = is_read; } -void MessageConversation::setFrom(std::string from) -{ - m_from = from; +void MessageConversation::setFrom(std::string from) { + m_from = from; } -void MessageConversation::setTo(std::vector &to) -{ - m_to = to; +void MessageConversation::setTo(std::vector& to) { + m_to = to; } -void MessageConversation::setCC(std::vector &cc) -{ - m_cc = cc; +void MessageConversation::setCC(std::vector& cc) { + m_cc = cc; } -void MessageConversation::setBCC(std::vector &bcc) -{ - m_bcc = bcc; +void MessageConversation::setBCC(std::vector& bcc) { + m_bcc = bcc; } -void MessageConversation::setLastMessageId(int last_message_id) -{ - m_last_message_id = last_message_id; +void MessageConversation::setLastMessageId(int last_message_id) { + m_last_message_id = last_message_id; } /** @@ -501,65 +438,51 @@ const std::string UNREAD_MESSAGES = MESSAGE_CONVERSATION_ATTRIBUTE_UNREAD_MESSAG const std::string PREVIEW = MESSAGE_CONVERSATION_ATTRIBUTE_PREVIEW; const std::string FROM = MESSAGE_CONVERSATION_ATTRIBUTE_FROM; const std::string TO = MESSAGE_CONVERSATION_ATTRIBUTE_TO; -} //namespace CONVERSATION_FILTER_ATTRIBUTE +} // namespace CONVERSATION_FILTER_ATTRIBUTE bool MessageConversation::isMatchingAttribute(const std::string& attribute_name, - const FilterMatchFlag match_flag, - AnyPtr match_value) const -{ - LoggerD("Entered"); - auto key = match_value->toString(); - LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), - match_flag, key.c_str()); - - using namespace CONVERSATION_FILTER_ATTRIBUTE; - - if(ID == attribute_name) { - return FilterUtils::isStringMatching(key, std::to_string(getConversationId()), - match_flag); - } - else if(TYPE == attribute_name) { - return FilterUtils::isStringMatching(key, getTypeString(), match_flag); - } - else if(MESSAGE_COUNT == attribute_name) { - return FilterUtils::isStringMatching(key, std::to_string(getMessageCount()), - match_flag); - } - else if(UNREAD_MESSAGES == attribute_name) { - return FilterUtils::isStringMatching(key, std::to_string(getUnreadMessages()), - match_flag); - } - else if(PREVIEW == attribute_name) { - return FilterUtils::isStringMatching(key, getPreview(), match_flag); - } - else if(FROM == attribute_name) { - return FilterUtils::isStringMatching(key, getFrom(), match_flag); - } - else if(TO == attribute_name) { - return FilterUtils::isAnyStringMatching(key, getTo(), match_flag); - } - else { - LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); - } + const FilterMatchFlag match_flag, + AnyPtr match_value) const { + LoggerD("Entered"); + auto key = match_value->toString(); + LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), match_flag, + key.c_str()); + + using namespace CONVERSATION_FILTER_ATTRIBUTE; + + if (ID == attribute_name) { + return FilterUtils::isStringMatching(key, std::to_string(getConversationId()), match_flag); + } else if (TYPE == attribute_name) { + return FilterUtils::isStringMatching(key, getTypeString(), match_flag); + } else if (MESSAGE_COUNT == attribute_name) { + return FilterUtils::isStringMatching(key, std::to_string(getMessageCount()), match_flag); + } else if (UNREAD_MESSAGES == attribute_name) { + return FilterUtils::isStringMatching(key, std::to_string(getUnreadMessages()), match_flag); + } else if (PREVIEW == attribute_name) { + return FilterUtils::isStringMatching(key, getPreview(), match_flag); + } else if (FROM == attribute_name) { + return FilterUtils::isStringMatching(key, getFrom(), match_flag); + } else if (TO == attribute_name) { + return FilterUtils::isAnyStringMatching(key, getTo(), match_flag); + } else { + LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); + } - return false; + return false; } bool MessageConversation::isMatchingAttributeRange(const std::string& attribute_name, - AnyPtr initial_value, - AnyPtr end_value) const -{ - LoggerD("Entered attribute_name: %s", attribute_name.c_str()); + AnyPtr initial_value, AnyPtr end_value) const { + LoggerD("Entered attribute_name: %s", attribute_name.c_str()); - using namespace CONVERSATION_FILTER_ATTRIBUTE; + using namespace CONVERSATION_FILTER_ATTRIBUTE; - if(TIMESTAMP == attribute_name) { - return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, end_value); - } - else { - LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); - } - return false; + if (TIMESTAMP == attribute_name) { + return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, end_value); + } else { + LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); + } + return false; } std::string MessageConversation::SanitizeUtf8String(const std::string& input) { @@ -575,6 +498,5 @@ std::string MessageConversation::SanitizeUtf8String(const std::string& input) { return result; } -} //messaging -} //extension - +} // messaging +} // extension diff --git a/src/messaging/message_conversation.h b/src/messaging/message_conversation.h index 5a2dc42..1d01ff5 100644 --- a/src/messaging/message_conversation.h +++ b/src/messaging/message_conversation.h @@ -14,19 +14,18 @@ * limitations under the License. */ - #ifndef __TIZEN_MESSAGE_CONVERSATION_H__ #define __TIZEN_MESSAGE_CONVERSATION_H__ -#include -#include -#include -#include #include #include #include -#include "messaging_util.h" +#include +#include +#include +#include #include "MsgCommon/AbstractFilter.h" +#include "messaging_util.h" namespace extension { namespace messaging { @@ -34,7 +33,7 @@ namespace messaging { class MessageConversation; struct MessageConversationHolder { - std::shared_ptrptr; + std::shared_ptr ptr; }; typedef std::shared_ptr ConversationPtr; @@ -42,79 +41,78 @@ typedef std::shared_ptr ConversationPtr; typedef std::vector ConversationPtrVector; class MessageConversation : public tizen::FilterableObject { -public: - MessageConversation(); - ~MessageConversation(); - - // attributes getters - int getConversationId() const; - MessageType getType() const; - std::string getTypeString() const; - time_t getTimestamp() const; - unsigned long getMessageCount() const; - unsigned long getUnreadMessages() const; - std::string getPreview() const; - std::string getSubject() const; - bool getIsRead() const; - std::string getFrom() const; - std::vector getTo() const; - std::vector getCC() const; - std::vector getBCC() const; - int getLastMessageId() const; - - static common::PlatformResult convertEmailConversationToObject( - unsigned int threadId, std::shared_ptr* result); - /** - * - * @param threadId Id of Message (not Conversation) - * @param handle - * @return - */ - static common::PlatformResult convertMsgConversationToObject( - unsigned int threadId, msg_handle_t handle, std::shared_ptr* result); - - virtual void setConversationId(int id); - virtual void setType(MessageType type); - virtual void setTimestamp(time_t timestamp); - virtual void setMessageCount(int count); - virtual void setUnreadMessages(int unread_messages); - virtual void setPreview(std::string preview); - virtual void setSubject(std::string conversation_subject); - virtual void setIsRead(bool is_read); - virtual void setFrom(std::string from); - virtual void setTo(std::vector &to); - virtual void setCC(std::vector &cc); - virtual void setBCC(std::vector &bcc); - virtual void setLastMessageId(int last_message_id); - - // tizen::FilterableObject - virtual bool isMatchingAttribute(const std::string& attribute_name, - const tizen::FilterMatchFlag match_flag, - tizen::AnyPtr match_value) const; - - virtual bool isMatchingAttributeRange(const std::string& attribute_name, - tizen::AnyPtr initial_value, - tizen::AnyPtr end_value) const; - -private: - std::string SanitizeUtf8String(const std::string& input); - - int m_conversation_id; - MessageType m_conversation_type; - time_t m_timestamp; - unsigned long m_count; - unsigned long m_unread_messages; - std::string m_preview; - std::string m_conversation_subject; - bool m_is_read; - std::string m_from; - std::vector m_to; - std::vector m_cc; - std::vector m_bcc; - int m_last_message_id; + public: + MessageConversation(); + ~MessageConversation(); + + // attributes getters + int getConversationId() const; + MessageType getType() const; + std::string getTypeString() const; + time_t getTimestamp() const; + unsigned long getMessageCount() const; + unsigned long getUnreadMessages() const; + std::string getPreview() const; + std::string getSubject() const; + bool getIsRead() const; + std::string getFrom() const; + std::vector getTo() const; + std::vector getCC() const; + std::vector getBCC() const; + int getLastMessageId() const; + + static common::PlatformResult convertEmailConversationToObject( + unsigned int threadId, std::shared_ptr* result); + /** + * + * @param threadId Id of Message (not Conversation) + * @param handle + * @return + */ + static common::PlatformResult convertMsgConversationToObject( + unsigned int threadId, msg_handle_t handle, std::shared_ptr* result); + + virtual void setConversationId(int id); + virtual void setType(MessageType type); + virtual void setTimestamp(time_t timestamp); + virtual void setMessageCount(int count); + virtual void setUnreadMessages(int unread_messages); + virtual void setPreview(std::string preview); + virtual void setSubject(std::string conversation_subject); + virtual void setIsRead(bool is_read); + virtual void setFrom(std::string from); + virtual void setTo(std::vector& to); + virtual void setCC(std::vector& cc); + virtual void setBCC(std::vector& bcc); + virtual void setLastMessageId(int last_message_id); + + // tizen::FilterableObject + virtual bool isMatchingAttribute(const std::string& attribute_name, + const tizen::FilterMatchFlag match_flag, + tizen::AnyPtr match_value) const; + + virtual bool isMatchingAttributeRange(const std::string& attribute_name, + tizen::AnyPtr initial_value, tizen::AnyPtr end_value) const; + + private: + std::string SanitizeUtf8String(const std::string& input); + + int m_conversation_id; + MessageType m_conversation_type; + time_t m_timestamp; + unsigned long m_count; + unsigned long m_unread_messages; + std::string m_preview; + std::string m_conversation_subject; + bool m_is_read; + std::string m_from; + std::vector m_to; + std::vector m_cc; + std::vector m_bcc; + int m_last_message_id; }; -} //messaging -} //extension +} // messaging +} // extension -#endif // __TIZEN_MESSAGE_CONVERSATION_H__ +#endif // __TIZEN_MESSAGE_CONVERSATION_H__ diff --git a/src/messaging/message_email.cc b/src/messaging/message_email.cc old mode 100755 new mode 100644 index bd0f06c..d2ee2bf --- a/src/messaging/message_email.cc +++ b/src/messaging/message_email.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_email.h" #include "common/logger.h" @@ -24,16 +24,13 @@ namespace messaging { using namespace common; -MessageEmail::MessageEmail(): - Message() -{ - LoggerD("MessageEmail constructor."); - this->m_type = MessageType(EMAIL); +MessageEmail::MessageEmail() : Message() { + LoggerD("MessageEmail constructor."); + this->m_type = MessageType(EMAIL); } -MessageEmail::~MessageEmail() -{ - LoggerD("MessageEmail destructor."); +MessageEmail::~MessageEmail() { + LoggerD("MessageEmail destructor."); } // *** overridden methods @@ -44,134 +41,126 @@ int MessageEmail::getFolderIdForUser() const { return m_folder_id; } -void MessageEmail::setCC(std::vector &cc) -{ - LoggerD("Entered"); - // CC recipient's format validation should be done by email service - m_cc = cc; +void MessageEmail::setCC(std::vector &cc) { + LoggerD("Entered"); + // CC recipient's format validation should be done by email service + m_cc = cc; - if(m_cc.empty()) { - LoggerD("Recipient's list cleared"); - return; - } + if (m_cc.empty()) { + LoggerD("Recipient's list cleared"); + return; + } } -void MessageEmail::setBCC(std::vector &bcc) -{ - LoggerD("Entered"); - // BCC recipient's format validation should be done by email service - m_bcc = bcc; +void MessageEmail::setBCC(std::vector &bcc) { + LoggerD("Entered"); + // BCC recipient's format validation should be done by email service + m_bcc = bcc; - if(m_bcc.empty()) { - LoggerD("Recipient's list cleared"); - return; - } + if (m_bcc.empty()) { + LoggerD("Recipient's list cleared"); + return; + } } -void MessageEmail::setSubject(std::string subject) -{ - LoggerD("Entered"); - m_subject = subject; +void MessageEmail::setSubject(std::string subject) { + LoggerD("Entered"); + m_subject = subject; } -void MessageEmail::setIsHighPriority(bool highpriority) -{ - LoggerD("Entered"); - m_high_priority = highpriority; +void MessageEmail::setIsHighPriority(bool highpriority) { + LoggerD("Entered"); + m_high_priority = highpriority; } -void MessageEmail::setMessageAttachments(AttachmentPtrVector &attachments) -{ - LoggerD("Entered"); - m_attachments = attachments; +void MessageEmail::setMessageAttachments(AttachmentPtrVector &attachments) { + LoggerD("Entered"); + m_attachments = attachments; - m_has_attachment = true; - if(m_attachments.empty()) { - LoggerD("Recipient's list cleared"); - m_has_attachment = false; - } + m_has_attachment = true; + if (m_attachments.empty()) { + LoggerD("Recipient's list cleared"); + m_has_attachment = false; + } } -bool MessageEmail::getHasAttachment() const -{ - LoggerD("MessageEmail::getHasAttachment()"); - return m_has_attachment || !m_body->getInlineAttachments().empty(); +bool MessageEmail::getHasAttachment() const { + LoggerD("MessageEmail::getHasAttachment()"); + return m_has_attachment || !m_body->getInlineAttachments().empty(); } -PlatformResult MessageEmail::updateEmailMessage(email_mail_data_t& mail) -{ - LoggerD("Entered"); - - std::vector recp_list; - setId(mail.mail_id); - setFolderId(mail.mailbox_id); - setConversationId(mail.thread_id); - if(mail.full_address_from) { - setFrom(MessagingUtil::extractSingleEmailAddress(mail.full_address_from)); - } - - if(mail.full_address_to) { - recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_to); - setTO(recp_list); - } - - if(mail.full_address_cc) { - recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_cc); - setCC(recp_list); - } - - if(mail.full_address_bcc) { - recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_bcc); - setBCC(recp_list); - } - - setTimeStamp(mail.date_time); - setIsRead(mail.flags_seen_field); - setIsHighPriority((EMAIL_MAIL_PRIORITY_HIGH == mail.priority) ? true : false); - - if (mail.subject == NULL) { - LoggerW("Subject is null"); - } else { - LoggerD("Subject: %s", mail.subject); - setSubject(mail.subject); - } - - PlatformResult ret = getBody()->updateBody(mail); - if (ret.IsError()) { - LoggerE("Update Email body failed"); - return ret; - } - - if (mail.mail_id != mail.thread_id) { - setInResponseTo(mail.thread_id); - } - - switch(mail.save_status) - { - case EMAIL_MAIL_STATUS_SENT: - setMessageStatus(MessageStatus::STATUS_SENT); - break; - case EMAIL_MAIL_STATUS_SENDING: - setMessageStatus(MessageStatus::STATUS_SENDING); - break; - case EMAIL_MAIL_STATUS_SAVED: - setMessageStatus(MessageStatus::STATUS_DRAFT); - break; - case EMAIL_MAIL_STATUS_SEND_FAILURE: - setMessageStatus(MessageStatus::STATUS_FAILED); - break; - default: - setMessageStatus(MessageStatus::STATUS_UNDEFINED); - break; - } - - AttachmentPtrVector att; - ret = convertEmailToMessageAttachment(mail, &att); - if (ret.IsError()) return ret; - - setMessageAttachments(att); - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult MessageEmail::updateEmailMessage(email_mail_data_t &mail) { + LoggerD("Entered"); + + std::vector recp_list; + setId(mail.mail_id); + setFolderId(mail.mailbox_id); + setConversationId(mail.thread_id); + if (mail.full_address_from) { + setFrom(MessagingUtil::extractSingleEmailAddress(mail.full_address_from)); + } + + if (mail.full_address_to) { + recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_to); + setTO(recp_list); + } + + if (mail.full_address_cc) { + recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_cc); + setCC(recp_list); + } + + if (mail.full_address_bcc) { + recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_bcc); + setBCC(recp_list); + } + + setTimeStamp(mail.date_time); + setIsRead(mail.flags_seen_field); + setIsHighPriority((EMAIL_MAIL_PRIORITY_HIGH == mail.priority) ? true : false); + + if (mail.subject == NULL) { + LoggerW("Subject is null"); + } else { + LoggerD("Subject: %s", mail.subject); + setSubject(mail.subject); + } + + PlatformResult ret = getBody()->updateBody(mail); + if (ret.IsError()) { + LoggerE("Update Email body failed"); + return ret; + } + + if (mail.mail_id != mail.thread_id) { + setInResponseTo(mail.thread_id); + } + + switch (mail.save_status) { + case EMAIL_MAIL_STATUS_SENT: + setMessageStatus(MessageStatus::STATUS_SENT); + break; + case EMAIL_MAIL_STATUS_SENDING: + setMessageStatus(MessageStatus::STATUS_SENDING); + break; + case EMAIL_MAIL_STATUS_SAVED: + setMessageStatus(MessageStatus::STATUS_DRAFT); + break; + case EMAIL_MAIL_STATUS_SEND_FAILURE: + setMessageStatus(MessageStatus::STATUS_FAILED); + break; + default: + setMessageStatus(MessageStatus::STATUS_UNDEFINED); + break; + } + + AttachmentPtrVector att; + ret = convertEmailToMessageAttachment(mail, &att); + if (ret.IsError()) return ret; + + setMessageAttachments(att); + return PlatformResult(ErrorCode::NO_ERROR); } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_email.h b/src/messaging/message_email.h index 092834f..a99e224 100644 --- a/src/messaging/message_email.h +++ b/src/messaging/message_email.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_EMAIL_H_ #define MESSAGING_MESSAGE_EMAIL_H_ @@ -22,35 +22,35 @@ namespace extension { namespace messaging { -class MessageEmail: public Message { -public: -// constructor - MessageEmail(); - ~MessageEmail(); +class MessageEmail : public Message { + public: + // constructor + MessageEmail(); + ~MessageEmail(); -//overrided base class functions - virtual int getFolderIdForUser() const override; + // overrided base class functions + virtual int getFolderIdForUser() const override; - void setCC(std::vector &cc); - void setBCC(std::vector &bcc); - void setSubject(std::string subject); - void setIsHighPriority(bool highpriority); + void setCC(std::vector &cc); + void setBCC(std::vector &bcc); + void setSubject(std::string subject); + void setIsHighPriority(bool highpriority); - void setMessageAttachments(AttachmentPtrVector &attachments); + void setMessageAttachments(AttachmentPtrVector &attachments); - bool getHasAttachment() const; - /** - * Updates message with data from email_mail_data_t structure. - * @param mail - */ - virtual common::PlatformResult updateEmailMessage(email_mail_data_t& mail); + bool getHasAttachment() const; + /** + * Updates message with data from email_mail_data_t structure. + * @param mail + */ + virtual common::PlatformResult updateEmailMessage(email_mail_data_t &mail); -private: - // function that verifies recipient's list validity - bool isValidRecpientsVector(std::vector &recipients); + private: + // function that verifies recipient's list validity + bool isValidRecpientsVector(std::vector &recipients); }; -} // messaging -} // extension +} // messaging +} // extension -#endif // MESSAGING_MESSAGE_EMAIL_H_ +#endif // MESSAGING_MESSAGE_EMAIL_H_ diff --git a/src/messaging/message_folder.cc b/src/messaging/message_folder.cc old mode 100755 new mode 100644 index 355675e..87c166d --- a/src/messaging/message_folder.cc +++ b/src/messaging/message_folder.cc @@ -14,133 +14,110 @@ * limitations under the License. */ -#include "messaging_util.h" #include "message_folder.h" +#include "messaging_util.h" namespace extension { namespace messaging { using namespace tizen; -MessageFolder::MessageFolder( - std::string id, - std::string parent_id, - std::string service_id, - std::string content_type, - std::string name, - std::string path, - MessageFolderType type, - bool synchronizable): - m_id(id), - m_parent_id(parent_id), - m_parent_id_set(true), - m_service_id(service_id), - m_content_type(content_type), - m_name(name), - m_path(path), - m_type(type), - m_synchronizable(synchronizable) -{ - LoggerD("Entered"); +MessageFolder::MessageFolder(std::string id, std::string parent_id, std::string service_id, + std::string content_type, std::string name, std::string path, + MessageFolderType type, bool synchronizable) + : m_id(id), + m_parent_id(parent_id), + m_parent_id_set(true), + m_service_id(service_id), + m_content_type(content_type), + m_name(name), + m_path(path), + m_type(type), + m_synchronizable(synchronizable) { + LoggerD("Entered"); } -MessageFolder::MessageFolder(email_mailbox_t mailbox) -{ - LoggerD("Entered"); - m_id = std::to_string(mailbox.mailbox_id); - m_parent_id_set = false; - m_service_id = std::to_string(mailbox.account_id); - m_content_type = MessagingUtil::messageTypeToString(EMAIL); - m_name = mailbox.alias; - m_path = mailbox.mailbox_name; - m_type = convertPlatformFolderType(mailbox.mailbox_type); - if (0 == mailbox.local) { - m_synchronizable = true; - } - else { - m_synchronizable = false; - } +MessageFolder::MessageFolder(email_mailbox_t mailbox) { + LoggerD("Entered"); + m_id = std::to_string(mailbox.mailbox_id); + m_parent_id_set = false; + m_service_id = std::to_string(mailbox.account_id); + m_content_type = MessagingUtil::messageTypeToString(EMAIL); + m_name = mailbox.alias; + m_path = mailbox.mailbox_name; + m_type = convertPlatformFolderType(mailbox.mailbox_type); + if (0 == mailbox.local) { + m_synchronizable = true; + } else { + m_synchronizable = false; + } } -std::string MessageFolder::getId() const -{ - return m_id; +std::string MessageFolder::getId() const { + return m_id; } -std::string MessageFolder::getParentId() const -{ - return m_parent_id; +std::string MessageFolder::getParentId() const { + return m_parent_id; } -bool MessageFolder::isParentIdSet() const -{ - return m_parent_id_set; +bool MessageFolder::isParentIdSet() const { + return m_parent_id_set; } -void MessageFolder::setParentId(const std::string& parentId) -{ - m_parent_id = parentId; - m_parent_id_set = true; +void MessageFolder::setParentId(const std::string& parentId) { + m_parent_id = parentId; + m_parent_id_set = true; } -std::string MessageFolder::getServiceId() const -{ - return m_service_id; +std::string MessageFolder::getServiceId() const { + return m_service_id; } -std::string MessageFolder::getContentType() const -{ - return m_content_type; +std::string MessageFolder::getContentType() const { + return m_content_type; } -std::string MessageFolder::getName() const -{ - return m_name; +std::string MessageFolder::getName() const { + return m_name; } -std::string MessageFolder::getPath() const -{ - return m_path; +std::string MessageFolder::getPath() const { + return m_path; } -MessageFolderType MessageFolder::getType() const -{ - return m_type; +MessageFolderType MessageFolder::getType() const { + return m_type; } -bool MessageFolder::getSynchronizable() const -{ - return m_synchronizable; +bool MessageFolder::getSynchronizable() const { + return m_synchronizable; } -void MessageFolder::setName(const std::string &value) -{ - m_name = value; +void MessageFolder::setName(const std::string& value) { + m_name = value; } -void MessageFolder::setSynchronizable(const bool &value) -{ - m_synchronizable = value; +void MessageFolder::setSynchronizable(const bool& value) { + m_synchronizable = value; } -MessageFolderType MessageFolder::convertPlatformFolderType( - email_mailbox_type_e folderType) -{ - LoggerD("Entered"); - switch (folderType) { - case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_INBOX: - return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; - case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_SENTBOX: - return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX; - case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_DRAFT: - return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS; - case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_OUTBOX: - return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX; - case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_ALL_EMAILS: - return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; - default: - return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; - } +MessageFolderType MessageFolder::convertPlatformFolderType(email_mailbox_type_e folderType) { + LoggerD("Entered"); + switch (folderType) { + case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_INBOX: + return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; + case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_SENTBOX: + return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX; + case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_DRAFT: + return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS; + case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_OUTBOX: + return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX; + case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_ALL_EMAILS: + return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; + default: + return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; + } } /** @@ -160,38 +137,33 @@ MessageFolderType MessageFolder::convertPlatformFolderType( namespace FOLDER_FILTER_ATTRIBUTE { const std::string SERVICE_ID = "serviceId"; -} //namespace FOLDER_FILTER_ATTRIBUTE +} // namespace FOLDER_FILTER_ATTRIBUTE bool MessageFolder::isMatchingAttribute(const std::string& attribute_name, - const FilterMatchFlag match_flag, - AnyPtr match_value) const -{ - LoggerD("Entered"); - auto key = match_value->toString(); - LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), - match_flag, key.c_str()); + const FilterMatchFlag match_flag, + AnyPtr match_value) const { + LoggerD("Entered"); + auto key = match_value->toString(); + LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), match_flag, + key.c_str()); - using namespace FOLDER_FILTER_ATTRIBUTE; + using namespace FOLDER_FILTER_ATTRIBUTE; - if (SERVICE_ID == attribute_name) { - return FilterUtils::isStringMatching(key, getServiceId() , match_flag); - } - else { - LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); - } + if (SERVICE_ID == attribute_name) { + return FilterUtils::isStringMatching(key, getServiceId(), match_flag); + } else { + LoggerD("attribute:%s is NOT SUPPORTED", attribute_name.c_str()); + } - return false; + return false; } - bool MessageFolder::isMatchingAttributeRange(const std::string& attribute_name, - AnyPtr initial_value, - AnyPtr end_value) const -{ - LoggerD("Entered"); - LoggerD("attribute_name: %s NOT SUPPORTED", attribute_name.c_str()); - return false; + AnyPtr initial_value, AnyPtr end_value) const { + LoggerD("Entered"); + LoggerD("attribute_name: %s NOT SUPPORTED", attribute_name.c_str()); + return false; } -} //messaging -} //extension +} // messaging +} // extension diff --git a/src/messaging/message_folder.h b/src/messaging/message_folder.h old mode 100755 new mode 100644 index 70317ad..c8f0646 --- a/src/messaging/message_folder.h +++ b/src/messaging/message_folder.h @@ -17,8 +17,8 @@ #ifndef __TIZEN_MESSAGING_MESSAGE_FOLDER_H__ #define __TIZEN_MESSAGING_MESSAGE_FOLDER_H__ -#include #include +#include #include #include @@ -28,74 +28,66 @@ namespace extension { namespace messaging { enum MessageFolderType { - MESSAGE_FOLDER_TYPE_INBOX, - MESSAGE_FOLDER_TYPE_OUTBOX, - MESSAGE_FOLDER_TYPE_DRAFTS, - MESSAGE_FOLDER_TYPE_SENTBOX, - MESSAGE_FOLDER_TYPE_NOTSTANDARD + MESSAGE_FOLDER_TYPE_INBOX, + MESSAGE_FOLDER_TYPE_OUTBOX, + MESSAGE_FOLDER_TYPE_DRAFTS, + MESSAGE_FOLDER_TYPE_SENTBOX, + MESSAGE_FOLDER_TYPE_NOTSTANDARD }; class MessageFolder; struct MessageFolderHolder { - std::shared_ptr ptr; + std::shared_ptr ptr; }; typedef std::shared_ptr FolderPtr; typedef std::vector FolderPtrVector; -class MessageFolder : public tizen::FilterableObject{ - -public: - MessageFolder( - std::string id, - std::string parent_id, - std::string service_id, - std::string content_type, - std::string name, - std::string path, - MessageFolderType type, - bool synchronizable); - MessageFolder(email_mailbox_t mailbox); - - std::string getId() const; - std::string getParentId() const; - bool isParentIdSet() const; - void setParentId(const std::string& parentId); - std::string getServiceId() const; - std::string getContentType() const; - std::string getName() const; - void setName(const std::string &value); - std::string getPath() const; - MessageFolderType getType() const; - bool getSynchronizable() const; - void setSynchronizable(const bool &value); - - // tizen::FilterableObject - virtual bool isMatchingAttribute(const std::string& attribute_name, - const tizen::FilterMatchFlag match_flag, - tizen::AnyPtr match_value) const; - - virtual bool isMatchingAttributeRange(const std::string& attribute_name, - tizen::AnyPtr initial_value, - tizen::AnyPtr end_value) const; -private: - MessageFolderType convertPlatformFolderType( - email_mailbox_type_e folderType); - - std::string m_id; - std::string m_parent_id; - bool m_parent_id_set; - std::string m_service_id; - std::string m_content_type; - std::string m_name; - std::string m_path; - MessageFolderType m_type; - bool m_synchronizable; +class MessageFolder : public tizen::FilterableObject { + public: + MessageFolder(std::string id, std::string parent_id, std::string service_id, + std::string content_type, std::string name, std::string path, + MessageFolderType type, bool synchronizable); + MessageFolder(email_mailbox_t mailbox); + + std::string getId() const; + std::string getParentId() const; + bool isParentIdSet() const; + void setParentId(const std::string& parentId); + std::string getServiceId() const; + std::string getContentType() const; + std::string getName() const; + void setName(const std::string& value); + std::string getPath() const; + MessageFolderType getType() const; + bool getSynchronizable() const; + void setSynchronizable(const bool& value); + + // tizen::FilterableObject + virtual bool isMatchingAttribute(const std::string& attribute_name, + const tizen::FilterMatchFlag match_flag, + tizen::AnyPtr match_value) const; + + virtual bool isMatchingAttributeRange(const std::string& attribute_name, + tizen::AnyPtr initial_value, tizen::AnyPtr end_value) const; + + private: + MessageFolderType convertPlatformFolderType(email_mailbox_type_e folderType); + + std::string m_id; + std::string m_parent_id; + bool m_parent_id_set; + std::string m_service_id; + std::string m_content_type; + std::string m_name; + std::string m_path; + MessageFolderType m_type; + bool m_synchronizable; }; -} //messaging -} //extension +} // messaging +} // extension -#endif // __TIZEN_MESSAGING_MESSAGE_FOLDER_H__ +#endif // __TIZEN_MESSAGING_MESSAGE_FOLDER_H__ diff --git a/src/messaging/message_mms.cc b/src/messaging/message_mms.cc old mode 100755 new mode 100644 index 8e621bb..8ef1cc3 --- a/src/messaging/message_mms.cc +++ b/src/messaging/message_mms.cc @@ -13,74 +13,66 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_mms.h" -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" namespace extension { namespace messaging { -MessageMMS::MessageMMS(): - Message() -{ - LoggerD("MessageMMS constructor."); - this->m_type = MessageType(MessageType(MMS)); +MessageMMS::MessageMMS() : Message() { + LoggerD("MessageMMS constructor."); + this->m_type = MessageType(MessageType(MMS)); } -MessageMMS::~MessageMMS() -{ - LoggerD("MessageMMS destructor."); +MessageMMS::~MessageMMS() { + LoggerD("MessageMMS destructor."); } // *** overrided methods -void MessageMMS::setCC(std::vector &cc) -{ - LoggerD("Entered"); - // CC recipient's format validation should be done by email service - m_cc = cc; +void MessageMMS::setCC(std::vector &cc) { + LoggerD("Entered"); + // CC recipient's format validation should be done by email service + m_cc = cc; - if(m_cc.empty()) { - LoggerD("Recipient's list cleared"); - return; - } + if (m_cc.empty()) { + LoggerD("Recipient's list cleared"); + return; + } } -void MessageMMS::setBCC(std::vector &bcc) -{ - LoggerD("Entered"); - // BCC recipient's format validation should be done by email service - m_bcc = bcc; +void MessageMMS::setBCC(std::vector &bcc) { + LoggerD("Entered"); + // BCC recipient's format validation should be done by email service + m_bcc = bcc; - if(m_bcc.empty()) { - LoggerD("Recipient's list cleared"); - return; - } + if (m_bcc.empty()) { + LoggerD("Recipient's list cleared"); + return; + } } -void MessageMMS::setSubject(std::string subject) -{ - m_subject = subject; +void MessageMMS::setSubject(std::string subject) { + m_subject = subject; } -void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments) -{ - LoggerD("Entered"); - m_attachments = attachments; +void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments) { + LoggerD("Entered"); + m_attachments = attachments; - m_has_attachment = true; - if(m_attachments.empty()) { - LoggerD("Recipient's list cleared"); - m_has_attachment = false; - } + m_has_attachment = true; + if (m_attachments.empty()) { + LoggerD("Recipient's list cleared"); + m_has_attachment = false; + } } -bool MessageMMS::getHasAttachment() const -{ - LoggerD("MessageMMS::getHasAttachment()"); - return m_has_attachment; +bool MessageMMS::getHasAttachment() const { + LoggerD("MessageMMS::getHasAttachment()"); + return m_has_attachment; } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_mms.h b/src/messaging/message_mms.h index cb25250..4bca8c7 100644 --- a/src/messaging/message_mms.h +++ b/src/messaging/message_mms.h @@ -26,22 +26,22 @@ namespace extension { namespace messaging { -class MessageMMS: public Message { -public: -// constructor - MessageMMS(); - ~MessageMMS(); - -//overrided base class functions - void setCC(std::vector &cc); - void setBCC(std::vector &bcc); - void setSubject(std::string subject); - void setMessageAttachments(AttachmentPtrVector &attachments); - - bool getHasAttachment() const; +class MessageMMS : public Message { + public: + // constructor + MessageMMS(); + ~MessageMMS(); + + // overrided base class functions + void setCC(std::vector &cc); + void setBCC(std::vector &bcc); + void setSubject(std::string subject); + void setMessageAttachments(AttachmentPtrVector &attachments); + + bool getHasAttachment() const; }; -} // messaging -} // extension +} // messaging +} // extension -#endif // __TIZEN_MESSAGE_MMS_H__ +#endif // __TIZEN_MESSAGE_MMS_H__ diff --git a/src/messaging/message_service.cc b/src/messaging/message_service.cc old mode 100755 new mode 100644 index cc3a8af..6472985 --- a/src/messaging/message_service.cc +++ b/src/messaging/message_service.cc @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_service.h" #include +#include "common/assert.h" #include "common/logger.h" #include "common/platform_exception.h" -#include "common/assert.h" -#include "messaging_util.h" +#include "message.h" #include "message_storage_email.h" #include "message_storage_short_msg.h" -#include "message.h" +#include "messaging_util.h" using common::ErrorCode; using common::PlatformResult; @@ -33,7 +33,7 @@ using common::PlatformResult; namespace extension { namespace messaging { -namespace{ +namespace { const char* JSON_SERVICE_ID = "id"; const char* JSON_SERVICE_TYPE = "type"; const char* JSON_SERVICE_NAME = "name"; @@ -41,360 +41,300 @@ const char* JSON_SERVICE_NAME = "name"; //#################### MessageRecipientsCallbackData #################### -MessageRecipientsCallbackData::MessageRecipientsCallbackData(PostQueue& queue, long cid) : - CallbackUserData(queue, cid), - m_account_id(-1), - m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN), - m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { +MessageRecipientsCallbackData::MessageRecipientsCallbackData(PostQueue& queue, long cid) + : CallbackUserData(queue, cid), + m_account_id(-1), + m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN), + m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { LoggerD("Entered"); } -MessageRecipientsCallbackData::~MessageRecipientsCallbackData() -{ - LoggerD("Entered"); +MessageRecipientsCallbackData::~MessageRecipientsCallbackData() { + LoggerD("Entered"); } -void MessageRecipientsCallbackData::setMessage(std::shared_ptr message) -{ - m_message = message; +void MessageRecipientsCallbackData::setMessage(std::shared_ptr message) { + m_message = message; } -std::shared_ptr MessageRecipientsCallbackData::getMessage() const -{ - return m_message; +std::shared_ptr MessageRecipientsCallbackData::getMessage() const { + return m_message; } void MessageRecipientsCallbackData::setMessageRecipients( - const std::vector& msgRecipients) -{ - m_msg_recipients = msgRecipients; + const std::vector& msgRecipients) { + m_msg_recipients = msgRecipients; } -const std::vector& MessageRecipientsCallbackData::getMessageRecipients() const -{ - return m_msg_recipients; +const std::vector& MessageRecipientsCallbackData::getMessageRecipients() const { + return m_msg_recipients; } -void MessageRecipientsCallbackData::setAccountId(int account_id){ - m_account_id = account_id; +void MessageRecipientsCallbackData::setAccountId(int account_id) { + m_account_id = account_id; } -int MessageRecipientsCallbackData::getAccountId() const -{ - return m_account_id; +int MessageRecipientsCallbackData::getAccountId() const { + return m_account_id; } -bool MessageRecipientsCallbackData::setSimIndex( - int sim_index) -{ - LoggerD("Entered"); - char **cp_list = tel_get_cp_name_list(); - int sim_count = 0; - if (cp_list) { - while (cp_list[sim_count]) { - sim_count++; - } - g_strfreev(cp_list); - } else { - LoggerD("Empty cp name list"); +bool MessageRecipientsCallbackData::setSimIndex(int sim_index) { + LoggerD("Entered"); + char** cp_list = tel_get_cp_name_list(); + int sim_count = 0; + if (cp_list) { + while (cp_list[sim_count]) { + sim_count++; } + g_strfreev(cp_list); + } else { + LoggerD("Empty cp name list"); + } - sim_index--; - if (sim_index >= sim_count || sim_index < -1) { - this->SetError(LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "The index of sim is out of bound", - ("Sim index out of bound %d : %d", sim_index, sim_count))); - return false; - } + sim_index--; + if (sim_index >= sim_count || sim_index < -1) { + this->SetError(LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "The index of sim is out of bound", + ("Sim index out of bound %d : %d", sim_index, sim_count))); + return false; + } - m_sim_index = static_cast(sim_index); + m_sim_index = static_cast(sim_index); - return true; + return true; } -TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getSimIndex() const -{ - return m_sim_index; +TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getSimIndex() const { + return m_sim_index; } -bool MessageRecipientsCallbackData::isSetSimIndex() const -{ - return m_sim_index != TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN; +bool MessageRecipientsCallbackData::isSetSimIndex() const { + return m_sim_index != TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN; } -void MessageRecipientsCallbackData::setDefaultSimIndex( - TelNetworkDefaultDataSubs_t sim_index) -{ - m_default_sim_index = sim_index; +void MessageRecipientsCallbackData::setDefaultSimIndex(TelNetworkDefaultDataSubs_t sim_index) { + m_default_sim_index = sim_index; } -TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() const -{ - return m_default_sim_index; +TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() const { + return m_default_sim_index; } //#################### BaseMessageServiceCallbackData #################### -BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(PostQueue& queue, long cid) : - CallbackUserData(queue, cid), - m_op_handle(-1) { +BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(PostQueue& queue, long cid) + : CallbackUserData(queue, cid), m_op_handle(-1) { LoggerD("Entered"); } -BaseMessageServiceCallbackData::~BaseMessageServiceCallbackData() -{ - LoggerD("Entered"); +BaseMessageServiceCallbackData::~BaseMessageServiceCallbackData() { + LoggerD("Entered"); } -void BaseMessageServiceCallbackData::setOperationHandle(const int op_handle) -{ - m_op_handle = op_handle; +void BaseMessageServiceCallbackData::setOperationHandle(const int op_handle) { + m_op_handle = op_handle; } -int BaseMessageServiceCallbackData::getOperationHandle() const -{ - return m_op_handle; +int BaseMessageServiceCallbackData::getOperationHandle() const { + return m_op_handle; } //#################### MessageBodyCallbackData #################### -MessageBodyCallbackData::~MessageBodyCallbackData() -{ - LoggerD("Entered"); +MessageBodyCallbackData::~MessageBodyCallbackData() { + LoggerD("Entered"); } -void MessageBodyCallbackData::setMessage(std::shared_ptr message) -{ - m_message = message; +void MessageBodyCallbackData::setMessage(std::shared_ptr message) { + m_message = message; } -std::shared_ptr MessageBodyCallbackData::getMessage() const -{ - return m_message; +std::shared_ptr MessageBodyCallbackData::getMessage() const { + return m_message; } //#################### MessageAttachmentCallbackData #################### -MessageAttachmentCallbackData::MessageAttachmentCallbackData(PostQueue& queue, long cid) : - BaseMessageServiceCallbackData(queue, cid), - m_nth(0) { +MessageAttachmentCallbackData::MessageAttachmentCallbackData(PostQueue& queue, long cid) + : BaseMessageServiceCallbackData(queue, cid), m_nth(0) { LoggerD("Entered"); } -MessageAttachmentCallbackData::~MessageAttachmentCallbackData() -{ - LoggerD("Entered"); +MessageAttachmentCallbackData::~MessageAttachmentCallbackData() { + LoggerD("Entered"); } void MessageAttachmentCallbackData::setMessageAttachment( - std::shared_ptr messageAttachment) -{ - m_message_attachment = messageAttachment; + std::shared_ptr messageAttachment) { + m_message_attachment = messageAttachment; } -std::shared_ptr MessageAttachmentCallbackData:: - getMessageAttachment() const -{ - return m_message_attachment; +std::shared_ptr MessageAttachmentCallbackData::getMessageAttachment() const { + return m_message_attachment; } -void MessageAttachmentCallbackData::setNth(const int nth) -{ - m_nth = nth; +void MessageAttachmentCallbackData::setNth(const int nth) { + m_nth = nth; } -int MessageAttachmentCallbackData::getNth() const -{ - return m_nth; +int MessageAttachmentCallbackData::getNth() const { + return m_nth; } //#################### SyncCallbackData #################### - -SyncCallbackData::SyncCallbackData(PostQueue& queue, long cid) : - BaseMessageServiceCallbackData(queue, cid), - m_is_limit(false), - m_limit(0), - m_op_id(-1), - m_account_id(-1) { +SyncCallbackData::SyncCallbackData(PostQueue& queue, long cid) + : BaseMessageServiceCallbackData(queue, cid), + m_is_limit(false), + m_limit(0), + m_op_id(-1), + m_account_id(-1) { LoggerD("Entered"); } -SyncCallbackData::~SyncCallbackData() -{ - LoggerD("Entered"); +SyncCallbackData::~SyncCallbackData() { + LoggerD("Entered"); } -void SyncCallbackData::setLimit(const unsigned long limit) -{ - m_is_limit = true; - m_limit = limit; +void SyncCallbackData::setLimit(const unsigned long limit) { + m_is_limit = true; + m_limit = limit; } -bool SyncCallbackData::isLimit() const -{ - return m_is_limit; +bool SyncCallbackData::isLimit() const { + return m_is_limit; } -unsigned long SyncCallbackData::getLimit() const -{ - return m_limit; +unsigned long SyncCallbackData::getLimit() const { + return m_limit; } -void SyncCallbackData::setOpId(long op_id) -{ - m_op_id = op_id; +void SyncCallbackData::setOpId(long op_id) { + m_op_id = op_id; } -long SyncCallbackData::getOpId() -{ - return m_op_id; +long SyncCallbackData::getOpId() { + return m_op_id; } -void SyncCallbackData::setAccountId(int account_id) -{ - m_account_id = account_id; +void SyncCallbackData::setAccountId(int account_id) { + m_account_id = account_id; } -int SyncCallbackData::getAccountId() const -{ - return m_account_id; +int SyncCallbackData::getAccountId() const { + return m_account_id; } //#################### SyncFolderCallbackData #################### -SyncFolderCallbackData::~SyncFolderCallbackData() -{ - LoggerD("Entered"); +SyncFolderCallbackData::~SyncFolderCallbackData() { + LoggerD("Entered"); } -void SyncFolderCallbackData::setMessageFolder( - std::shared_ptr message_folder) -{ - m_message_folder = message_folder; +void SyncFolderCallbackData::setMessageFolder(std::shared_ptr message_folder) { + m_message_folder = message_folder; } -std::shared_ptr SyncFolderCallbackData::getMessageFolder() const -{ - return m_message_folder; +std::shared_ptr SyncFolderCallbackData::getMessageFolder() const { + return m_message_folder; } //#################### MessageService #################### -MessageService::MessageService(int id, - MessageType msgType, - const std::string& name): - m_id(id), - m_msg_type(msgType), - m_name(name) -{ - LoggerD("Entered"); - switch (msgType) { - case MessageType::SMS: - case MessageType::MMS: - m_storage.reset(new MessageStorageShortMsg(id, msgType)); - break; - case MessageType::EMAIL: - m_storage.reset(new MessageStorageEmail(id)); - break; - default: - LoggerE("Undefined message type: %d", msgType); - Assert(false); - break; - } -} - -MessageService::~MessageService() -{ - LoggerD("Entered"); +MessageService::MessageService(int id, MessageType msgType, const std::string& name) + : m_id(id), m_msg_type(msgType), m_name(name) { + LoggerD("Entered"); + switch (msgType) { + case MessageType::SMS: + case MessageType::MMS: + m_storage.reset(new MessageStorageShortMsg(id, msgType)); + break; + case MessageType::EMAIL: + m_storage.reset(new MessageStorageEmail(id)); + break; + default: + LoggerE("Undefined message type: %d", msgType); + Assert(false); + break; + } +} + +MessageService::~MessageService() { + LoggerD("Entered"); } -picojson::object MessageService::toPicoJS() const -{ - LoggerD("Entered"); - picojson::object picojs = picojson::object(); - picojs[JSON_SERVICE_ID] = picojson::value(std::to_string(m_id)); - picojs[JSON_SERVICE_TYPE] = picojson::value(getMsgServiceTypeString()); - picojs[JSON_SERVICE_NAME] = picojson::value(m_name); - return picojs; +picojson::object MessageService::toPicoJS() const { + LoggerD("Entered"); + picojson::object picojs = picojson::object(); + picojs[JSON_SERVICE_ID] = picojson::value(std::to_string(m_id)); + picojs[JSON_SERVICE_TYPE] = picojson::value(getMsgServiceTypeString()); + picojs[JSON_SERVICE_NAME] = picojson::value(m_name); + return picojs; } -int MessageService::getMsgServiceId() const -{ - return m_id; +int MessageService::getMsgServiceId() const { + return m_id; } -std::string MessageService::getMsgServiceIdStr() const -{ - return std::to_string(m_id); +std::string MessageService::getMsgServiceIdStr() const { + return std::to_string(m_id); } -MessageType MessageService::getMsgServiceType() const -{ - return m_msg_type; +MessageType MessageService::getMsgServiceType() const { + return m_msg_type; } std::string MessageService::getMsgServiceTypeString() const { return MessagingUtil::messageTypeToString(getMsgServiceType()); } -std::string MessageService::getMsgServiceName() const -{ - return m_name; +std::string MessageService::getMsgServiceName() const { + return m_name; } -MessageStoragePtr MessageService::getMsgStorage() const -{ - return m_storage; +MessageStoragePtr MessageService::getMsgStorage() const { + return m_storage; } -common::PlatformResult MessageService::sendMessage(MessageRecipientsCallbackData *callback) -{ - // this method should be overwritten be specific services - delete callback; - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Unable to send message."); +common::PlatformResult MessageService::sendMessage(MessageRecipientsCallbackData* callback) { + // this method should be overwritten be specific services + delete callback; + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Unable to send message."); } -PlatformResult MessageService::loadMessageBody(MessageBodyCallbackData* callback) -{ - // this method should be overwritten by specific services - delete callback; - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot load message body"); +PlatformResult MessageService::loadMessageBody(MessageBodyCallbackData* callback) { + // this method should be overwritten by specific services + delete callback; + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot load message body"); } -PlatformResult MessageService::loadMessageAttachment(MessageAttachmentCallbackData* callback) -{ - // this method should be overwritten by email service - // for MMS and SMS this function is not supported - delete callback; - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot load message attachment"); +PlatformResult MessageService::loadMessageAttachment(MessageAttachmentCallbackData* callback) { + // this method should be overwritten by email service + // for MMS and SMS this function is not supported + delete callback; + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot load message attachment"); } -PlatformResult MessageService::sync(SyncCallbackData *callback, long* operation_id) -{ - // this method should be overwritten by email service - // for MMS and SMS this function is not supported - delete callback; - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot sync with external server"); +PlatformResult MessageService::sync(SyncCallbackData* callback, long* operation_id) { + // this method should be overwritten by email service + // for MMS and SMS this function is not supported + delete callback; + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot sync with external server"); } -PlatformResult MessageService::syncFolder(SyncFolderCallbackData *callback, long* operation_id) -{ - // this method should be overwritten by email service - // for MMS and SMS this function is not supported - delete callback; - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "Cannot sync folder with external server"); +PlatformResult MessageService::syncFolder(SyncFolderCallbackData* callback, long* operation_id) { + // this method should be overwritten by email service + // for MMS and SMS this function is not supported + delete callback; + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Cannot sync folder with external server"); } -PlatformResult MessageService::stopSync(long op_id) -{ - // this method should be overwritten by email service - // for MMS and SMS this function is not supported - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "Cannot stop sync with external server"); +PlatformResult MessageService::stopSync(long op_id) { + // this method should be overwritten by email service + // for MMS and SMS this function is not supported + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Cannot stop sync with external server"); } -} // messaging -} // extension - +} // messaging +} // extension diff --git a/src/messaging/message_service.h b/src/messaging/message_service.h index 5aab33e..e0e888e 100644 --- a/src/messaging/message_service.h +++ b/src/messaging/message_service.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_SERVICE_H_ #define MESSAGING_MESSAGE_SERVICE_H_ @@ -21,178 +21,170 @@ #include #include -#include "messaging/callback_user_data.h" #include "common/picojson.h" #include "common/platform_result.h" +#include "messaging/callback_user_data.h" -#include "messaging_util.h" -#include "message_storage.h" #include "message.h" +#include "message_storage.h" +#include "messaging_util.h" namespace extension { namespace messaging { -enum MessageServiceAccountId -{ - UNKNOWN_ACCOUNT_ID = 0, - SMS_ACCOUNT_ID = 101, - MMS_ACCOUNT_ID = 102 -}; +enum MessageServiceAccountId { UNKNOWN_ACCOUNT_ID = 0, SMS_ACCOUNT_ID = 101, MMS_ACCOUNT_ID = 102 }; class MessageRecipientsCallbackData : public CallbackUserData { -public: - MessageRecipientsCallbackData(PostQueue& queue, long cid); - virtual ~MessageRecipientsCallbackData(); - - void setMessage(std::shared_ptr message); - std::shared_ptr getMessage() const; - - void setMessageRecipients(const std::vector& msgRecipients); - const std::vector& getMessageRecipients() const; - - void setAccountId(int account_id); - int getAccountId() const; - - bool setSimIndex(int sim_index); - TelNetworkDefaultDataSubs_t getSimIndex() const; - void setDefaultSimIndex(TelNetworkDefaultDataSubs_t sim_index); - TelNetworkDefaultDataSubs_t getDefaultSimIndex() const; - bool isSetSimIndex() const; - -private: - std::shared_ptr m_message; - std::vector m_msg_recipients; - int m_account_id; - TelNetworkDefaultDataSubs_t m_sim_index; - TelNetworkDefaultDataSubs_t m_default_sim_index; + public: + MessageRecipientsCallbackData(PostQueue& queue, long cid); + virtual ~MessageRecipientsCallbackData(); + + void setMessage(std::shared_ptr message); + std::shared_ptr getMessage() const; + + void setMessageRecipients(const std::vector& msgRecipients); + const std::vector& getMessageRecipients() const; + + void setAccountId(int account_id); + int getAccountId() const; + + bool setSimIndex(int sim_index); + TelNetworkDefaultDataSubs_t getSimIndex() const; + void setDefaultSimIndex(TelNetworkDefaultDataSubs_t sim_index); + TelNetworkDefaultDataSubs_t getDefaultSimIndex() const; + bool isSetSimIndex() const; + + private: + std::shared_ptr m_message; + std::vector m_msg_recipients; + int m_account_id; + TelNetworkDefaultDataSubs_t m_sim_index; + TelNetworkDefaultDataSubs_t m_default_sim_index; }; class BaseMessageServiceCallbackData : public CallbackUserData { -public: - BaseMessageServiceCallbackData(PostQueue& queue, long cid); - virtual ~BaseMessageServiceCallbackData(); - - /** - * This handle is returned from various native API functions: - * int email_sync_header(..., int *handle); - * int email_download_body(..., int *handle); - * int email_download_attachment(..., int *handle); - * - * It is used to stop and identify request. - */ - void setOperationHandle(const int op_handle); - int getOperationHandle() const; - -protected: - int m_op_handle; + public: + BaseMessageServiceCallbackData(PostQueue& queue, long cid); + virtual ~BaseMessageServiceCallbackData(); + + /** + * This handle is returned from various native API functions: + * int email_sync_header(..., int *handle); + * int email_download_body(..., int *handle); + * int email_download_attachment(..., int *handle); + * + * It is used to stop and identify request. + */ + void setOperationHandle(const int op_handle); + int getOperationHandle() const; + + protected: + int m_op_handle; }; class MessageBodyCallbackData : public BaseMessageServiceCallbackData { -public: - using BaseMessageServiceCallbackData::BaseMessageServiceCallbackData; - virtual ~MessageBodyCallbackData(); + public: + using BaseMessageServiceCallbackData::BaseMessageServiceCallbackData; + virtual ~MessageBodyCallbackData(); - void setMessage(std::shared_ptr message); - std::shared_ptr getMessage() const; + void setMessage(std::shared_ptr message); + std::shared_ptr getMessage() const; -private: - std::shared_ptr m_message; + private: + std::shared_ptr m_message; }; class MessageAttachmentCallbackData : public BaseMessageServiceCallbackData { -public: - MessageAttachmentCallbackData(PostQueue& queue, long cid); - virtual ~MessageAttachmentCallbackData(); - - void setMessageAttachment(std::shared_ptr messageAttachment); - std::shared_ptr getMessageAttachment() const; - - /** - * nth is used in native api call: - * int email_download_attachment(int mail_id, int nth, int *handle); - * - * nth is equal to attachment index+1 (starts from 1 not 0) see - * email-api-network.h for details. - * */ - void setNth(const int nth); - int getNth() const; - -private: - std::shared_ptr m_message_attachment; - int m_nth; + public: + MessageAttachmentCallbackData(PostQueue& queue, long cid); + virtual ~MessageAttachmentCallbackData(); + + void setMessageAttachment(std::shared_ptr messageAttachment); + std::shared_ptr getMessageAttachment() const; + + /** + * nth is used in native api call: + * int email_download_attachment(int mail_id, int nth, int *handle); + * + * nth is equal to attachment index+1 (starts from 1 not 0) see + * email-api-network.h for details. + * */ + void setNth(const int nth); + int getNth() const; + + private: + std::shared_ptr m_message_attachment; + int m_nth; }; class SyncCallbackData : public BaseMessageServiceCallbackData { -public: - SyncCallbackData(PostQueue& queue, long cid); - virtual ~SyncCallbackData(); + public: + SyncCallbackData(PostQueue& queue, long cid); + virtual ~SyncCallbackData(); - void setLimit(const unsigned long limit); - bool isLimit() const; - unsigned long getLimit() const; + void setLimit(const unsigned long limit); + bool isLimit() const; + unsigned long getLimit() const; - void setOpId(long op_id); - long getOpId(); - void setAccountId(int account_id); - int getAccountId() const; + void setOpId(long op_id); + long getOpId(); + void setAccountId(int account_id); + int getAccountId() const; -protected: - bool m_is_limit; - unsigned long m_limit; + protected: + bool m_is_limit; + unsigned long m_limit; - long m_op_id; - int m_account_id; + long m_op_id; + int m_account_id; }; class SyncFolderCallbackData : public SyncCallbackData { -public: - using SyncCallbackData::SyncCallbackData; - virtual ~SyncFolderCallbackData(); + public: + using SyncCallbackData::SyncCallbackData; + virtual ~SyncFolderCallbackData(); - void setMessageFolder(std::shared_ptr message_folder); - std::shared_ptr getMessageFolder() const; + void setMessageFolder(std::shared_ptr message_folder); + std::shared_ptr getMessageFolder() const; -private: - std::shared_ptr m_message_folder; + private: + std::shared_ptr m_message_folder; }; -class MessageService -{ -public: - virtual ~MessageService(); - - virtual int getMsgServiceId() const; - virtual std::string getMsgServiceIdStr() const; - virtual MessageType getMsgServiceType() const; - std::string getMsgServiceTypeString() const; - virtual std::string getMsgServiceName() const; - - virtual MessageStoragePtr getMsgStorage() const; - - virtual common::PlatformResult sendMessage(MessageRecipientsCallbackData *callback); - virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); - virtual common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); - virtual common::PlatformResult sync(SyncCallbackData *callback, long* operation_id); - virtual common::PlatformResult syncFolder(SyncFolderCallbackData *callback, long* operation_id); - virtual common::PlatformResult stopSync(long op_id); - - picojson::object toPicoJS() const; - -protected: - /** - * We have child classes MessageServiceEmail and MessageServiceShortMsg which - * should provide specialized implementation. - */ - MessageService(int id, - MessageType msgType, - const std::string& name); - - int m_id; - MessageType m_msg_type; - std::string m_name; - MessageStoragePtr m_storage; +class MessageService { + public: + virtual ~MessageService(); + + virtual int getMsgServiceId() const; + virtual std::string getMsgServiceIdStr() const; + virtual MessageType getMsgServiceType() const; + std::string getMsgServiceTypeString() const; + virtual std::string getMsgServiceName() const; + + virtual MessageStoragePtr getMsgStorage() const; + + virtual common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); + virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); + virtual common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); + virtual common::PlatformResult sync(SyncCallbackData* callback, long* operation_id); + virtual common::PlatformResult syncFolder(SyncFolderCallbackData* callback, long* operation_id); + virtual common::PlatformResult stopSync(long op_id); + + picojson::object toPicoJS() const; + + protected: + /** + * We have child classes MessageServiceEmail and MessageServiceShortMsg which + * should provide specialized implementation. + */ + MessageService(int id, MessageType msgType, const std::string& name); + + int m_id; + MessageType m_msg_type; + std::string m_name; + MessageStoragePtr m_storage; }; -} // messaging -} // extension -#endif // MESSAGING_MESSAGE_SERVICE_EMAIL_H_ +} // messaging +} // extension +#endif // MESSAGING_MESSAGE_SERVICE_EMAIL_H_ diff --git a/src/messaging/message_service_email.cc b/src/messaging/message_service_email.cc old mode 100755 new mode 100644 index 34c2f6d..6780539 --- a/src/messaging/message_service_email.cc +++ b/src/messaging/message_service_email.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_service_email.h" #include "email_manager.h" @@ -26,11 +26,8 @@ namespace extension { namespace messaging { MessageServiceEmail::MessageServiceEmail(int id, std::string name) - : MessageService(id, - MessageType::EMAIL, - name) -{ - LoggerD("Entered"); + : MessageService(id, MessageType::EMAIL, name) { + LoggerD("Entered"); } MessageServiceEmail::~MessageServiceEmail() { @@ -43,11 +40,11 @@ MessageServiceEmail::~MessageServiceEmail() { } } -static gboolean sendMessageTask(void* data) -{ +static gboolean sendMessageTask(void* data) { LoggerD("Entered"); - auto ret = EmailManager::getInstance().sendMessage(static_cast(data)); + auto ret = + EmailManager::getInstance().sendMessage(static_cast(data)); if (!ret) { LoggerE("Error: %d - %s", ret.error_code(), ret.message().c_str()); @@ -56,56 +53,48 @@ static gboolean sendMessageTask(void* data) return FALSE; } -PlatformResult MessageServiceEmail::sendMessage(MessageRecipientsCallbackData *callback) -{ - LoggerD("Entered"); +PlatformResult MessageServiceEmail::sendMessage(MessageRecipientsCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); - } + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); + } - callback->setAccountId(m_id); + callback->setAccountId(m_id); - guint id = g_idle_add(sendMessageTask, static_cast(callback)); - if (!id) { - delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add fails")); - } + guint id = g_idle_add(sendMessageTask, static_cast(callback)); + if (!id) { + delete callback; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add fails")); + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean loadMessageBodyTask(void* data) -{ - LoggerD("Entered"); +static gboolean loadMessageBodyTask(void* data) { + LoggerD("Entered"); - EmailManager::getInstance().loadMessageBody(static_cast(data)); + EmailManager::getInstance().loadMessageBody(static_cast(data)); - return FALSE; + return FALSE; } -PlatformResult MessageServiceEmail::loadMessageBody(MessageBodyCallbackData* callback) -{ - LoggerD("Entered"); - if (!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); - } +PlatformResult MessageServiceEmail::loadMessageBody(MessageBodyCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); + } - guint id = g_idle_add(loadMessageBodyTask, static_cast(callback)); - if (!id) { - delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add failed")); - } + guint id = g_idle_add(loadMessageBodyTask, static_cast(callback)); + if (!id) { + delete callback; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add failed")); + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean loadMessageAttachmentTask(void* data) -{ +static gboolean loadMessageAttachmentTask(void* data) { LoggerD("Entered"); auto callback = static_cast(data); @@ -137,21 +126,17 @@ static gboolean loadMessageAttachmentTask(void* data) return FALSE; } -PlatformResult MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallbackData *callback) -{ +PlatformResult MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallbackData* callback) { LoggerD("Entered"); guint id = g_idle_add(loadMessageAttachmentTask, static_cast(callback)); if (!id) { delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add failed")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add failed")); } return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean syncTask(void* data) -{ +static gboolean syncTask(void* data) { LoggerD("Entered"); EmailManager::getInstance().sync(data); @@ -159,8 +144,7 @@ static gboolean syncTask(void* data) return FALSE; } -PlatformResult MessageServiceEmail::sync(SyncCallbackData *callback, long* operation_id) -{ +PlatformResult MessageServiceEmail::sync(SyncCallbackData* callback, long* operation_id) { LoggerD("Entered"); if (!callback) { @@ -173,26 +157,23 @@ PlatformResult MessageServiceEmail::sync(SyncCallbackData *callback, long* opera guint id = g_idle_add(syncTask, static_cast(callback)); if (!id) { delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add failed")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add failed")); } *operation_id = op_id; registered_callbacks_.insert(op_id); return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean syncFolderTask(void* data) -{ - LoggerD("Entered"); +static gboolean syncFolderTask(void* data) { + LoggerD("Entered"); - EmailManager::getInstance().syncFolder(static_cast(data)); + EmailManager::getInstance().syncFolder(static_cast(data)); - return FALSE; + return FALSE; } -PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData *callback, long* operation_id) -{ +PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData* callback, + long* operation_id) { LoggerD("Entered"); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); @@ -209,17 +190,14 @@ PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData *callback, guint id = g_idle_add(syncFolderTask, callback); if (!id) { delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add fails")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add fails")); } *operation_id = op_id; registered_callbacks_.insert(op_id); return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean stopSyncTask(void* data) -{ +static gboolean stopSyncTask(void* data) { LoggerD("Entered"); if (!data) { @@ -235,8 +213,7 @@ static gboolean stopSyncTask(void* data) return FALSE; } -PlatformResult MessageServiceEmail::stopSync(long op_id) -{ +PlatformResult MessageServiceEmail::stopSync(long op_id) { LoggerD("Entered"); registered_callbacks_.erase(op_id); @@ -246,13 +223,10 @@ PlatformResult MessageServiceEmail::stopSync(long op_id) if (!id) { delete data; data = NULL; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add failed")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add failed")); } return PlatformResult(ErrorCode::NO_ERROR); } -} // messaging -} // extension - +} // messaging +} // extension diff --git a/src/messaging/message_service_email.h b/src/messaging/message_service_email.h old mode 100755 new mode 100644 index e78801b..8d14bb7 --- a/src/messaging/message_service_email.h +++ b/src/messaging/message_service_email.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_SERVICE_EMAIL_H_ #define MESSAGING_MESSAGE_SERVICE_EMAIL_H_ @@ -25,22 +25,22 @@ namespace extension { namespace messaging { class MessageServiceEmail : public MessageService { -public: - MessageServiceEmail(int id, std::string name); - virtual ~MessageServiceEmail(); - - virtual common::PlatformResult sendMessage(MessageRecipientsCallbackData *callback); - virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); - virtual common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); - virtual common::PlatformResult sync(SyncCallbackData *callback, long* operation_id); - virtual common::PlatformResult syncFolder(SyncFolderCallbackData *callback, long* operation_id); - virtual common::PlatformResult stopSync(long op_id); - -private: - std::unordered_set registered_callbacks_; + public: + MessageServiceEmail(int id, std::string name); + virtual ~MessageServiceEmail(); + + virtual common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); + virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); + virtual common::PlatformResult loadMessageAttachment(MessageAttachmentCallbackData* callback); + virtual common::PlatformResult sync(SyncCallbackData* callback, long* operation_id); + virtual common::PlatformResult syncFolder(SyncFolderCallbackData* callback, long* operation_id); + virtual common::PlatformResult stopSync(long op_id); + + private: + std::unordered_set registered_callbacks_; }; -} // messaging -} // extension +} // messaging +} // extension -#endif // MESSAGING_MESSAGE_SERVICE_EMAIL_H_ +#endif // MESSAGING_MESSAGE_SERVICE_EMAIL_H_ diff --git a/src/messaging/message_service_short_msg.cc b/src/messaging/message_service_short_msg.cc old mode 100755 new mode 100644 index 3d0cd75..290f865 --- a/src/messaging/message_service_short_msg.cc +++ b/src/messaging/message_service_short_msg.cc @@ -15,21 +15,21 @@ */ #include "message_service_short_msg.h" -#include "messaging_instance.h" -#include "short_message_manager.h" #include "common/logger.h" #include "common/platform_exception.h" +#include "messaging_instance.h" +#include "short_message_manager.h" -#include -#include #include +#include +#include //#include //#include //#include //#include "JSMessage.h" -//using namespace DeviceAPI::Common; +// using namespace DeviceAPI::Common; using common::ErrorCode; using common::PlatformResult; @@ -38,23 +38,19 @@ namespace extension { namespace messaging { MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType) - : MessageService(id, - msgType, - MessagingUtil::messageTypeToString(msgType)) -{ - LoggerD("Entered"); + : MessageService(id, msgType, MessagingUtil::messageTypeToString(msgType)) { + LoggerD("Entered"); } -MessageServiceShortMsg::~MessageServiceShortMsg() -{ - LoggerD("Entered"); +MessageServiceShortMsg::~MessageServiceShortMsg() { + LoggerD("Entered"); } -static gboolean sendMessageThread(void* data) -{ +static gboolean sendMessageThread(void* data) { LoggerD("Entered"); - auto ret = ShortMsgManager::getInstance().sendMessage(static_cast(data)); + auto ret = + ShortMsgManager::getInstance().sendMessage(static_cast(data)); if (!ret) { LoggerE("Error: %d - %s", ret.error_code(), ret.message().c_str()); @@ -63,117 +59,106 @@ static gboolean sendMessageThread(void* data) return FALSE; } -PlatformResult MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData *callback) -{ - LoggerD("Entered"); - if (!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); - } +PlatformResult MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); + } - /* - * Set sim index. - * If user has set sim index manually, check sim index is valid. - * Otherwise, use default sim which is already set. - */ - TelNetworkDefaultDataSubs_t default_sim = - TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN; - TapiHandle *handle = tel_init(NULL); - - int ret = tel_get_network_default_data_subscription(handle, &default_sim); - if (ret != TAPI_API_SUCCESS) { - LoggerE("Failed to find default sim index %d", ret); - } + /* + * Set sim index. + * If user has set sim index manually, check sim index is valid. + * Otherwise, use default sim which is already set. + */ + TelNetworkDefaultDataSubs_t default_sim = TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN; + TapiHandle* handle = tel_init(NULL); + + int ret = tel_get_network_default_data_subscription(handle, &default_sim); + if (ret != TAPI_API_SUCCESS) { + LoggerE("Failed to find default sim index %d", ret); + } - LoggerD("Default sim index: %d", default_sim); - callback->setDefaultSimIndex(default_sim); - tel_deinit(handle); - - // simIndex parameter is only available for sms message. - // In case of mms, the parameter is silently ignored. - if (callback->isSetSimIndex() && - callback->getMessage()->getType() == MessageType::SMS) { - char **cp_list = tel_get_cp_name_list(); - TelNetworkDefaultDataSubs_t sim_index = callback->getSimIndex(); - int sim_count = 0; - - if (cp_list) { - while (cp_list[sim_count]) { - sim_count++; - } - g_strfreev(cp_list); - } else { - LoggerD("Empty cp name list"); - } - - if (sim_index >= sim_count) { - delete callback; - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "The index of sim is out of bound", - ("Sim index out of count %d : %d", sim_index, sim_count)); - } - - callback->getMessage()->setSimIndex(sim_index); + LoggerD("Default sim index: %d", default_sim); + callback->setDefaultSimIndex(default_sim); + tel_deinit(handle); + + // simIndex parameter is only available for sms message. + // In case of mms, the parameter is silently ignored. + if (callback->isSetSimIndex() && callback->getMessage()->getType() == MessageType::SMS) { + char** cp_list = tel_get_cp_name_list(); + TelNetworkDefaultDataSubs_t sim_index = callback->getSimIndex(); + int sim_count = 0; + + if (cp_list) { + while (cp_list[sim_count]) { + sim_count++; + } + g_strfreev(cp_list); } else { - callback->getMessage()->setSimIndex(default_sim); + LoggerD("Empty cp name list"); } - if(!g_idle_add(sendMessageThread, static_cast(callback))) { - delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add fails")); + if (sim_index >= sim_count) { + delete callback; + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "The index of sim is out of bound", + ("Sim index out of count %d : %d", sim_index, sim_count)); } - return PlatformResult(ErrorCode::NO_ERROR); + callback->getMessage()->setSimIndex(sim_index); + } else { + callback->getMessage()->setSimIndex(default_sim); + } + + if (!g_idle_add(sendMessageThread, static_cast(callback))) { + delete callback; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add fails")); + } + + return PlatformResult(ErrorCode::NO_ERROR); } -static gboolean loadMessageBodyTask(void* data) -{ - LoggerD("Entered"); - MessageBodyCallbackData* callback = static_cast(data); - if(!callback) { - LoggerE("callback is NULL"); - return FALSE; - } +static gboolean loadMessageBodyTask(void* data) { + LoggerD("Entered"); + MessageBodyCallbackData* callback = static_cast(data); + if (!callback) { + LoggerE("callback is NULL"); + return FALSE; + } - std::shared_ptr body = callback->getMessage()->getBody(); - picojson::object args; - args[JSON_DATA_MESSAGE_BODY] = MessagingUtil::messageBodyToJson(body); + std::shared_ptr body = callback->getMessage()->getBody(); + picojson::object args; + args[JSON_DATA_MESSAGE_BODY] = MessagingUtil::messageBodyToJson(body); - callback->SetSuccess(picojson::value(args)); - callback->Post(); + callback->SetSuccess(picojson::value(args)); + callback->Post(); - return FALSE; + return FALSE; } -PlatformResult MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData *callback) -{ - LoggerD("Entered"); - if (!callback) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); - } +PlatformResult MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); + } - guint id = g_idle_add(loadMessageBodyTask, static_cast(callback)); - if (!id) { - delete callback; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Could not add task", - ("g_idle_add fails")); - } + guint id = g_idle_add(loadMessageBodyTask, static_cast(callback)); + if (!id) { + delete callback; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add task", ("g_idle_add fails")); + } - return PlatformResult(ErrorCode::NO_ERROR); + return PlatformResult(ErrorCode::NO_ERROR); } MessageServiceShortMsg* MessageServiceShortMsg::GetMmsMessageService() { - return new (std::nothrow) MessageServiceShortMsg( - MessageServiceAccountId::MMS_ACCOUNT_ID, MessageType::MMS); + return new (std::nothrow) + MessageServiceShortMsg(MessageServiceAccountId::MMS_ACCOUNT_ID, MessageType::MMS); } MessageServiceShortMsg* MessageServiceShortMsg::GetSmsMessageService() { - return new (std::nothrow) MessageServiceShortMsg( - MessageServiceAccountId::SMS_ACCOUNT_ID, MessageType::SMS); + return new (std::nothrow) + MessageServiceShortMsg(MessageServiceAccountId::SMS_ACCOUNT_ID, MessageType::SMS); } -} // namespace messaging -} // namespace extension - +} // namespace messaging +} // namespace extension diff --git a/src/messaging/message_service_short_msg.h b/src/messaging/message_service_short_msg.h old mode 100755 new mode 100644 index 727385f..d1ad5f2 --- a/src/messaging/message_service_short_msg.h +++ b/src/messaging/message_service_short_msg.h @@ -24,20 +24,20 @@ namespace extension { namespace messaging { class MessageServiceShortMsg : public MessageService { -public: - virtual ~MessageServiceShortMsg(); + public: + virtual ~MessageServiceShortMsg(); - common::PlatformResult sendMessage(MessageRecipientsCallbackData *callback); + common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); - virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData *callback); + virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); - static MessageServiceShortMsg* GetMmsMessageService(); - static MessageServiceShortMsg* GetSmsMessageService(); + static MessageServiceShortMsg* GetMmsMessageService(); + static MessageServiceShortMsg* GetSmsMessageService(); -protected: - MessageServiceShortMsg(int id, MessageType msgType); + protected: + MessageServiceShortMsg(int id, MessageType msgType); }; -} // namespace messaging -} // namespace extension -#endif // __MESSAGING_MESSAGE_SERVICE_SHORT_MSG_H__ +} // namespace messaging +} // namespace extension +#endif // __MESSAGING_MESSAGE_SERVICE_SHORT_MSG_H__ diff --git a/src/messaging/message_sms.cc b/src/messaging/message_sms.cc old mode 100755 new mode 100644 index 0f02ec4..bf67c8c --- a/src/messaging/message_sms.cc +++ b/src/messaging/message_sms.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include #include "message_sms.h" @@ -21,17 +21,14 @@ namespace extension { namespace messaging { -MessageSMS::MessageSMS(): - Message() -{ - LoggerD("MessageSMS constructor."); - this->m_type = MessageType(MessageType(SMS)); +MessageSMS::MessageSMS() : Message() { + LoggerD("MessageSMS constructor."); + this->m_type = MessageType(MessageType(SMS)); } -MessageSMS::~MessageSMS() -{ - LoggerD("MessageSMS destructor."); +MessageSMS::~MessageSMS() { + LoggerD("MessageSMS destructor."); } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_sms.h b/src/messaging/message_sms.h index 5b252ff..337861f 100644 --- a/src/messaging/message_sms.h +++ b/src/messaging/message_sms.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __MESSAGING_MESSAGE_SMS_H__ #define __MESSAGING_MESSAGE_SMS_H__ @@ -25,15 +25,14 @@ namespace extension { namespace messaging { -class MessageSMS: public Message { -public: -// constructor - MessageSMS(); - ~MessageSMS(); - +class MessageSMS : public Message { + public: + // constructor + MessageSMS(); + ~MessageSMS(); }; -} // messaging -} // extension +} // messaging +} // extension -#endif // __MESSAGING_MESSAGE_SMS_H__ +#endif // __MESSAGING_MESSAGE_SMS_H__ diff --git a/src/messaging/message_storage.cc b/src/messaging/message_storage.cc old mode 100755 new mode 100644 index 7ce8304..36a771b --- a/src/messaging/message_storage.cc +++ b/src/messaging/message_storage.cc @@ -13,22 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_storage.h" -#include "messages_change_callback.h" +#include "change_listener_container.h" #include "conversations_change_callback.h" #include "folders_change_callback.h" -#include "change_listener_container.h" +#include "messages_change_callback.h" #include "common/logger.h" namespace extension { namespace messaging { -MessageStorage::MessageStorage(int id, MessageType msgType) : - m_id(id), m_msg_type(msgType) -{ - LoggerD("Entered"); +MessageStorage::MessageStorage(int id, MessageType msgType) : m_id(id), m_msg_type(msgType) { + LoggerD("Entered"); } MessageStorage::~MessageStorage() { @@ -39,53 +37,47 @@ MessageStorage::~MessageStorage() { } } -int MessageStorage::getMsgServiceId() const -{ - LoggerD("Entered"); - return m_id; +int MessageStorage::getMsgServiceId() const { + LoggerD("Entered"); + return m_id; } -MessageType MessageStorage::getMsgServiceType() const -{ - LoggerD("Entered"); - return m_msg_type; +MessageType MessageStorage::getMsgServiceType() const { + LoggerD("Entered"); + return m_msg_type; } std::string MessageStorage::getMsgServiceTypeString() const { return MessagingUtil::messageTypeToString(getMsgServiceType()); } -long MessageStorage::addMessagesChangeListener(std::shared_ptr callback) -{ - LoggerD("Entered"); - long id = ChangeListenerContainer::getInstance().addMessageChangeListener(callback); - registered_listeners_.insert(id); - return id; +long MessageStorage::addMessagesChangeListener(std::shared_ptr callback) { + LoggerD("Entered"); + long id = ChangeListenerContainer::getInstance().addMessageChangeListener(callback); + registered_listeners_.insert(id); + return id; } long MessageStorage::addConversationsChangeListener( - std::shared_ptr callback) -{ - LoggerD("Entered"); - long id = ChangeListenerContainer::getInstance().addConversationChangeListener(callback); - registered_listeners_.insert(id); - return id; + std::shared_ptr callback) { + LoggerD("Entered"); + long id = ChangeListenerContainer::getInstance().addConversationChangeListener(callback); + registered_listeners_.insert(id); + return id; } -long MessageStorage::addFoldersChangeListener(std::shared_ptr callback) -{ - LoggerD("Entered"); - long id = ChangeListenerContainer::getInstance().addFolderChangeListener(callback); - registered_listeners_.insert(id); - return id; +long MessageStorage::addFoldersChangeListener(std::shared_ptr callback) { + LoggerD("Entered"); + long id = ChangeListenerContainer::getInstance().addFolderChangeListener(callback); + registered_listeners_.insert(id); + return id; } -void MessageStorage::removeChangeListener(long watchId) -{ - LoggerD("Entered"); - ChangeListenerContainer::getInstance().removeChangeListener(watchId); - registered_listeners_.erase(watchId); +void MessageStorage::removeChangeListener(long watchId) { + LoggerD("Entered"); + ChangeListenerContainer::getInstance().removeChangeListener(watchId); + registered_listeners_.erase(watchId); } -} //messaging -} //extension +} // messaging +} // extension diff --git a/src/messaging/message_storage.h b/src/messaging/message_storage.h index 6db19f1..8fdb208 100644 --- a/src/messaging/message_storage.h +++ b/src/messaging/message_storage.h @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGE_STORAGE_H_ #define MESSAGING_MESSAGE_STORAGE_H_ #include #include -#include "common/platform_result.h" #include "common/logger.h" +#include "common/platform_result.h" -#include "messaging_util.h" -#include "message_callback_user_data.h" -#include "messages_callback_user_data.h" #include "conversation_callback_data.h" #include "find_msg_callback_user_data.h" #include "folders_callback_data.h" +#include "message_callback_user_data.h" +#include "messages_callback_user_data.h" +#include "messaging_util.h" namespace extension { namespace messaging { @@ -41,37 +41,36 @@ class MessageStorage; typedef std::shared_ptr MessageStoragePtr; class MessageStorage { -public: - MessageStorage(int id, MessageType msgType); - virtual ~MessageStorage(); + public: + MessageStorage(int id, MessageType msgType); + virtual ~MessageStorage(); - virtual int getMsgServiceId() const; - virtual MessageType getMsgServiceType() const; - std::string getMsgServiceTypeString() const; + virtual int getMsgServiceId() const; + virtual MessageType getMsgServiceType() const; + std::string getMsgServiceTypeString() const; - virtual void addDraftMessage(MessageCallbackUserData* callback) = 0; - virtual void removeMessages(MessagesCallbackUserData* callback) = 0; - virtual void updateMessages(MessagesCallbackUserData* callback) = 0; - virtual void findMessages(FindMsgCallbackUserData* callback) = 0; - virtual void findConversations(ConversationCallbackData* callback) = 0; - virtual void removeConversations(ConversationCallbackData* callback) = 0; - virtual void findFolders(FoldersCallbackData* callback) = 0; + virtual void addDraftMessage(MessageCallbackUserData* callback) = 0; + virtual void removeMessages(MessagesCallbackUserData* callback) = 0; + virtual void updateMessages(MessagesCallbackUserData* callback) = 0; + virtual void findMessages(FindMsgCallbackUserData* callback) = 0; + virtual void findConversations(ConversationCallbackData* callback) = 0; + virtual void removeConversations(ConversationCallbackData* callback) = 0; + virtual void findFolders(FoldersCallbackData* callback) = 0; - // Listeners registration/removal is common for all types of storage - // and does not have to be overwritten in derived classes. - long addMessagesChangeListener(std::shared_ptr callback); - long addConversationsChangeListener(std::shared_ptr callback); - long addFoldersChangeListener(std::shared_ptr callback); - void removeChangeListener(long watchId); + // Listeners registration/removal is common for all types of storage + // and does not have to be overwritten in derived classes. + long addMessagesChangeListener(std::shared_ptr callback); + long addConversationsChangeListener(std::shared_ptr callback); + long addFoldersChangeListener(std::shared_ptr callback); + void removeChangeListener(long watchId); -protected: - int m_id; - MessageType m_msg_type; - std::unordered_set registered_listeners_; + protected: + int m_id; + MessageType m_msg_type; + std::unordered_set registered_listeners_; }; -} //messaging -} //extension +} // messaging +} // extension #endif /* MESSAGING_MESSAGE_STORAGE_H_ */ - diff --git a/src/messaging/message_storage_email.cc b/src/messaging/message_storage_email.cc old mode 100755 new mode 100644 index cbb63d9..432f21b --- a/src/messaging/message_storage_email.cc +++ b/src/messaging/message_storage_email.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "message_storage_email.h" #include @@ -26,216 +26,200 @@ namespace extension { namespace messaging { -MessageStorageEmail::MessageStorageEmail(int id) : - MessageStorage(id, MessageType::EMAIL) -{ - LoggerD("Entered"); +MessageStorageEmail::MessageStorageEmail(int id) : MessageStorage(id, MessageType::EMAIL) { + LoggerD("Entered"); } -MessageStorageEmail::~MessageStorageEmail() -{ - LoggerD("Entered"); +MessageStorageEmail::~MessageStorageEmail() { + LoggerD("Entered"); } -static gboolean addDraftMessageTask(void* data) -{ - LoggerD("Entered"); +static gboolean addDraftMessageTask(void* data) { + LoggerD("Entered"); - MessageCallbackUserData *callback = static_cast(data); - EmailManager::getInstance().addDraftMessage(callback); + MessageCallbackUserData* callback = static_cast(data); + EmailManager::getInstance().addDraftMessage(callback); - return FALSE; + return FALSE; } void MessageStorageEmail::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Entered"); + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setAccountId(m_id); + callback->setAccountId(m_id); - guint id = g_idle_add(addDraftMessageTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + guint id = g_idle_add(addDraftMessageTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean removeMessagesTask(void* data) -{ - LoggerD("Entered"); +static gboolean removeMessagesTask(void* data) { + LoggerD("Entered"); - MessagesCallbackUserData *callback = static_cast(data); - EmailManager::getInstance().removeMessages(callback); + MessagesCallbackUserData* callback = static_cast(data); + EmailManager::getInstance().removeMessages(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(removeMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + guint id = g_idle_add(removeMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean updateMessagesTask(void* data) -{ - LoggerD("Entered"); +static gboolean updateMessagesTask(void* data) { + LoggerD("Entered"); - MessagesCallbackUserData *callback = static_cast(data); - EmailManager::getInstance().updateMessages(callback); + MessagesCallbackUserData* callback = static_cast(data); + EmailManager::getInstance().updateMessages(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(updateMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + callback->setMessageServiceType(m_msg_type); + guint id = g_idle_add(updateMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean findMessagesTask(void* data) -{ - LoggerD("Entered"); +static gboolean findMessagesTask(void* data) { + LoggerD("Entered"); - FindMsgCallbackUserData *callback = static_cast(data); - EmailManager::getInstance().findMessages(callback); + FindMsgCallbackUserData* callback = static_cast(data); + EmailManager::getInstance().findMessages(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setAccountId(m_id); - callback->setMessageServiceType(m_msg_type); + callback->setAccountId(m_id); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(findMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + guint id = g_idle_add(findMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean findConversationsTask(void* data) -{ - LoggerD("Entered"); +static gboolean findConversationsTask(void* data) { + LoggerD("Entered"); - ConversationCallbackData *callback = static_cast(data); - EmailManager::getInstance().findConversations(callback); + ConversationCallbackData* callback = static_cast(data); + EmailManager::getInstance().findConversations(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::findConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::findConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setAccountId(m_id); - callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(findConversationsTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + callback->setAccountId(m_id); + callback->setMessageServiceType(m_msg_type); + guint id = g_idle_add(findConversationsTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean removeConversationsTask(void* data) -{ - LoggerD("Entered"); +static gboolean removeConversationsTask(void* data) { + LoggerD("Entered"); - ConversationCallbackData *callback = static_cast(data); - EmailManager::getInstance().removeConversations(callback); + ConversationCallbackData* callback = static_cast(data); + EmailManager::getInstance().removeConversations(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::removeConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::removeConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(removeConversationsTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + guint id = g_idle_add(removeConversationsTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -static gboolean findFoldersTask(void* data) -{ - LoggerD("Entered"); +static gboolean findFoldersTask(void* data) { + LoggerD("Entered"); - FoldersCallbackData *callback = static_cast(data); - EmailManager::getInstance().findFolders(callback); + FoldersCallbackData* callback = static_cast(data); + EmailManager::getInstance().findFolders(callback); - return FALSE; + return FALSE; } -void MessageStorageEmail::findFolders(FoldersCallbackData* callback) -{ - LoggerD("Entered"); +void MessageStorageEmail::findFolders(FoldersCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - guint id = g_idle_add(findFoldersTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } + guint id = g_idle_add(findFoldersTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -} //messaging -} //extension +} // messaging +} // extension diff --git a/src/messaging/message_storage_email.h b/src/messaging/message_storage_email.h index fe943e7..53a557b 100644 --- a/src/messaging/message_storage_email.h +++ b/src/messaging/message_storage_email.h @@ -22,22 +22,21 @@ namespace extension { namespace messaging { -class MessageStorageEmail: public MessageStorage { -public: - MessageStorageEmail(int id); - virtual ~MessageStorageEmail(); - - virtual void addDraftMessage(MessageCallbackUserData* callback); - virtual void removeMessages(MessagesCallbackUserData* callback); - virtual void updateMessages(MessagesCallbackUserData* callback); - virtual void findMessages(FindMsgCallbackUserData* callback); - virtual void findConversations(ConversationCallbackData* callback); - virtual void removeConversations(ConversationCallbackData* callback); - virtual void findFolders(FoldersCallbackData* callback); +class MessageStorageEmail : public MessageStorage { + public: + MessageStorageEmail(int id); + virtual ~MessageStorageEmail(); + + virtual void addDraftMessage(MessageCallbackUserData* callback); + virtual void removeMessages(MessagesCallbackUserData* callback); + virtual void updateMessages(MessagesCallbackUserData* callback); + virtual void findMessages(FindMsgCallbackUserData* callback); + virtual void findConversations(ConversationCallbackData* callback); + virtual void removeConversations(ConversationCallbackData* callback); + virtual void findFolders(FoldersCallbackData* callback); }; -} //messaging -} //extension +} // messaging +} // extension #endif /* MESSAGING_MESSAGE_STORAGE_EMAIL_H_ */ - diff --git a/src/messaging/message_storage_short_msg.cc b/src/messaging/message_storage_short_msg.cc old mode 100755 new mode 100644 index 2691a3e..69a1ebd --- a/src/messaging/message_storage_short_msg.cc +++ b/src/messaging/message_storage_short_msg.cc @@ -13,259 +13,245 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "common/logger.h" #include "common/platform_exception.h" -#include "messaging_util.h" #include "message_sms.h" -#include "short_message_manager.h" #include "message_storage_short_msg.h" #include "messaging_instance.h" +#include "messaging_util.h" +#include "short_message_manager.h" namespace extension { namespace messaging { -MessageStorageShortMsg::MessageStorageShortMsg(int id, MessageType msgType): - MessageStorage(id, msgType) { - LoggerD("Entered"); +MessageStorageShortMsg::MessageStorageShortMsg(int id, MessageType msgType) + : MessageStorage(id, msgType) { + LoggerD("Entered"); } MessageStorageShortMsg::~MessageStorageShortMsg() { - LoggerD("Entered"); + LoggerD("Entered"); } static gboolean addDraftMessageTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - MessageCallbackUserData *callback = static_cast(data); - ShortMsgManager::getInstance().addDraftMessage(callback); + MessageCallbackUserData* callback = static_cast(data); + ShortMsgManager::getInstance().addDraftMessage(callback); - return false; + return false; } void MessageStorageShortMsg::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Entered"); - - if (!callback) { - LoggerE("Callback is null"); - return; - } - - guint id = g_idle_add(addDraftMessageTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + LoggerD("Entered"); + + if (!callback) { + LoggerE("Callback is null"); + return; + } + + guint id = g_idle_add(addDraftMessageTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } static gboolean removeMessagesTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - MessagesCallbackUserData *callback = static_cast(data); - ShortMsgManager::getInstance().removeMessages(callback); + MessagesCallbackUserData* callback = static_cast(data); + ShortMsgManager::getInstance().removeMessages(callback); - return false; + return false; } -void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(removeMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + guint id = g_idle_add(removeMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } static gboolean updateMessagesTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - MessagesCallbackUserData *callback = static_cast(data); - ShortMsgManager::getInstance().updateMessages(callback); + MessagesCallbackUserData* callback = static_cast(data); + ShortMsgManager::getInstance().updateMessages(callback); - return false; + return false; } -void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(updateMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + guint id = g_idle_add(updateMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } static gboolean findMessagesTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - FindMsgCallbackUserData *callback = static_cast(data); - ShortMsgManager::getInstance().findMessages(callback); + FindMsgCallbackUserData* callback = static_cast(data); + ShortMsgManager::getInstance().findMessages(callback); - return false; + return false; } -void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback) -{ - LoggerD("Entered"); +void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(findMessagesTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + guint id = g_idle_add(findMessagesTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } static gboolean findConversationsTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - ConversationCallbackData *callback = static_cast(data); - ShortMsgManager::getInstance().findConversations(callback); + ConversationCallbackData* callback = static_cast(data); + ShortMsgManager::getInstance().findConversations(callback); - return false; + return false; } -void MessageStorageShortMsg::findConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void MessageStorageShortMsg::findConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(findConversationsTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + guint id = g_idle_add(findConversationsTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } static gboolean removeConversationsTask(void* data) { - LoggerD("Entered"); + LoggerD("Entered"); - ConversationCallbackData *callback = static_cast(data); - ShortMsgManager::getInstance().removeConversations(callback); + ConversationCallbackData* callback = static_cast(data); + ShortMsgManager::getInstance().removeConversations(callback); - return false; + return false; } -void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback) { - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - callback->setMessageServiceType(m_msg_type); + callback->setMessageServiceType(m_msg_type); - guint id = g_idle_add(removeConversationsTask, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - return; - } + guint id = g_idle_add(removeConversationsTask, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + return; + } } -static gboolean findFoldersCB(void* data) -{ - LoggerD("Entered"); +static gboolean findFoldersCB(void* data) { + LoggerD("Entered"); - FoldersCallbackData *callback = static_cast(data); + FoldersCallbackData* callback = static_cast(data); - picojson::array array; - auto each = [&array](std::shared_ptr folder)->void { - array.push_back(MessagingUtil::folderToJson(folder)); - }; + picojson::array array; + auto each = [&array](std::shared_ptr folder) -> void { + array.push_back(MessagingUtil::folderToJson(folder)); + }; - auto folders = callback->getFolders(); - for_each(folders.begin(), folders.end(), each); + auto folders = callback->getFolders(); + for_each(folders.begin(), folders.end(), each); - callback->SetSuccess(picojson::value(array)); - callback->Post(); + callback->SetSuccess(picojson::value(array)); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return FALSE; + return FALSE; } - -void MessageStorageShortMsg::findFolders(FoldersCallbackData* callback) -{ - LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; - } - - std::string content_type = getMsgServiceTypeString(); - std::string empty = ""; - std::shared_ptr folder; - - /* For SMS and MMS, folderId can be one of these values: - * - * INBOX = 1, - * OUTBOX = 2, - * DRAFTS = 3, - * SENTBOX = 4 - */ - - for(int i = 1;i < 5;i++) - { - folder = std::make_shared( - std::to_string(i), - empty, - std::to_string(m_id), - content_type, - MessagingUtil::messageFolderTypeToString((MessageFolderType)i), - empty, - (MessageFolderType)i, - false); - - callback->addFolder(folder); - } - - guint id = g_idle_add(findFoldersCB, static_cast(callback)); - if (!id) { - LoggerE("g_idle_add failed"); - delete callback; - callback = NULL; - } +void MessageStorageShortMsg::findFolders(FoldersCallbackData* callback) { + LoggerD("Entered"); + if (!callback) { + LoggerE("Callback is null"); + return; + } + + std::string content_type = getMsgServiceTypeString(); + std::string empty = ""; + std::shared_ptr folder; + + /* For SMS and MMS, folderId can be one of these values: + * + * INBOX = 1, + * OUTBOX = 2, + * DRAFTS = 3, + * SENTBOX = 4 + */ + + for (int i = 1; i < 5; i++) { + folder = std::make_shared( + std::to_string(i), empty, std::to_string(m_id), content_type, + MessagingUtil::messageFolderTypeToString((MessageFolderType)i), empty, (MessageFolderType)i, + false); + + callback->addFolder(folder); + } + + guint id = g_idle_add(findFoldersCB, static_cast(callback)); + if (!id) { + LoggerE("g_idle_add failed"); + delete callback; + callback = NULL; + } } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/message_storage_short_msg.h b/src/messaging/message_storage_short_msg.h old mode 100755 new mode 100644 index 2d7e40e..df20d4e --- a/src/messaging/message_storage_short_msg.h +++ b/src/messaging/message_storage_short_msg.h @@ -13,32 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __MESSAGING_MESSAGE_STORAGE_SMS_H #define __MESSAGING_MESSAGE_STORAGE_SMS_H #include "message_storage.h" - namespace extension { namespace messaging { -class MessageStorageShortMsg: public MessageStorage { -public: - MessageStorageShortMsg(int id, MessageType msgType); - virtual ~MessageStorageShortMsg(); - - virtual void addDraftMessage(MessageCallbackUserData* callback); - virtual void removeMessages(MessagesCallbackUserData* callback); - virtual void updateMessages(MessagesCallbackUserData* callback); - virtual void findMessages(FindMsgCallbackUserData* callback); - virtual void findConversations(ConversationCallbackData* callback); - virtual void removeConversations(ConversationCallbackData* callback); - virtual void findFolders(FoldersCallbackData* callback); +class MessageStorageShortMsg : public MessageStorage { + public: + MessageStorageShortMsg(int id, MessageType msgType); + virtual ~MessageStorageShortMsg(); + + virtual void addDraftMessage(MessageCallbackUserData* callback); + virtual void removeMessages(MessagesCallbackUserData* callback); + virtual void updateMessages(MessagesCallbackUserData* callback); + virtual void findMessages(FindMsgCallbackUserData* callback); + virtual void findConversations(ConversationCallbackData* callback); + virtual void removeConversations(ConversationCallbackData* callback); + virtual void findFolders(FoldersCallbackData* callback); }; -} // messaging -} // extension +} // messaging +} // extension #endif /* __MESSAGING_MESSAGE_STORAGE_SMS_H */ - diff --git a/src/messaging/messages_callback_user_data.cc b/src/messaging/messages_callback_user_data.cc old mode 100755 new mode 100644 index 37cdf76..cb41f5d --- a/src/messaging/messages_callback_user_data.cc +++ b/src/messaging/messages_callback_user_data.cc @@ -13,42 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "messages_callback_user_data.h" namespace extension { namespace messaging { -MessagesCallbackUserData::MessagesCallbackUserData(PostQueue& queue, long cid, bool keep /* = false*/) : - CallbackUserData(queue, cid, keep), - m_service_type(UNDEFINED) { +MessagesCallbackUserData::MessagesCallbackUserData(PostQueue& queue, long cid, + bool keep /* = false*/) + : CallbackUserData(queue, cid, keep), m_service_type(UNDEFINED) { LoggerD("Entered"); } MessagesCallbackUserData::~MessagesCallbackUserData() { - LoggerD("Entered"); + LoggerD("Entered"); } -void MessagesCallbackUserData::addMessage(std::shared_ptr msg) -{ - LoggerD("Entered"); - m_messages.push_back(msg); +void MessagesCallbackUserData::addMessage(std::shared_ptr msg) { + LoggerD("Entered"); + m_messages.push_back(msg); } -std::vector> MessagesCallbackUserData::getMessages() const -{ - return m_messages; +std::vector> MessagesCallbackUserData::getMessages() const { + return m_messages; } -void MessagesCallbackUserData::setMessageServiceType(MessageType m_msg_type) -{ - m_service_type = m_msg_type; +void MessagesCallbackUserData::setMessageServiceType(MessageType m_msg_type) { + m_service_type = m_msg_type; } -MessageType MessagesCallbackUserData::getMessageServiceType() const -{ - return m_service_type; +MessageType MessagesCallbackUserData::getMessageServiceType() const { + return m_service_type; } -}//messaging -}//extension +} // messaging +} // extension diff --git a/src/messaging/messages_callback_user_data.h b/src/messaging/messages_callback_user_data.h old mode 100755 new mode 100644 index 4efa84f..e59b100 --- a/src/messaging/messages_callback_user_data.h +++ b/src/messaging/messages_callback_user_data.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGES_CALLBACK_USER_DATA_H_ #define MESSAGING_MESSAGES_CALLBACK_USER_DATA_H_ @@ -31,22 +31,22 @@ namespace messaging { class Message; class MessagesCallbackUserData : public CallbackUserData { -public: - MessagesCallbackUserData(PostQueue& queue, long cid, bool keep = false); - virtual ~MessagesCallbackUserData(); + public: + MessagesCallbackUserData(PostQueue& queue, long cid, bool keep = false); + virtual ~MessagesCallbackUserData(); - void addMessage(std::shared_ptr msg); - std::vector> getMessages() const; + void addMessage(std::shared_ptr msg); + std::vector> getMessages() const; - void setMessageServiceType(MessageType m_msg_type); - MessageType getMessageServiceType() const; + void setMessageServiceType(MessageType m_msg_type); + MessageType getMessageServiceType() const; -private: - std::vector> m_messages; - MessageType m_service_type; + private: + std::vector> m_messages; + MessageType m_service_type; }; -}//messaging -}//extension +} // messaging +} // extension #endif /* MESSAGING_MESSAGES_CALLBACK_USER_DATA_H_ */ diff --git a/src/messaging/messages_change_callback.cc b/src/messaging/messages_change_callback.cc old mode 100755 new mode 100644 index c95e22e..937f942 --- a/src/messaging/messages_change_callback.cc +++ b/src/messaging/messages_change_callback.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + //#include //#include @@ -31,210 +31,187 @@ namespace messaging { namespace { -std::string limitedString(const std::string& src, - const size_t max_len = 40) -{ - LoggerD("Entered"); - if(src.length() > max_len) { - return src.substr(0,max_len); - } else { - return src; - } +std::string limitedString(const std::string& src, const size_t max_len = 40) { + LoggerD("Entered"); + if (src.length() > max_len) { + return src.substr(0, max_len); + } else { + return src; + } } -} //Anonymous namespace +} // Anonymous namespace const char* MESSAGESADDED = "messagesadded"; const char* MESSAGESUPDATED = "messagesupdated"; const char* MESSAGESREMOVED = "messagesremoved"; -MessagesChangeCallback::MessagesChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue) : - m_callback_data(queue, cid, true), - m_service_id(service_id), - m_msg_type(service_type), - m_is_act(true) -{ - LoggerD("Entered"); - m_callback_data.SetListenerId("MessagesChangeListener"); +MessagesChangeCallback::MessagesChangeCallback(long cid, int service_id, MessageType service_type, + PostQueue& queue) + : m_callback_data(queue, cid, true), + m_service_id(service_id), + m_msg_type(service_type), + m_is_act(true) { + LoggerD("Entered"); + m_callback_data.SetListenerId("MessagesChangeListener"); } -MessagesChangeCallback::~MessagesChangeCallback() -{ - LoggerD("Entered"); -} - -MessagePtrVector MessagesChangeCallback::filterMessages( - tizen::AbstractFilterPtr filter, - const MessagePtrVector& source_messages, - const int service_id) -{ - LoggerD("Entered sourceMessages.size():%d filter:%s", source_messages.size(), - (filter ? "PRESENT" : "NULL")); - - if (filter) { - MessagePtrVector filtered_messages; - MessagePtrVector::const_iterator it = source_messages.begin(); - MessagePtrVector::const_iterator end_it = source_messages.end(); - - for(int i = 0; it != end_it ; ++i, ++it) { - const MessagePtr& message = *it; - message->setServiceId(service_id); - - const bool matched = filter->isMatching(message.get()); - if(matched) { - filtered_messages.push_back(message); - } - - LoggerD("[%d] is Message(%p) {", i, message.get()); - LoggerD("[%d] messageId: %d", i, message->getId()); - LoggerD("[%d] message subject: %s", i, message->getSubject().c_str()); - LoggerD("[%d] from: %s", i, message->getFrom().c_str()); - - if(message->getBody()) { - const std::string& pBody = message->getBody()->getPlainBody(); - LoggerD("[%d] message plainBody: %s", i, limitedString(pBody).c_str()); - } - - LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); - LoggerD("[%d] }"); - } - - LoggerD("returning matching %d of %d messages", filtered_messages.size(), - source_messages.size()); - return filtered_messages; - } - else { - LoggerD("Abstract filter pointer is null"); - return source_messages; - } +MessagesChangeCallback::~MessagesChangeCallback() { + LoggerD("Entered"); } -void MessagesChangeCallback::added(const MessagePtrVector& msgs) -{ - LoggerD("Entered num messages: %d", msgs.size()); - if (!m_is_act) { - return; - } - MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); - //cancel callback only if filter did remove all messages - //if callback was called with empty msgs list, call it - if (msgs.size() > 0 && filtered_msgs.size() == 0) { - LoggerD("All messages were filtered out, not calling callback"); - return; +MessagePtrVector MessagesChangeCallback::filterMessages(tizen::AbstractFilterPtr filter, + const MessagePtrVector& source_messages, + const int service_id) { + LoggerD("Entered sourceMessages.size():%d filter:%s", source_messages.size(), + (filter ? "PRESENT" : "NULL")); + + if (filter) { + MessagePtrVector filtered_messages; + MessagePtrVector::const_iterator it = source_messages.begin(); + MessagePtrVector::const_iterator end_it = source_messages.end(); + + for (int i = 0; it != end_it; ++i, ++it) { + const MessagePtr& message = *it; + message->setServiceId(service_id); + + const bool matched = filter->isMatching(message.get()); + if (matched) { + filtered_messages.push_back(message); + } + + LoggerD("[%d] is Message(%p) {", i, message.get()); + LoggerD("[%d] messageId: %d", i, message->getId()); + LoggerD("[%d] message subject: %s", i, message->getSubject().c_str()); + LoggerD("[%d] from: %s", i, message->getFrom().c_str()); + + if (message->getBody()) { + const std::string& pBody = message->getBody()->getPlainBody(); + LoggerD("[%d] message plainBody: %s", i, limitedString(pBody).c_str()); + } + + LoggerD("[%d] matched filter: %s", i, matched ? "YES" : "NO"); + LoggerD("[%d] }"); } - picojson::array array; - auto each = [&array] (std::shared_ptr m)->void { - array.push_back(MessagingUtil::messageToJson(m)); - }; - - for_each(filtered_msgs.begin(), filtered_msgs.end(), each); - - LoggerD("Calling:%s with:%d added messages", MESSAGESADDED, - filtered_msgs.size()); - - m_callback_data.SetAction(MESSAGESADDED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::MEDIUM); + LoggerD("returning matching %d of %d messages", filtered_messages.size(), + source_messages.size()); + return filtered_messages; + } else { + LoggerD("Abstract filter pointer is null"); + return source_messages; + } } -void MessagesChangeCallback::updated(const MessagePtrVector& msgs) -{ - LoggerD("Entered num messages: %d", msgs.size()); - if (!m_is_act) { - return; - } - MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); - //cancel callback only if filter did remove all messages - //if callback was called with empty msgs list, call it - if (msgs.size() > 0 && filtered_msgs.size() == 0) { - LoggerD("All messages were filtered out, not calling callback"); - return; - } - - picojson::array array; - auto each = [&array] (std::shared_ptr m)->void { - array.push_back(MessagingUtil::messageToJson(m)); - }; - - for_each(filtered_msgs.begin(), filtered_msgs.end(), each); - - LoggerD("Calling:%s with:%d updated messages", MESSAGESUPDATED, - filtered_msgs.size()); +void MessagesChangeCallback::added(const MessagePtrVector& msgs) { + LoggerD("Entered num messages: %d", msgs.size()); + if (!m_is_act) { + return; + } + MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); + // cancel callback only if filter did remove all messages + // if callback was called with empty msgs list, call it + if (msgs.size() > 0 && filtered_msgs.size() == 0) { + LoggerD("All messages were filtered out, not calling callback"); + return; + } + + picojson::array array; + auto each = [&array](std::shared_ptr m) -> void { + array.push_back(MessagingUtil::messageToJson(m)); + }; + + for_each(filtered_msgs.begin(), filtered_msgs.end(), each); + + LoggerD("Calling:%s with:%d added messages", MESSAGESADDED, filtered_msgs.size()); + + m_callback_data.SetAction(MESSAGESADDED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::MEDIUM); +} - m_callback_data.SetAction(MESSAGESUPDATED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LOW); +void MessagesChangeCallback::updated(const MessagePtrVector& msgs) { + LoggerD("Entered num messages: %d", msgs.size()); + if (!m_is_act) { + return; + } + MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); + // cancel callback only if filter did remove all messages + // if callback was called with empty msgs list, call it + if (msgs.size() > 0 && filtered_msgs.size() == 0) { + LoggerD("All messages were filtered out, not calling callback"); + return; + } + + picojson::array array; + auto each = [&array](std::shared_ptr m) -> void { + array.push_back(MessagingUtil::messageToJson(m)); + }; + + for_each(filtered_msgs.begin(), filtered_msgs.end(), each); + + LoggerD("Calling:%s with:%d updated messages", MESSAGESUPDATED, filtered_msgs.size()); + + m_callback_data.SetAction(MESSAGESUPDATED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LOW); } -void MessagesChangeCallback::removed(const MessagePtrVector& msgs) -{ - LoggerD("Enter event: msgs.size() = %d", msgs.size()); - if (!m_is_act) { - return; - } +void MessagesChangeCallback::removed(const MessagePtrVector& msgs) { + LoggerD("Enter event: msgs.size() = %d", msgs.size()); + if (!m_is_act) { + return; + } - MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); - //cancel callback only if filter did remove all messages - //if callback was called with empty msgs list, call it - if (msgs.size() > 0 && filtered_msgs.size() == 0) { - LoggerD("All messages were filtered out, not calling callback"); - return; - } + MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id); + // cancel callback only if filter did remove all messages + // if callback was called with empty msgs list, call it + if (msgs.size() > 0 && filtered_msgs.size() == 0) { + LoggerD("All messages were filtered out, not calling callback"); + return; + } - picojson::array array; - auto each = [&array] (std::shared_ptr m)->void { - array.push_back(MessagingUtil::messageToJson(m)); - }; + picojson::array array; + auto each = [&array](std::shared_ptr m) -> void { + array.push_back(MessagingUtil::messageToJson(m)); + }; - for_each(filtered_msgs.begin(), filtered_msgs.end(), each); + for_each(filtered_msgs.begin(), filtered_msgs.end(), each); - LoggerD("Calling:%s with:%d removed messages", MESSAGESREMOVED, - filtered_msgs.size()); + LoggerD("Calling:%s with:%d removed messages", MESSAGESREMOVED, filtered_msgs.size()); - m_callback_data.SetAction(MESSAGESREMOVED, picojson::value(array)); - m_callback_data.AddAndPost(PostPriority::LAST); + m_callback_data.SetAction(MESSAGESREMOVED, picojson::value(array)); + m_callback_data.AddAndPost(PostPriority::LAST); } -void MessagesChangeCallback::setFilter(tizen::AbstractFilterPtr filter) -{ - m_filter = filter; +void MessagesChangeCallback::setFilter(tizen::AbstractFilterPtr filter) { + m_filter = filter; } -AbstractFilterPtr MessagesChangeCallback::getFilter() const -{ - return m_filter; +AbstractFilterPtr MessagesChangeCallback::getFilter() const { + return m_filter; } -int MessagesChangeCallback::getServiceId() const -{ - return m_service_id; +int MessagesChangeCallback::getServiceId() const { + return m_service_id; } -MessageType MessagesChangeCallback::getServiceType() const -{ - return m_msg_type; +MessageType MessagesChangeCallback::getServiceType() const { + return m_msg_type; } void MessagesChangeCallback::setActive(bool act) { - m_is_act = act; + m_is_act = act; } bool MessagesChangeCallback::isActive() { - return m_is_act; + return m_is_act; } -void MessagesChangeCallback::setItems(MessagePtrVector& items) -{ - m_items = items; +void MessagesChangeCallback::setItems(MessagePtrVector& items) { + m_items = items; } -MessagePtrVector MessagesChangeCallback::getItems() -{ - return m_items; +MessagePtrVector MessagesChangeCallback::getItems() { + return m_items; } - -} //namespace messaging -} //namespace extension +} // namespace messaging +} // namespace extension diff --git a/src/messaging/messages_change_callback.h b/src/messaging/messages_change_callback.h old mode 100755 new mode 100644 index 6e19fdd..64343cb --- a/src/messaging/messages_change_callback.h +++ b/src/messaging/messages_change_callback.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __TIZEN_MESSAGES_CHANGE_CALLBACK_H__ #define __TIZEN_MESSAGES_CHANGE_CALLBACK_H__ @@ -24,8 +24,8 @@ #include "MsgCommon/AbstractFilter.h" #include "message.h" -#include "messaging_util.h" #include "messages_callback_user_data.h" +#include "messaging_util.h" namespace extension { namespace messaging { @@ -35,46 +35,41 @@ extern const char* MESSAGESUPDATED; extern const char* MESSAGESREMOVED; class MessagesChangeCallback { -public: - typedef void(MessagesChangeCallback::*Signature)(const MessagePtrVector& conversations); - - MessagesChangeCallback( - long cid, - int service_id, - MessageType service_type, - PostQueue& queue); - virtual ~MessagesChangeCallback(); - - void added(const MessagePtrVector& messages); - void updated(const MessagePtrVector& messages); - void removed(const MessagePtrVector& messages); - - void setFilter(tizen::AbstractFilterPtr filter); - tizen::AbstractFilterPtr getFilter() const; - - int getServiceId() const; - MessageType getServiceType() const; - static MessagePtrVector filterMessages( - tizen::AbstractFilterPtr a_filter, - const MessagePtrVector& a_sourceMessages, - const int service_id); - - void setActive(bool act); - bool isActive(); - - void setItems(MessagePtrVector& items); - MessagePtrVector getItems(); -private: - MessagesCallbackUserData m_callback_data; - tizen::AbstractFilterPtr m_filter; - int m_service_id; - MessageType m_msg_type; - bool m_is_act; - MessagePtrVector m_items; + public: + typedef void (MessagesChangeCallback::*Signature)(const MessagePtrVector& conversations); + + MessagesChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue); + virtual ~MessagesChangeCallback(); + + void added(const MessagePtrVector& messages); + void updated(const MessagePtrVector& messages); + void removed(const MessagePtrVector& messages); + + void setFilter(tizen::AbstractFilterPtr filter); + tizen::AbstractFilterPtr getFilter() const; + + int getServiceId() const; + MessageType getServiceType() const; + static MessagePtrVector filterMessages(tizen::AbstractFilterPtr a_filter, + const MessagePtrVector& a_sourceMessages, + const int service_id); + + void setActive(bool act); + bool isActive(); + + void setItems(MessagePtrVector& items); + MessagePtrVector getItems(); + + private: + MessagesCallbackUserData m_callback_data; + tizen::AbstractFilterPtr m_filter; + int m_service_id; + MessageType m_msg_type; + bool m_is_act; + MessagePtrVector m_items; }; -} //namespace messaging -} //namespace extension - +} // namespace messaging +} // namespace extension -#endif // __TIZEN_MESSAGES_CHANGE_CALLBACK_H__ +#endif // __TIZEN_MESSAGES_CHANGE_CALLBACK_H__ diff --git a/src/messaging/messaging_database_manager.cc b/src/messaging/messaging_database_manager.cc old mode 100755 new mode 100644 index 793ea10..7e57bc7 --- a/src/messaging/messaging_database_manager.cc +++ b/src/messaging/messaging_database_manager.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include -#include #include -#include -#include +#include #include +#include #include +#include +#include -#include #include +#include #include #include "common/logger.h" @@ -39,962 +39,923 @@ using namespace extension::tizen; namespace extension { namespace messaging { -AttributeInfo::AttributeInfo() : - sql_name(), - sql_type(UNDEFINED_TYPE), - any_type(PrimitiveType_NoType) -{ - LoggerD("Entered"); +AttributeInfo::AttributeInfo() + : sql_name(), sql_type(UNDEFINED_TYPE), any_type(PrimitiveType_NoType) { + LoggerD("Entered"); } -AttributeInfo::AttributeInfo(const std::string& in_sql_name, - const SQLAttributeType in_sql_type, - const tizen::PrimitiveType in_any_type) : - sql_name(in_sql_name), - sql_type(in_sql_type), - any_type(in_any_type) -{ - LoggerD("Entered"); +AttributeInfo::AttributeInfo(const std::string& in_sql_name, const SQLAttributeType in_sql_type, + const tizen::PrimitiveType in_any_type) + : sql_name(in_sql_name), sql_type(in_sql_type), any_type(in_any_type) { + LoggerD("Entered"); } -AttributeInfo::AttributeInfo(const AttributeInfo& other) : - sql_name(other.sql_name), - sql_type(other.sql_type), - any_type(other.any_type) -{ - LoggerD("Entered"); +AttributeInfo::AttributeInfo(const AttributeInfo& other) + : sql_name(other.sql_name), sql_type(other.sql_type), any_type(other.any_type) { + LoggerD("Entered"); } -AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other) -{ - sql_name = other.any_type; - sql_type = other.sql_type; - any_type = other.any_type; - return *this; +AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other) { + sql_name = other.any_type; + sql_type = other.sql_type; + any_type = other.any_type; + return *this; } -MessagingDatabaseManager::MessagingDatabaseManager() -{ - LoggerD("Entered"); -// Attributes map for short messages ========================================== - m_msg_attr_map.insert(std::make_pair("id", - AttributeInfo("A.MSG_ID", INTEGER, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("serviceId", - AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("folderId", - AttributeInfo("A.FOLDER_ID", INTEGER, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("type", - AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("timestamp", - AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time))); - m_msg_attr_map.insert(std::make_pair("from", - AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("to", - AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("body.plainBody", - AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("isRead", - AttributeInfo("A.READ_STATUS", INTEGER, PrimitiveType_Boolean))); - m_msg_attr_map.insert(std::make_pair("hasAttachment", - AttributeInfo("A.ATTACHMENT_COUNT", INTEGER, PrimitiveType_Boolean))); - m_msg_attr_map.insert(std::make_pair("isHighPriority", - AttributeInfo("A.PRIORITY", INTEGER, PrimitiveType_Boolean))); - m_msg_attr_map.insert(std::make_pair("subject", - AttributeInfo("A.SUBJECT", TEXT, PrimitiveType_String))); - m_msg_attr_map.insert(std::make_pair("direction", - AttributeInfo("A.MSG_DIRECTION", INTEGER, PrimitiveType_String))); - -// Attributes map for emails ================================================== - m_email_attr_map.insert(std::make_pair("id", - AttributeInfo("mail_id", INTEGER, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("serviceId", - AttributeInfo("account_id", INTEGER, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("folderId", - AttributeInfo("mailbox_id", INTEGER, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("type", - AttributeInfo("account_id", INTEGER, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("timestamp", - AttributeInfo("date_time", DATETIME, PrimitiveType_Time))); - m_email_attr_map.insert(std::make_pair("from", - AttributeInfo("full_address_from", TEXT, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("to", - AttributeInfo("full_address_to", TEXT, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("cc", - AttributeInfo("full_address_cc", TEXT, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("bcc", - AttributeInfo("full_address_bcc", TEXT, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("body.plainBody", - AttributeInfo("preview_text", TEXT, PrimitiveType_String))); - m_email_attr_map.insert(std::make_pair("isRead", - AttributeInfo("flags_seen_field", BOOLEAN, PrimitiveType_Boolean))); - m_email_attr_map.insert(std::make_pair("hasAttachment", - AttributeInfo("attachment_count", INTEGER, PrimitiveType_Boolean))); - m_email_attr_map.insert(std::make_pair("isHighPriority", - AttributeInfo("priority", INTEGER, PrimitiveType_Boolean))); - m_email_attr_map.insert(std::make_pair("subject", - AttributeInfo("subject", TEXT, PrimitiveType_String))); - -// Attributes map for short message conversations ============================= - m_msg_conv_attr_map.insert(std::make_pair("id", - AttributeInfo("A.CONV_ID", INTEGER, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("type", - AttributeInfo("B.MAIN_TYPE", INTEGER, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("timestamp", - AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time))); - m_msg_conv_attr_map.insert(std::make_pair("messageCount", - AttributeInfo("(A.SMS_CNT + A.MMS_CNT)", INTEGER, PrimitiveType_ULong))); - m_msg_conv_attr_map.insert(std::make_pair("unreadMessages", - AttributeInfo("A.UNREAD_CNT", INTEGER, PrimitiveType_ULong))); - m_msg_conv_attr_map.insert(std::make_pair("preview", - AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("from", - AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("to", - AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("msgId", - AttributeInfo("B.MSG_ID", INTEGER, PrimitiveType_String))); - m_msg_conv_attr_map.insert(std::make_pair("direction", - AttributeInfo("B.MSG_DIRECTION", INTEGER, PrimitiveType_String))); - -// Attributes map for email conversations ===================================== - m_email_conv_attr_map.insert(std::make_pair("id", - AttributeInfo("thread_id", INTEGER, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("serviceId", - AttributeInfo("account_id", INTEGER, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("type", - AttributeInfo("account_id", INTEGER, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("timestamp", - AttributeInfo("date_time", DATETIME, PrimitiveType_Time))); - m_email_conv_attr_map.insert(std::make_pair("messageCount", - AttributeInfo("thread_item_count", INTEGER, PrimitiveType_ULong))); - m_email_conv_attr_map.insert(std::make_pair("unreadMessages", - AttributeInfo(std::string("thread_id IN (SELECT thread_id ") - + std::string("FROM mail_tbl WHERE flags_seen_field = 0 ") - + std::string("GROUP BY thread_id HAVING COUNT(thread_id)"), - INTEGER, - PrimitiveType_ULong))); - m_email_conv_attr_map.insert(std::make_pair("preview", - AttributeInfo("preview_text", TEXT, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("subject", - AttributeInfo("subject", TEXT, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("from", - AttributeInfo("full_address_from", TEXT, PrimitiveType_String))); - m_email_conv_attr_map.insert(std::make_pair("to", - AttributeInfo("full_address_to", TEXT, PrimitiveType_String))); +MessagingDatabaseManager::MessagingDatabaseManager() { + LoggerD("Entered"); + // Attributes map for short messages ========================================== + m_msg_attr_map.insert( + std::make_pair("id", AttributeInfo("A.MSG_ID", INTEGER, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("serviceId", AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("folderId", AttributeInfo("A.FOLDER_ID", INTEGER, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("type", AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("timestamp", AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time))); + m_msg_attr_map.insert( + std::make_pair("from", AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("to", AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("body.plainBody", AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("isRead", AttributeInfo("A.READ_STATUS", INTEGER, PrimitiveType_Boolean))); + m_msg_attr_map.insert(std::make_pair( + "hasAttachment", AttributeInfo("A.ATTACHMENT_COUNT", INTEGER, PrimitiveType_Boolean))); + m_msg_attr_map.insert(std::make_pair( + "isHighPriority", AttributeInfo("A.PRIORITY", INTEGER, PrimitiveType_Boolean))); + m_msg_attr_map.insert( + std::make_pair("subject", AttributeInfo("A.SUBJECT", TEXT, PrimitiveType_String))); + m_msg_attr_map.insert( + std::make_pair("direction", AttributeInfo("A.MSG_DIRECTION", INTEGER, PrimitiveType_String))); + + // Attributes map for emails ================================================== + m_email_attr_map.insert( + std::make_pair("id", AttributeInfo("mail_id", INTEGER, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("serviceId", AttributeInfo("account_id", INTEGER, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("folderId", AttributeInfo("mailbox_id", INTEGER, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("type", AttributeInfo("account_id", INTEGER, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("timestamp", AttributeInfo("date_time", DATETIME, PrimitiveType_Time))); + m_email_attr_map.insert( + std::make_pair("from", AttributeInfo("full_address_from", TEXT, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("to", AttributeInfo("full_address_to", TEXT, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("cc", AttributeInfo("full_address_cc", TEXT, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("bcc", AttributeInfo("full_address_bcc", TEXT, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("body.plainBody", AttributeInfo("preview_text", TEXT, PrimitiveType_String))); + m_email_attr_map.insert( + std::make_pair("isRead", AttributeInfo("flags_seen_field", BOOLEAN, PrimitiveType_Boolean))); + m_email_attr_map.insert(std::make_pair( + "hasAttachment", AttributeInfo("attachment_count", INTEGER, PrimitiveType_Boolean))); + m_email_attr_map.insert( + std::make_pair("isHighPriority", AttributeInfo("priority", INTEGER, PrimitiveType_Boolean))); + m_email_attr_map.insert( + std::make_pair("subject", AttributeInfo("subject", TEXT, PrimitiveType_String))); + + // Attributes map for short message conversations ============================= + m_msg_conv_attr_map.insert( + std::make_pair("id", AttributeInfo("A.CONV_ID", INTEGER, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("type", AttributeInfo("B.MAIN_TYPE", INTEGER, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("timestamp", AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time))); + m_msg_conv_attr_map.insert(std::make_pair( + "messageCount", AttributeInfo("(A.SMS_CNT + A.MMS_CNT)", INTEGER, PrimitiveType_ULong))); + m_msg_conv_attr_map.insert(std::make_pair( + "unreadMessages", AttributeInfo("A.UNREAD_CNT", INTEGER, PrimitiveType_ULong))); + m_msg_conv_attr_map.insert( + std::make_pair("preview", AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("from", AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("to", AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("msgId", AttributeInfo("B.MSG_ID", INTEGER, PrimitiveType_String))); + m_msg_conv_attr_map.insert( + std::make_pair("direction", AttributeInfo("B.MSG_DIRECTION", INTEGER, PrimitiveType_String))); + + // Attributes map for email conversations ===================================== + m_email_conv_attr_map.insert( + std::make_pair("id", AttributeInfo("thread_id", INTEGER, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("serviceId", AttributeInfo("account_id", INTEGER, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("type", AttributeInfo("account_id", INTEGER, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("timestamp", AttributeInfo("date_time", DATETIME, PrimitiveType_Time))); + m_email_conv_attr_map.insert(std::make_pair( + "messageCount", AttributeInfo("thread_item_count", INTEGER, PrimitiveType_ULong))); + m_email_conv_attr_map.insert(std::make_pair( + "unreadMessages", AttributeInfo(std::string("thread_id IN (SELECT thread_id ") + + std::string("FROM mail_tbl WHERE flags_seen_field = 0 ") + + std::string("GROUP BY thread_id HAVING COUNT(thread_id)"), + INTEGER, PrimitiveType_ULong))); + m_email_conv_attr_map.insert( + std::make_pair("preview", AttributeInfo("preview_text", TEXT, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("subject", AttributeInfo("subject", TEXT, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("from", AttributeInfo("full_address_from", TEXT, PrimitiveType_String))); + m_email_conv_attr_map.insert( + std::make_pair("to", AttributeInfo("full_address_to", TEXT, PrimitiveType_String))); } -MessagingDatabaseManager::~MessagingDatabaseManager() -{ - LoggerD("Entered"); +MessagingDatabaseManager::~MessagingDatabaseManager() { + LoggerD("Entered"); } -MessagingDatabaseManager& MessagingDatabaseManager::getInstance() -{ - LoggerD("Entered"); - static MessagingDatabaseManager instance; - return instance; +MessagingDatabaseManager& MessagingDatabaseManager::getInstance() { + LoggerD("Entered"); + static MessagingDatabaseManager instance; + return instance; } __thread sqlite3* sqlHandle = NULL; __thread sqlite3_stmt* stmt = NULL; -msg_error_t MessagingDatabaseManager::connect() -{ - LoggerD("Entered"); - if (NULL == sqlHandle) { - char strDBName[64]; - - memset(strDBName, 0x00, sizeof(strDBName)); - snprintf(strDBName, sizeof(strDBName), "%s/%s", - tzplatform_getenv(TZ_SYS_GLOBALUSER_DB), MSG_DB_NAME); +msg_error_t MessagingDatabaseManager::connect() { + LoggerD("Entered"); + if (NULL == sqlHandle) { + char strDBName[64]; - // this should match MSGFW_DB_NAME defined in msg-service/include/utils/MsgSqliteWrapper.h - SLoggerD("Using database: [%s]", strDBName); + memset(strDBName, 0x00, sizeof(strDBName)); + snprintf(strDBName, sizeof(strDBName), "%s/%s", tzplatform_getenv(TZ_SYS_GLOBALUSER_DB), + MSG_DB_NAME); - int err = db_util_open(strDBName, &sqlHandle, DB_UTIL_REGISTER_HOOK_METHOD); + // this should match MSGFW_DB_NAME defined in msg-service/include/utils/MsgSqliteWrapper.h + SLoggerD("Using database: [%s]", strDBName); - if (SQLITE_OK != err) { - LoggerE("Failed to connect to database '%s', error: [%d]", strDBName, err); - sqlHandle = nullptr; - return MSG_ERR_DB_CONNECT; - } + int err = db_util_open(strDBName, &sqlHandle, DB_UTIL_REGISTER_HOOK_METHOD); - LoggerD("DB connecting success: [%d]", sqlHandle); - } else { - LoggerD("DB connection exists: [%d]", sqlHandle); + if (SQLITE_OK != err) { + LoggerE("Failed to connect to database '%s', error: [%d]", strDBName, err); + sqlHandle = nullptr; + return MSG_ERR_DB_CONNECT; } - return MSG_SUCCESS; -} + LoggerD("DB connecting success: [%d]", sqlHandle); + } else { + LoggerD("DB connection exists: [%d]", sqlHandle); + } -msg_error_t MessagingDatabaseManager::disconnect() -{ - LoggerD("Entered"); - msg_error_t err = 0; - if (NULL != sqlHandle) { - err = db_util_close(sqlHandle); + return MSG_SUCCESS; +} - if (SQLITE_OK != err) { - LoggerE("DB disconnecting fail [%d]", err); - return MSG_ERR_DB_DISCONNECT; - } +msg_error_t MessagingDatabaseManager::disconnect() { + LoggerD("Entered"); + msg_error_t err = 0; + if (NULL != sqlHandle) { + err = db_util_close(sqlHandle); - sqlHandle = NULL; - LoggerD("DB disconnecting success"); + if (SQLITE_OK != err) { + LoggerE("DB disconnecting fail [%d]", err); + return MSG_ERR_DB_DISCONNECT; } - return MSG_SUCCESS; + sqlHandle = NULL; + LoggerD("DB disconnecting success"); + } + + return MSG_SUCCESS; } -msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery, - char*** results, - int* resultsCount) -{ - LoggerD("Entered"); - msg_error_t err = 0; - *resultsCount = 0; +msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery, char*** results, + int* resultsCount) { + LoggerD("Entered"); + msg_error_t err = 0; + *resultsCount = 0; - freeTable(results); + freeTable(results); - if (MSG_SUCCESS != connect()) { - LoggerE("Failed to connect to database."); - return MSG_ERR_DB_CONNECT; - } + if (MSG_SUCCESS != connect()) { + LoggerE("Failed to connect to database."); + return MSG_ERR_DB_CONNECT; + } - char* error_msg = NULL; - err = sqlite3_get_table(sqlHandle, sqlQuery.c_str(), results, - resultsCount, 0, &error_msg); + char* error_msg = NULL; + err = sqlite3_get_table(sqlHandle, sqlQuery.c_str(), results, resultsCount, 0, &error_msg); - if (SQLITE_OK != err) { - LoggerE("Getting table fail [%d] error_msg:%s querry was:%s", err, error_msg, - sqlQuery.c_str()); - freeTable(results); - return MSG_ERR_DB_GETTABLE; - } + if (SQLITE_OK != err) { + LoggerE("Getting table fail [%d] error_msg:%s querry was:%s", err, error_msg, sqlQuery.c_str()); + freeTable(results); + return MSG_ERR_DB_GETTABLE; + } - LoggerD("Getting table success"); - if (0 == *resultsCount) { - LoggerD("No results"); - } + LoggerD("Getting table success"); + if (0 == *resultsCount) { + LoggerD("No results"); + } - disconnect(); - return MSG_SUCCESS; + disconnect(); + return MSG_SUCCESS; } -void MessagingDatabaseManager::freeTable(char*** results) -{ - LoggerD("Entered"); - if (*results) { - sqlite3_free_table(*results); - *results = NULL; - } +void MessagingDatabaseManager::freeTable(char*** results) { + LoggerD("Entered"); + if (*results) { + sqlite3_free_table(*results); + *results = NULL; + } } -int MessagingDatabaseManager::cellToInt(char** array, int cellId) -{ - LoggerD("Entered"); - if (NULL == array) { - LoggerD("Array is NULL"); - return 0; - } +int MessagingDatabaseManager::cellToInt(char** array, int cellId) { + LoggerD("Entered"); + if (NULL == array) { + LoggerD("Array is NULL"); + return 0; + } - char* tmp = *(array + cellId); - if (NULL == tmp) { - LoggerD("Cell is NULL"); - return 0; - } + char* tmp = *(array + cellId); + if (NULL == tmp) { + LoggerD("Cell is NULL"); + return 0; + } - return static_cast(strtol(tmp, (char**) NULL, 10)); + return static_cast(strtol(tmp, (char**)NULL, 10)); } std::string MessagingDatabaseManager::getMatchString(tizen::AnyPtr match_value, - const PrimitiveType type) const -{ - LoggerD("Entered"); - if(!match_value) { - LoggerD("Warning: match value is NULL"); - return std::string(); - } - - std::ostringstream converter; - switch(type) { - case PrimitiveType_NoType: { - LoggerD("Warning: match value is no type"); - return std::string(); - } - case PrimitiveType_Null: { - LoggerD("Warning: match value is null"); - return std::string(); - } - case PrimitiveType_Boolean: { - converter << match_value->toBool(); - return converter.str(); - } - case PrimitiveType_Long: { - converter << match_value->toLong(); - return converter.str(); - } - case PrimitiveType_ULong: { - converter << match_value->toULong(); - return converter.str(); - } - case PrimitiveType_LongLong: { - converter << match_value->toLongLong(); - return converter.str(); - } - case PrimitiveType_ULongLong: { - converter << match_value->toULongLong(); - return converter.str(); - } - case PrimitiveType_Double: { - converter << match_value->toDouble(); - return converter.str(); - } - case PrimitiveType_String: { - return match_value->toString(); - } - case PrimitiveType_Time: { - converter << match_value->toTimeT(); - return converter.str(); - } - default: { - LoggerD("Warning: match value is not specified"); - return std::string(); - } - } + const PrimitiveType type) const { + LoggerD("Entered"); + if (!match_value) { + LoggerD("Warning: match value is NULL"); + return std::string(); + } + + std::ostringstream converter; + switch (type) { + case PrimitiveType_NoType: { + LoggerD("Warning: match value is no type"); + return std::string(); + } + case PrimitiveType_Null: { + LoggerD("Warning: match value is null"); + return std::string(); + } + case PrimitiveType_Boolean: { + converter << match_value->toBool(); + return converter.str(); + } + case PrimitiveType_Long: { + converter << match_value->toLong(); + return converter.str(); + } + case PrimitiveType_ULong: { + converter << match_value->toULong(); + return converter.str(); + } + case PrimitiveType_LongLong: { + converter << match_value->toLongLong(); + return converter.str(); + } + case PrimitiveType_ULongLong: { + converter << match_value->toULongLong(); + return converter.str(); + } + case PrimitiveType_Double: { + converter << match_value->toDouble(); + return converter.str(); + } + case PrimitiveType_String: { + return match_value->toString(); + } + case PrimitiveType_Time: { + converter << match_value->toTimeT(); + return converter.str(); + } + default: { + LoggerD("Warning: match value is not specified"); + return std::string(); + } + } } PlatformResult MessagingDatabaseManager::getAttributeFilterQuery(AbstractFilterPtr filter, - AttributeInfoMap& attribute_map, MessageType msgType, std::string* result) -{ - LoggerD("Entered"); - - std::ostringstream sqlQuery; - AttributeFilterPtr attr_filter = castToAttributeFilter(filter); - if(!attr_filter) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Wrong filter type - not attribute filter", - ("passed filter is not valid AttributeFilter!")); - } - - const std::string attribute_name = attr_filter->getAttributeName(); - AttributeInfoMap::iterator it = attribute_map.find(attribute_name); - - if (it != attribute_map.end()) { - sqlQuery << "(" << attribute_map[attribute_name].sql_name << " "; + AttributeInfoMap& attribute_map, + MessageType msgType, + std::string* result) { + LoggerD("Entered"); + + std::ostringstream sqlQuery; + AttributeFilterPtr attr_filter = castToAttributeFilter(filter); + if (!attr_filter) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Wrong filter type - not attribute filter", + ("passed filter is not valid AttributeFilter!")); + } + + const std::string attribute_name = attr_filter->getAttributeName(); + AttributeInfoMap::iterator it = attribute_map.find(attribute_name); + + if (it != attribute_map.end()) { + sqlQuery << "(" << attribute_map[attribute_name].sql_name << " "; + } else { + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "The attribute does not exist.", + ("The attribute: %s does not exist.", attribute_name.c_str())); + } + + AnyPtr match_value_any_ptr = attr_filter->getMatchValue(); + const AttributeInfo& attr_info = it->second; + std::string match_value = getMatchString(match_value_any_ptr, attr_info.any_type); + const FilterMatchFlag match_flag = attr_filter->getMatchFlag(); + + LoggerD("match_value_any_ptr:%p any_type:%d attr_name:%s match_value:%s", + match_value_any_ptr.get(), attr_info.any_type, attribute_name.c_str(), + match_value.c_str()); + + if ("serviceId" == attribute_name) { + LoggerD("Attribute name: serviceId"); + + int i_matchValue; + std::istringstream iss(match_value); + iss >> i_matchValue; + + switch (i_matchValue) { + case MessageServiceAccountId::SMS_ACCOUNT_ID: { + sqlQuery << "= " << MessageType::SMS; + break; + } + case MessageServiceAccountId::MMS_ACCOUNT_ID: { + sqlQuery << "= " << MessageType::MMS; + break; + } + default: + sqlQuery << "= " << match_value; + } + } else if ("type" == attribute_name) { + LoggerD("Attribute name: type"); + if ("messaging.sms" == match_value && MessageType::SMS == msgType) { + sqlQuery << "= " << msgType; + } else if ("messaging.mms" == match_value && MessageType::MMS == msgType) { + sqlQuery << "= " << msgType; + } else if ("messaging.email" == match_value && MessageType::EMAIL == msgType) { + sqlQuery << "= " << attr_info.sql_name; } else { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "The attribute does not exist.", - ("The attribute: %s does not exist.", attribute_name.c_str())); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "The value does not match service type.", + ("attribute \"type\" matchValue:%s " + "does not match messaging.sms/mms/email\n" + "msgType:%d does not match SMS(%d), MMS(%d) nor EMAIL(%d)!", + match_value.c_str(), msgType, MessageType::SMS, MessageType::MMS, MessageType::EMAIL)); + } + } else if ("isRead" == attribute_name || "hasAttachment" == attribute_name) { + LoggerD("Attribute name: isRead or hasAttachment"); + if (attr_filter->getMatchValue()->toBool()) { + sqlQuery << "> 0"; + } else { + sqlQuery << "= 0"; } + } else if ("isHighPriority" == attribute_name) { + LoggerD("Attribute name: isHighPriority"); + if (attr_filter->getMatchValue()->toBool()) { + sqlQuery << "= "; + } else { + sqlQuery << "<> "; + } + + if (MessageType::SMS == msgType || MessageType::MMS == msgType) { + sqlQuery << MSG_MESSAGE_PRIORITY_HIGH; + } else if (MessageType::EMAIL == msgType) { + sqlQuery << EMAIL_MAIL_PRIORITY_HIGH; + } + } else { + LoggerD("Another attribute"); + // Addresses which are stored in database can have different form than in filters + if (MessageType::EMAIL == msgType && ("from" == attribute_name || "to" == attribute_name || + "cc" == attribute_name || "bcc" == attribute_name)) { + std::size_t foundPos; + while ((foundPos = match_value.find('<')) != std::string::npos) { + match_value.erase(foundPos, 1); + } + + while ((foundPos = match_value.find('>')) != std::string::npos) { + match_value.erase(foundPos, 1); + } + + if (EXACTLY == match_flag) { + match_value = "%<" + match_value + ">%"; + } else if (CONTAINS == match_flag) { + match_value = "%<%" + match_value + "%>%"; + } else if (STARTSWITH == match_flag) { + match_value = "%<" + match_value + "%>%"; + } else if (ENDSWITH == match_flag) { + match_value = "%<%" + match_value + ">%"; + } + } else if ("folderId" == attribute_name && + (MessageType::SMS == msgType || MessageType::MMS == msgType)) { + LoggerD("Non-email folder ID"); + + // need to convert from values presented to user to _MSG_FOLDER_ID_E + auto folder_id = attr_filter->getMatchValue()->toLong(); + switch (folder_id) { + case 1: + folder_id = MSG_INBOX_ID; + break; + + case 2: + folder_id = MSG_OUTBOX_ID; + break; + + case 3: + folder_id = MSG_DRAFT_ID; + break; + + case 4: + folder_id = MSG_SENTBOX_ID; + break; - AnyPtr match_value_any_ptr = attr_filter->getMatchValue(); - const AttributeInfo& attr_info = it->second; - std::string match_value = getMatchString(match_value_any_ptr, attr_info.any_type); - const FilterMatchFlag match_flag = attr_filter->getMatchFlag(); - - LoggerD("match_value_any_ptr:%p any_type:%d attr_name:%s match_value:%s", - match_value_any_ptr.get(), attr_info.any_type, attribute_name.c_str(), - match_value.c_str()); - - if ("serviceId" == attribute_name) { - LoggerD("Attribute name: serviceId"); - - int i_matchValue; - std::istringstream iss(match_value); - iss >> i_matchValue; - - switch(i_matchValue) { - case MessageServiceAccountId::SMS_ACCOUNT_ID: { - sqlQuery << "= " << MessageType::SMS; - break; - } - case MessageServiceAccountId::MMS_ACCOUNT_ID: { - sqlQuery << "= " << MessageType::MMS; - break; - } default: - sqlQuery << "= " << match_value; - } - } - else if ("type" == attribute_name) { - LoggerD("Attribute name: type"); - if ("messaging.sms" == match_value && MessageType::SMS == msgType) { - sqlQuery << "= " << msgType; - } else if ("messaging.mms" == match_value && MessageType::MMS == msgType) { - sqlQuery << "= " << msgType; - } else if ("messaging.email" == match_value && MessageType::EMAIL == msgType) { - sqlQuery << "= " << attr_info.sql_name; - } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The value does not match service type.", - ("attribute \"type\" matchValue:%s " - "does not match messaging.sms/mms/email\n" - "msgType:%d does not match SMS(%d), MMS(%d) nor EMAIL(%d)!", - match_value.c_str(), msgType, MessageType::SMS, MessageType::MMS, - MessageType::EMAIL)); - } - } - else if ("isRead" == attribute_name || "hasAttachment" == attribute_name) { - LoggerD("Attribute name: isRead or hasAttachment"); - if (attr_filter->getMatchValue()->toBool()) { - sqlQuery << "> 0"; + LoggerE("Unexpected folder ID: %d", folder_id); + folder_id = -1; + break; + } + + match_value = std::to_string(folder_id); + } + + switch (match_flag) { + /* + case NONE: { + // Determines if the apostrophes have to be added over match value + if (TEXT == attribute_map[attribute_name].sql_type) { + sqlQuery << "NOT LIKE '" << match_value << "'"; + } else { + sqlQuery << "<> " << match_value; + } + break; + }*/ + case EXACTLY: { + // Determines if the apostrophes have to be added over match value + if (TEXT == attribute_map[attribute_name].sql_type) { + sqlQuery << "LIKE '" << match_value << "'"; } else { - sqlQuery << "= 0"; - } - } - else if ("isHighPriority" == attribute_name) { - LoggerD("Attribute name: isHighPriority"); - if (attr_filter->getMatchValue()->toBool()) { - sqlQuery << "= "; + sqlQuery << "= " << match_value; + } + break; + } + case CONTAINS: { + sqlQuery << "LIKE '%" << match_value << "%'"; + break; + } + case STARTSWITH: { + sqlQuery << "LIKE '" << match_value << "%'"; + break; + } + case ENDSWITH: { + sqlQuery << "LIKE '%" << match_value << "'"; + break; + } + case EXISTS: { + if ("unreadMessages" != attribute_name) { + sqlQuery << "IS NOT NULL"; } else { - sqlQuery << "<> "; - } - - if (MessageType::SMS == msgType || MessageType::MMS == msgType) { - sqlQuery << MSG_MESSAGE_PRIORITY_HIGH; - } else if (MessageType::EMAIL == msgType) { - sqlQuery << EMAIL_MAIL_PRIORITY_HIGH; - } - } - else { - LoggerD("Another attribute"); - // Addresses which are stored in database can have different form than in filters - if (MessageType::EMAIL == msgType && ("from" == attribute_name || - "to" == attribute_name || "cc" == attribute_name || - "bcc" == attribute_name)) { - std::size_t foundPos; - while ((foundPos = match_value.find('<')) != std::string::npos) { - match_value.erase(foundPos, 1); - } - - while ((foundPos = match_value.find('>')) != std::string::npos) { - match_value.erase(foundPos, 1); - } - - if (EXACTLY == match_flag) { - match_value = "%<" + match_value + ">%"; - } else if (CONTAINS == match_flag) { - match_value = "%<%" + match_value + "%>%"; - } else if (STARTSWITH == match_flag) { - match_value = "%<" + match_value + "%>%"; - } else if (ENDSWITH == match_flag) { - match_value = "%<%" + match_value + ">%"; - } - } else if ("folderId" == attribute_name && - (MessageType::SMS == msgType || MessageType::MMS == msgType)) { - LoggerD("Non-email folder ID"); - - // need to convert from values presented to user to _MSG_FOLDER_ID_E - auto folder_id = attr_filter->getMatchValue()->toLong(); - switch (folder_id) { - case 1: - folder_id = MSG_INBOX_ID; - break; - - case 2: - folder_id = MSG_OUTBOX_ID; - break; - - case 3: - folder_id = MSG_DRAFT_ID; - break; - - case 4: - folder_id = MSG_SENTBOX_ID; - break; - - default: - LoggerE("Unexpected folder ID: %d", folder_id); - folder_id = -1; - break; - } - - match_value = std::to_string(folder_id); - } - - switch (match_flag) { - /* - case NONE: { - // Determines if the apostrophes have to be added over match value - if (TEXT == attribute_map[attribute_name].sql_type) { - sqlQuery << "NOT LIKE '" << match_value << "'"; - } else { - sqlQuery << "<> " << match_value; - } - break; - }*/ - case EXACTLY: { - // Determines if the apostrophes have to be added over match value - if (TEXT == attribute_map[attribute_name].sql_type) { - sqlQuery << "LIKE '" << match_value << "'"; - } else { - sqlQuery << "= " << match_value; - } - break; - } - case CONTAINS: { - sqlQuery << "LIKE '%" << match_value << "%'"; - break; - } - case STARTSWITH: { - sqlQuery << "LIKE '" << match_value << "%'"; - break; - } - case ENDSWITH: { - sqlQuery << "LIKE '%" << match_value << "'"; - break; - } - case EXISTS: { - if ("unreadMessages" != attribute_name) { - sqlQuery << "IS NOT NULL"; - } else { - sqlQuery << "!= 0"; - } - break; - } - default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The match flag is incorrect.", - ("The match flag is incorrect: %d", match_flag)); - } - - if (MessageType::SMS == msgType || MessageType::MMS == msgType) { - if ("from" == attribute_name) { - // "From" and "to" attributes require message direction value - sqlQuery << " AND " << attribute_map["direction"].sql_name << " = 1"; - } else if ("to" == attribute_name) { - sqlQuery << " AND " << attribute_map["direction"].sql_name << " <> 1"; - } - } else if (MessageType::EMAIL == msgType) { - if("unreadMessages" == attribute_name) { - sqlQuery << ")"; - } - } - } - sqlQuery << ") "; - *result = sqlQuery.str(); - return PlatformResult(ErrorCode::NO_ERROR); + sqlQuery << "!= 0"; + } + break; + } + default: + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "The match flag is incorrect.", + ("The match flag is incorrect: %d", match_flag)); + } + + if (MessageType::SMS == msgType || MessageType::MMS == msgType) { + if ("from" == attribute_name) { + // "From" and "to" attributes require message direction value + sqlQuery << " AND " << attribute_map["direction"].sql_name << " = 1"; + } else if ("to" == attribute_name) { + sqlQuery << " AND " << attribute_map["direction"].sql_name << " <> 1"; + } + } else if (MessageType::EMAIL == msgType) { + if ("unreadMessages" == attribute_name) { + sqlQuery << ")"; + } + } + } + sqlQuery << ") "; + *result = sqlQuery.str(); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MessagingDatabaseManager::getAttributeRangeFilterQuery(AbstractFilterPtr filter, - AttributeInfoMap& attribute_map, MessageType msg_type, std::string* result) -{ - LoggerD("Entered"); - - std::ostringstream sql_query, converter; - std::string initial_value, end_value; - - AttributeRangeFilterPtr attr_range_filter = castToAttributeRangeFilter(filter); - if(!attr_range_filter) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Wrong filter type - not attribute range filter", - ("passed filter is not valid AttributeRangeFilter!")); - } - - converter << attr_range_filter->getInitialValue()->toTimeT(); - initial_value = converter.str(); - converter.str(""); - converter << attr_range_filter->getEndValue()->toTimeT(); - end_value = converter.str(); - - sql_query << "(" << attribute_map[attr_range_filter->getAttributeName()].sql_name << " "; - sql_query << "BETWEEN " << initial_value << " AND " << end_value << ") "; - *result = sql_query.str(); - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult MessagingDatabaseManager::getAttributeRangeFilterQuery( + AbstractFilterPtr filter, AttributeInfoMap& attribute_map, MessageType msg_type, + std::string* result) { + LoggerD("Entered"); + + std::ostringstream sql_query, converter; + std::string initial_value, end_value; + + AttributeRangeFilterPtr attr_range_filter = castToAttributeRangeFilter(filter); + if (!attr_range_filter) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Wrong filter type - not attribute range filter", + ("passed filter is not valid AttributeRangeFilter!")); + } + + converter << attr_range_filter->getInitialValue()->toTimeT(); + initial_value = converter.str(); + converter.str(""); + converter << attr_range_filter->getEndValue()->toTimeT(); + end_value = converter.str(); + + sql_query << "(" << attribute_map[attr_range_filter->getAttributeName()].sql_name << " "; + sql_query << "BETWEEN " << initial_value << " AND " << end_value << ") "; + *result = sql_query.str(); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MessagingDatabaseManager::getCompositeFilterQuery(AbstractFilterPtr filter, - AttributeInfoMap& attribute_map, MessageType msg_type, std::string* result) -{ - LoggerD("Entered"); - std::ostringstream sql_query; - - CompositeFilterPtr comp_filter = castToCompositeFilter(filter); - if(!comp_filter) { + AttributeInfoMap& attribute_map, + MessageType msg_type, + std::string* result) { + LoggerD("Entered"); + std::ostringstream sql_query; + + CompositeFilterPtr comp_filter = castToCompositeFilter(filter); + if (!comp_filter) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Wrong filter type - not composite filter", + ("passed filter is not valid CompositeFilter!")); + } + + AbstractFilterPtrVector filters_arr = comp_filter->getFilters(); + + std::string logical_operator; + if (UNION == comp_filter->getType()) { + logical_operator = "OR "; + } else { + logical_operator = "AND "; + } + + sql_query << "("; + const unsigned int size = filters_arr.size(); + for (unsigned int i = 0; i < size; ++i) { + const FilterType filter_type = filters_arr[i]->getFilterType(); + switch (filter_type) { + case ATTRIBUTE_FILTER: { + std::string query; + PlatformResult ret = + getAttributeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get attribute filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + case ATTRIBUTE_RANGE_FILTER: { + std::string query; + PlatformResult ret = + getAttributeRangeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get attribute filter range filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + case COMPOSITE_FILTER: { + std::string query; + PlatformResult ret = + getCompositeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get composite filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + default: return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Wrong filter type - not composite filter", - ("passed filter is not valid CompositeFilter!")); - } - - AbstractFilterPtrVector filters_arr = comp_filter->getFilters(); - - std::string logical_operator; - if (UNION == comp_filter->getType()) { - logical_operator = "OR "; - } else { - logical_operator = "AND "; + ErrorCode::UNKNOWN_ERR, "Error while querying message.", + ("Error while querying message - unsupported filter type: %d", filter_type)); } - sql_query << "("; - const unsigned int size = filters_arr.size(); - for (unsigned int i = 0; i < size; ++i) { - - const FilterType filter_type = filters_arr[i]->getFilterType(); - switch (filter_type) { - case ATTRIBUTE_FILTER: { - std::string query; - PlatformResult ret = getAttributeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get attribute filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - case ATTRIBUTE_RANGE_FILTER: { - std::string query; - PlatformResult ret = getAttributeRangeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get attribute filter range filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - case COMPOSITE_FILTER: { - std::string query; - PlatformResult ret = getCompositeFilterQuery(filters_arr[i], attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get composite filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while querying message.", - ("Error while querying message - unsupported filter type: %d", filter_type)); - } - - if (i != (size - 1)) { - sql_query << logical_operator; - } + if (i != (size - 1)) { + sql_query << logical_operator; } - sql_query << ") "; + } + sql_query << ") "; - *result = sql_query.str(); - return PlatformResult(ErrorCode::NO_ERROR); + *result = sql_query.str(); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MessagingDatabaseManager::addFilters(AbstractFilterPtr filter, - SortModePtr sort_mode, long limit, long offset, AttributeInfoMap& attribute_map, - MessageType msg_type, std::string* result) -{ - LoggerD("Entered"); - std::ostringstream sql_query; - - // Service type query - if (MessageType::SMS == msg_type || MessageType::MMS == msg_type) { - sql_query << attribute_map["type"].sql_name << " = " << msg_type << " AND "; - } - - if(filter) { - // Filter query - switch (filter->getFilterType()) { - case ATTRIBUTE_FILTER: { - std::string query; - PlatformResult ret = getAttributeFilterQuery(filter, attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get attribute filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - case ATTRIBUTE_RANGE_FILTER: { - std::string query; - PlatformResult ret = getAttributeRangeFilterQuery(filter, attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get attribute range filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - case COMPOSITE_FILTER : { - std::string query; - PlatformResult ret = getCompositeFilterQuery(filter, attribute_map, msg_type, &query); - if (ret.IsError()) { - LoggerE("Get composite filter query failed (%s)", ret.message().c_str()); - return ret; - } - sql_query << query; - break; - } - default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "The filter type is incorrect.", - ("The filter type is incorrect: %d", filter->getFilterType())); - } - } - - // SortMode query - if (sort_mode) { - if (attribute_map.find(sort_mode->getAttributeName()) != attribute_map.end()) { - sql_query << "ORDER BY " - << attribute_map[sort_mode->getAttributeName()].sql_name << " "; - } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "The attribute does not exist."); - } - - if (ASC == sort_mode->getOrder()) { - sql_query << "ASC "; - } else { - sql_query << "DESC "; - } - } - - // Limit query - if (0 != limit) { - sql_query << "LIMIT " << limit << " "; - } - - // Offset query - if (0 != offset) { - if( 0 == limit ) { - //Ugly fix proposed by mySQL team: - //http://dev.mysql.com/doc/refman/5.0/en/select.html - //To retrieve all rows from a certain offset up to the end of the result set, - //you can use some large number for the second parameter. - // - //Reason: to use OFFSET you need to have LIMIT statement - //18446744073709551615 is 2^64-1 - max value of big int - //However we will use -1 since it will work fine for various int sizes (this - //trick have been used in old implementation). - - sql_query << "LIMIT -1 "; - } - sql_query << "OFFSET " << offset << " "; +PlatformResult MessagingDatabaseManager::addFilters(AbstractFilterPtr filter, SortModePtr sort_mode, + long limit, long offset, + AttributeInfoMap& attribute_map, + MessageType msg_type, std::string* result) { + LoggerD("Entered"); + std::ostringstream sql_query; + + // Service type query + if (MessageType::SMS == msg_type || MessageType::MMS == msg_type) { + sql_query << attribute_map["type"].sql_name << " = " << msg_type << " AND "; + } + + if (filter) { + // Filter query + switch (filter->getFilterType()) { + case ATTRIBUTE_FILTER: { + std::string query; + PlatformResult ret = getAttributeFilterQuery(filter, attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get attribute filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + case ATTRIBUTE_RANGE_FILTER: { + std::string query; + PlatformResult ret = getAttributeRangeFilterQuery(filter, attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get attribute range filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + case COMPOSITE_FILTER: { + std::string query; + PlatformResult ret = getCompositeFilterQuery(filter, attribute_map, msg_type, &query); + if (ret.IsError()) { + LoggerE("Get composite filter query failed (%s)", ret.message().c_str()); + return ret; + } + sql_query << query; + break; + } + default: + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "The filter type is incorrect.", + ("The filter type is incorrect: %d", filter->getFilterType())); + } + } + + // SortMode query + if (sort_mode) { + if (attribute_map.find(sort_mode->getAttributeName()) != attribute_map.end()) { + sql_query << "ORDER BY " << attribute_map[sort_mode->getAttributeName()].sql_name << " "; + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "The attribute does not exist."); } - *result = sql_query.str(); - return PlatformResult(ErrorCode::NO_ERROR); + if (ASC == sort_mode->getOrder()) { + sql_query << "ASC "; + } else { + sql_query << "DESC "; + } + } + + // Limit query + if (0 != limit) { + sql_query << "LIMIT " << limit << " "; + } + + // Offset query + if (0 != offset) { + if (0 == limit) { + // Ugly fix proposed by mySQL team: + // http://dev.mysql.com/doc/refman/5.0/en/select.html + // To retrieve all rows from a certain offset up to the end of the result set, + // you can use some large number for the second parameter. + // + // Reason: to use OFFSET you need to have LIMIT statement + // 18446744073709551615 is 2^64-1 - max value of big int + // However we will use -1 since it will work fine for various int sizes (this + // trick have been used in old implementation). + + sql_query << "LIMIT -1 "; + } + sql_query << "OFFSET " << offset << " "; + } + + *result = sql_query.str(); + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MessagingDatabaseManager::findShortMessages( - FindMsgCallbackUserData* callback, std::vector* result) -{ - LoggerD("Entered"); - std::ostringstream sqlQuery; - int attributesCount = 1; // It has to be set manually each time when the query is changed - int cellId = attributesCount; - char** results = NULL; - int resultsCount; - std::vector messagesIds; - - sqlQuery << "SELECT " << "DISTINCT(" << m_msg_attr_map["id"].sql_name << ") " - << "FROM " << MSG_MESSAGE_TABLE_NAME << " A " - << "JOIN " << MSG_ADDRESS_TABLE_NAME << " B " - << "ON A.CONV_ID = B.CONV_ID " << "WHERE B.ADDRESS_ID <> 0 AND "; - - // Adding filters query - AbstractFilterPtr filter = callback->getFilter(); - SortModePtr sortMode = callback->getSortMode(); - long limit = callback->getLimit(); - long offset = callback->getOffset(); - MessageType msgType = callback->getMessageServiceType(); - - std::string filters_query; - PlatformResult ret = addFilters(filter, sortMode, limit, offset, m_msg_attr_map, - msgType, &filters_query); - if (ret.IsError()) { - LoggerE("Add filters failed (%s)", ret.message().c_str()); - return ret; - } - sqlQuery << filters_query; - LoggerD("%s", sqlQuery.str().c_str()); - - // Getting results from database - msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount); - if (MSG_SUCCESS != err) { - freeTable(&results); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", - ("getTable error: %d (%s)", err, get_error_message(err))); - } - - for (int i = 0; i < resultsCount; ++i) { - messagesIds.push_back(cellToInt(results, cellId++)); - LoggerD("id: %d", messagesIds.at(messagesIds.size() - 1)); - } - +PlatformResult MessagingDatabaseManager::findShortMessages(FindMsgCallbackUserData* callback, + std::vector* result) { + LoggerD("Entered"); + std::ostringstream sqlQuery; + int attributesCount = 1; // It has to be set manually each time when the query is changed + int cellId = attributesCount; + char** results = NULL; + int resultsCount; + std::vector messagesIds; + + sqlQuery << "SELECT " + << "DISTINCT(" << m_msg_attr_map["id"].sql_name << ") " + << "FROM " << MSG_MESSAGE_TABLE_NAME << " A " + << "JOIN " << MSG_ADDRESS_TABLE_NAME << " B " + << "ON A.CONV_ID = B.CONV_ID " + << "WHERE B.ADDRESS_ID <> 0 AND "; + + // Adding filters query + AbstractFilterPtr filter = callback->getFilter(); + SortModePtr sortMode = callback->getSortMode(); + long limit = callback->getLimit(); + long offset = callback->getOffset(); + MessageType msgType = callback->getMessageServiceType(); + + std::string filters_query; + PlatformResult ret = + addFilters(filter, sortMode, limit, offset, m_msg_attr_map, msgType, &filters_query); + if (ret.IsError()) { + LoggerE("Add filters failed (%s)", ret.message().c_str()); + return ret; + } + sqlQuery << filters_query; + LoggerD("%s", sqlQuery.str().c_str()); + + // Getting results from database + msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount); + if (MSG_SUCCESS != err) { freeTable(&results); - *result = messagesIds; - return PlatformResult(ErrorCode::NO_ERROR); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", + ("getTable error: %d (%s)", err, get_error_message(err))); + } + + for (int i = 0; i < resultsCount; ++i) { + messagesIds.push_back(cellToInt(results, cellId++)); + LoggerD("id: %d", messagesIds.at(messagesIds.size() - 1)); + } + + freeTable(&results); + *result = messagesIds; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult MessagingDatabaseManager::findEmails( - FindMsgCallbackUserData* callback, std::pair* result) -{ - LoggerD("Entered"); - std::ostringstream sqlWhereClause; - int resultsCount; - email_mail_data_t* results; - - // Adding filters query - AbstractFilterPtr filter = callback->getFilter(); - SortModePtr sortMode = callback->getSortMode(); - long limit = callback->getLimit(); - long offset = callback->getOffset(); - MessageType msgType = callback->getMessageServiceType(); - int accountId = callback->getAccountId(); - - std::string filters_query; - PlatformResult ret = addFilters(filter, sortMode, limit, offset, - m_email_attr_map, msgType, &filters_query); - if (ret.IsError()) { - LoggerE("Add filters failed (%s)", ret.message().c_str()); - return ret; - } - sqlWhereClause << "WHERE " - << m_email_attr_map["serviceId"].sql_name << " = " << accountId << " AND " - << filters_query; - LoggerD("%s", sqlWhereClause.str().c_str()); - - // Getting results from database - msg_error_t err = email_query_mails(const_cast(sqlWhereClause.str().c_str()), - &results, &resultsCount); - if (EMAIL_ERROR_NONE != err) { - LoggerE("Getting mail list fail [%d]", err); - - if (EMAIL_ERROR_MAIL_NOT_FOUND == err) { - resultsCount = 0; - } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", - ("email_query_mails error: %d (%s)", err, get_error_message(err))); - } +PlatformResult MessagingDatabaseManager::findEmails(FindMsgCallbackUserData* callback, + std::pair* result) { + LoggerD("Entered"); + std::ostringstream sqlWhereClause; + int resultsCount; + email_mail_data_t* results; + + // Adding filters query + AbstractFilterPtr filter = callback->getFilter(); + SortModePtr sortMode = callback->getSortMode(); + long limit = callback->getLimit(); + long offset = callback->getOffset(); + MessageType msgType = callback->getMessageServiceType(); + int accountId = callback->getAccountId(); + + std::string filters_query; + PlatformResult ret = + addFilters(filter, sortMode, limit, offset, m_email_attr_map, msgType, &filters_query); + if (ret.IsError()) { + LoggerE("Add filters failed (%s)", ret.message().c_str()); + return ret; + } + sqlWhereClause << "WHERE " << m_email_attr_map["serviceId"].sql_name << " = " << accountId + << " AND " << filters_query; + LoggerD("%s", sqlWhereClause.str().c_str()); + + // Getting results from database + msg_error_t err = + email_query_mails(const_cast(sqlWhereClause.str().c_str()), &results, &resultsCount); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Getting mail list fail [%d]", err); + + if (EMAIL_ERROR_MAIL_NOT_FOUND == err) { + resultsCount = 0; + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", + ("email_query_mails error: %d (%s)", err, get_error_message(err))); } + } - *result = std::make_pair(resultsCount, results); - return PlatformResult(ErrorCode::NO_ERROR); + *result = std::make_pair(resultsCount, results); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MessagingDatabaseManager::findShortMessageConversations( - ConversationCallbackData* callback, std::vector* result) -{ - LoggerD("Entered"); - std::ostringstream sqlQuery; - int attributesCount = 1; // It has to be set manually each time when the query is changed - int cellId = attributesCount; - char** results = NULL; - int resultsCount; - std::vector conversationsIds; - - sqlQuery << "SELECT " << "DISTINCT(" << m_msg_conv_attr_map["id"].sql_name << ") " - << "FROM " << MSG_CONVERSATION_TABLE_NAME << " A " - << "JOIN " << MSG_MESSAGE_TABLE_NAME << " B " - << "ON A.CONV_ID = B.CONV_ID " - << "JOIN " << MSG_ADDRESS_TABLE_NAME << " C " - << "ON A.CONV_ID = C.CONV_ID " - << "WHERE (A.SMS_CNT > 0 OR A.MMS_CNT > 0) AND "; - - // Adding filters query - AbstractFilterPtr filter = callback->getFilter(); - SortModePtr sortMode = callback->getSortMode(); - long limit = callback->getLimit(); - long offset = callback->getOffset(); - MessageType msgType = callback->getMessageServiceType(); - - std::string filters_query; - PlatformResult ret = addFilters(filter, sortMode, limit, offset, m_msg_conv_attr_map, - msgType, &filters_query); - if (ret.IsError()) { - LoggerE("Add filters failed (%s)", ret.message().c_str()); - return ret; - } - sqlQuery << filters_query; - LoggerD("%s", sqlQuery.str().c_str()); - - // Getting results from database - msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount); - if (MSG_SUCCESS != err) { - freeTable(&results); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", - ("getTable error: %d (%s)", err, get_error_message(err))); - } - - for (int i = 0; i < resultsCount; ++i) { - conversationsIds.push_back(cellToInt(results, cellId++)); - LoggerD("id: %d", conversationsIds.at(conversationsIds.size() - 1)); - } - + ConversationCallbackData* callback, std::vector* result) { + LoggerD("Entered"); + std::ostringstream sqlQuery; + int attributesCount = 1; // It has to be set manually each time when the query is changed + int cellId = attributesCount; + char** results = NULL; + int resultsCount; + std::vector conversationsIds; + + sqlQuery << "SELECT " + << "DISTINCT(" << m_msg_conv_attr_map["id"].sql_name << ") " + << "FROM " << MSG_CONVERSATION_TABLE_NAME << " A " + << "JOIN " << MSG_MESSAGE_TABLE_NAME << " B " + << "ON A.CONV_ID = B.CONV_ID " + << "JOIN " << MSG_ADDRESS_TABLE_NAME << " C " + << "ON A.CONV_ID = C.CONV_ID " + << "WHERE (A.SMS_CNT > 0 OR A.MMS_CNT > 0) AND "; + + // Adding filters query + AbstractFilterPtr filter = callback->getFilter(); + SortModePtr sortMode = callback->getSortMode(); + long limit = callback->getLimit(); + long offset = callback->getOffset(); + MessageType msgType = callback->getMessageServiceType(); + + std::string filters_query; + PlatformResult ret = + addFilters(filter, sortMode, limit, offset, m_msg_conv_attr_map, msgType, &filters_query); + if (ret.IsError()) { + LoggerE("Add filters failed (%s)", ret.message().c_str()); + return ret; + } + sqlQuery << filters_query; + LoggerD("%s", sqlQuery.str().c_str()); + + // Getting results from database + msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount); + if (MSG_SUCCESS != err) { freeTable(&results); - *result = conversationsIds; - return PlatformResult(ErrorCode::NO_ERROR); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", + ("getTable error: %d (%s)", err, get_error_message(err))); + } + + for (int i = 0; i < resultsCount; ++i) { + conversationsIds.push_back(cellToInt(results, cellId++)); + LoggerD("id: %d", conversationsIds.at(conversationsIds.size() - 1)); + } + + freeTable(&results); + *result = conversationsIds; + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MessagingDatabaseManager::findEmailConversations( - ConversationCallbackData* callback, std::vector* result) -{ - LoggerD("Entered"); - std::ostringstream sqlWhereClause; - int resultsCount; - email_mail_data_t* results; - std::map conversationsBag; - std::vector conversationsInfo; - - // Adding filters query - AbstractFilterPtr filter = callback->getFilter(); - SortModePtr sortMode = callback->getSortMode(); - long limit = callback->getLimit(); - long offset = callback->getOffset(); - MessageType msgType = callback->getMessageServiceType(); - int accountId = callback->getAccountId(); - - std::string filters_query; - PlatformResult ret = addFilters(filter, sortMode, limit, offset, m_email_conv_attr_map, - msgType, &filters_query); - if (ret.IsError()) { - LoggerE("Add filters failed (%s)", ret.message().c_str()); - return ret; - } - sqlWhereClause << "WHERE " - << m_email_conv_attr_map["serviceId"].sql_name << " = " << accountId << " AND " - << filters_query; - LoggerD("%s", sqlWhereClause.str().c_str()); - - // Getting results from database - msg_error_t err = email_query_mails(const_cast(sqlWhereClause.str().c_str()), - &results, &resultsCount); - if (EMAIL_ERROR_NONE != err) { - LoggerE("Getting mail list fail [%d]", err); - - if (EMAIL_ERROR_MAIL_NOT_FOUND == err) { - resultsCount = 0; - } else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", - ("email_query_mails error: %d (%s)", err, get_error_message(err))); - } + ConversationCallbackData* callback, std::vector* result) { + LoggerD("Entered"); + std::ostringstream sqlWhereClause; + int resultsCount; + email_mail_data_t* results; + std::map conversationsBag; + std::vector conversationsInfo; + + // Adding filters query + AbstractFilterPtr filter = callback->getFilter(); + SortModePtr sortMode = callback->getSortMode(); + long limit = callback->getLimit(); + long offset = callback->getOffset(); + MessageType msgType = callback->getMessageServiceType(); + int accountId = callback->getAccountId(); + + std::string filters_query; + PlatformResult ret = + addFilters(filter, sortMode, limit, offset, m_email_conv_attr_map, msgType, &filters_query); + if (ret.IsError()) { + LoggerE("Add filters failed (%s)", ret.message().c_str()); + return ret; + } + sqlWhereClause << "WHERE " << m_email_conv_attr_map["serviceId"].sql_name << " = " << accountId + << " AND " << filters_query; + LoggerD("%s", sqlWhereClause.str().c_str()); + + // Getting results from database + msg_error_t err = + email_query_mails(const_cast(sqlWhereClause.str().c_str()), &results, &resultsCount); + if (EMAIL_ERROR_NONE != err) { + LoggerE("Getting mail list fail [%d]", err); + + if (EMAIL_ERROR_MAIL_NOT_FOUND == err) { + resultsCount = 0; + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while getting data from database.", + ("email_query_mails error: %d (%s)", err, get_error_message(err))); } + } - // Assigning found emails to conversation - for (int i = 0; i < resultsCount; ++i) { - if (conversationsBag.find(results[i].thread_id) == conversationsBag.end()) { - EmailConversationInfo info; - info.id = results[i].thread_id; - conversationsInfo.push_back(info); - conversationsBag.insert(std::make_pair(results[i].thread_id, 0)); - } - - if (!(static_cast(results[i].flags_seen_field))) { - ++conversationsBag[results[i].thread_id]; - } + // Assigning found emails to conversation + for (int i = 0; i < resultsCount; ++i) { + if (conversationsBag.find(results[i].thread_id) == conversationsBag.end()) { + EmailConversationInfo info; + info.id = results[i].thread_id; + conversationsInfo.push_back(info); + conversationsBag.insert(std::make_pair(results[i].thread_id, 0)); } - for (std::vector::iterator it = conversationsInfo.begin(); - it != conversationsInfo.end(); ++it) { - (*it).unreadMessages = conversationsBag[(*it).id]; + if (!(static_cast(results[i].flags_seen_field))) { + ++conversationsBag[results[i].thread_id]; } + } + + for (std::vector::iterator it = conversationsInfo.begin(); + it != conversationsInfo.end(); ++it) { + (*it).unreadMessages = conversationsBag[(*it).id]; + } - email_free_mail_data(&results, resultsCount); - *result = conversationsInfo; - return PlatformResult(ErrorCode::NO_ERROR); + email_free_mail_data(&results, resultsCount); + *result = conversationsInfo; + return PlatformResult(ErrorCode::NO_ERROR); } -} // Messaging -} // DeviceAPI +} // Messaging +} // DeviceAPI diff --git a/src/messaging/messaging_database_manager.h b/src/messaging/messaging_database_manager.h old mode 100755 new mode 100644 index 91977c1..a241492 --- a/src/messaging/messaging_database_manager.h +++ b/src/messaging/messaging_database_manager.h @@ -20,8 +20,8 @@ #include #include -#include #include +#include #include "MsgCommon/AbstractFilter.h" #include "common/platform_result.h" @@ -32,91 +32,92 @@ namespace extension { namespace messaging { // ================================================================= -#define MSG_DB_NAME ".msg_service.db" -#define MSG_MESSAGE_TABLE_NAME "MSG_MESSAGE_TABLE" -#define MSG_FOLDER_TABLE_NAME "MSG_FOLDER_TABLE" -#define MSG_ADDRESS_TABLE_NAME "MSG_ADDRESS_TABLE" -#define MSG_CONVERSATION_TABLE_NAME "MSG_CONVERSATION_TABLE" -#define MSG_SIM_MSG_TABLE_NAME "MSG_SIM_TABLE" -#define MSG_FILTER_TABLE_NAME "MSG_FILTER_TABLE" -#define MSG_PUSH_MSG_TABLE_NAME "MSG_PUSH_TABLE" -#define MSG_CB_MSG_TABLE_NAME "MSG_CBMSG_TABLE" -#define MMS_PLUGIN_MESSAGE_TABLE_NAME "MSG_MMS_MESSAGE_TABLE" -#define MSG_SYNCML_MSG_TABLE_NAME "MSG_SYNCML_TABLE" -#define MSG_SCHEDULED_MSG_TABLE_NAME "MSG_SCHEDULED_TABLE" -#define MSG_SMS_SENDOPT_TABLE_NAME "MSG_SMS_SENDOPT_TABLE" +#define MSG_DB_NAME ".msg_service.db" +#define MSG_MESSAGE_TABLE_NAME "MSG_MESSAGE_TABLE" +#define MSG_FOLDER_TABLE_NAME "MSG_FOLDER_TABLE" +#define MSG_ADDRESS_TABLE_NAME "MSG_ADDRESS_TABLE" +#define MSG_CONVERSATION_TABLE_NAME "MSG_CONVERSATION_TABLE" +#define MSG_SIM_MSG_TABLE_NAME "MSG_SIM_TABLE" +#define MSG_FILTER_TABLE_NAME "MSG_FILTER_TABLE" +#define MSG_PUSH_MSG_TABLE_NAME "MSG_PUSH_TABLE" +#define MSG_CB_MSG_TABLE_NAME "MSG_CBMSG_TABLE" +#define MMS_PLUGIN_MESSAGE_TABLE_NAME "MSG_MMS_MESSAGE_TABLE" +#define MSG_SYNCML_MSG_TABLE_NAME "MSG_SYNCML_TABLE" +#define MSG_SCHEDULED_MSG_TABLE_NAME "MSG_SCHEDULED_TABLE" +#define MSG_SMS_SENDOPT_TABLE_NAME "MSG_SMS_SENDOPT_TABLE" // ================================================================= enum SQLAttributeType { - UNDEFINED_TYPE, - BOOLEAN, - INTEGER, - DATETIME, - TEXT, + UNDEFINED_TYPE, + BOOLEAN, + INTEGER, + DATETIME, + TEXT, }; struct AttributeInfo { - AttributeInfo(); - AttributeInfo(const std::string& in_sql_name, - const SQLAttributeType in_sql_type, - const tizen::PrimitiveType in_any_type); - AttributeInfo(const AttributeInfo& other); - AttributeInfo& operator=(const AttributeInfo& other); - - std::string sql_name; - SQLAttributeType sql_type; - tizen::PrimitiveType any_type; + AttributeInfo(); + AttributeInfo(const std::string& in_sql_name, const SQLAttributeType in_sql_type, + const tizen::PrimitiveType in_any_type); + AttributeInfo(const AttributeInfo& other); + AttributeInfo& operator=(const AttributeInfo& other); + + std::string sql_name; + SQLAttributeType sql_type; + tizen::PrimitiveType any_type; }; typedef std::map AttributeInfoMap; struct EmailConversationInfo { - int id, unreadMessages; + int id, unreadMessages; }; // ================================================================= class MessagingDatabaseManager { -public: - static MessagingDatabaseManager& getInstance(); - common::PlatformResult findShortMessages(FindMsgCallbackUserData* callback, std::vector* result); - common::PlatformResult findEmails(FindMsgCallbackUserData* callback, - std::pair* result); - common::PlatformResult findShortMessageConversations(ConversationCallbackData* callback, - std::vector* result); - common::PlatformResult findEmailConversations(ConversationCallbackData* callback, - std::vector* result); - -private: - MessagingDatabaseManager(); - MessagingDatabaseManager(const MessagingDatabaseManager &); - void operator=(const MessagingDatabaseManager &); - virtual ~MessagingDatabaseManager(); - - msg_error_t connect(); - msg_error_t disconnect(); - msg_error_t getTable(std::string query, char*** results, int* resultsCount); - void freeTable(char*** array); - int cellToInt(char** array, int cellId); - std::string getMatchString(tizen::AnyPtr matchValue, - const tizen::PrimitiveType type) const; - common::PlatformResult getAttributeFilterQuery(tizen::AbstractFilterPtr filter, - AttributeInfoMap& attributeMap, MessageType msgType, std::string* result); - common::PlatformResult getAttributeRangeFilterQuery(tizen::AbstractFilterPtr filter, - AttributeInfoMap& attributeMap, MessageType msgType, std::string* result); - common::PlatformResult getCompositeFilterQuery(tizen::AbstractFilterPtr filter, - AttributeInfoMap& attributeMap, MessageType msgType, std::string* result); - common::PlatformResult addFilters(tizen::AbstractFilterPtr filter, - tizen::SortModePtr sortMode, long limit, long offset, - AttributeInfoMap& attributeMap, MessageType msgType, - std::string* result); - - AttributeInfoMap m_msg_attr_map; - AttributeInfoMap m_email_attr_map; - - AttributeInfoMap m_msg_conv_attr_map; - AttributeInfoMap m_email_conv_attr_map; + public: + static MessagingDatabaseManager& getInstance(); + common::PlatformResult findShortMessages(FindMsgCallbackUserData* callback, + std::vector* result); + common::PlatformResult findEmails(FindMsgCallbackUserData* callback, + std::pair* result); + common::PlatformResult findShortMessageConversations(ConversationCallbackData* callback, + std::vector* result); + common::PlatformResult findEmailConversations(ConversationCallbackData* callback, + std::vector* result); + + private: + MessagingDatabaseManager(); + MessagingDatabaseManager(const MessagingDatabaseManager&); + void operator=(const MessagingDatabaseManager&); + virtual ~MessagingDatabaseManager(); + + msg_error_t connect(); + msg_error_t disconnect(); + msg_error_t getTable(std::string query, char*** results, int* resultsCount); + void freeTable(char*** array); + int cellToInt(char** array, int cellId); + std::string getMatchString(tizen::AnyPtr matchValue, const tizen::PrimitiveType type) const; + common::PlatformResult getAttributeFilterQuery(tizen::AbstractFilterPtr filter, + AttributeInfoMap& attributeMap, + MessageType msgType, std::string* result); + common::PlatformResult getAttributeRangeFilterQuery(tizen::AbstractFilterPtr filter, + AttributeInfoMap& attributeMap, + MessageType msgType, std::string* result); + common::PlatformResult getCompositeFilterQuery(tizen::AbstractFilterPtr filter, + AttributeInfoMap& attributeMap, + MessageType msgType, std::string* result); + common::PlatformResult addFilters(tizen::AbstractFilterPtr filter, tizen::SortModePtr sortMode, + long limit, long offset, AttributeInfoMap& attributeMap, + MessageType msgType, std::string* result); + + AttributeInfoMap m_msg_attr_map; + AttributeInfoMap m_email_attr_map; + + AttributeInfoMap m_msg_conv_attr_map; + AttributeInfoMap m_email_conv_attr_map; }; -} // Messaging -} // DeviceAPI +} // Messaging +} // DeviceAPI -#endif // __TIZEN_MSG_DATABASE_MANAGER_H__ +#endif // __TIZEN_MSG_DATABASE_MANAGER_H__ diff --git a/src/messaging/messaging_extension.cc b/src/messaging/messaging_extension.cc old mode 100755 new mode 100644 index 67d0747..066e5a6 --- a/src/messaging/messaging_extension.cc +++ b/src/messaging/messaging_extension.cc @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "common/logger.h" + #include "messaging_extension.h" -#include "messaging_instance.h" +#include "common/logger.h" #include "email_manager.h" +#include "messaging_instance.h" namespace { - const char* kMessaging = "tizen.messaging"; - const char* kMessage = "tizen.Message"; - const char* kMessageAttachment = "tizen.MessageAttachment"; +const char* kMessaging = "tizen.messaging"; +const char* kMessage = "tizen.Message"; +const char* kMessageAttachment = "tizen.MessageAttachment"; } // This will be generated from messaging_api.js. extern const char kSource_messaging_api[]; @@ -37,11 +37,7 @@ MessagingExtension::MessagingExtension() { LoggerD("Entered"); SetExtensionName(kMessaging); SetJavaScriptAPI(kSource_messaging_api); - const char* entry_points[] = { - kMessage, - kMessageAttachment, - NULL - }; + const char* entry_points[] = {kMessage, kMessageAttachment, NULL}; SetExtraJSEntryPoints(entry_points); } @@ -53,8 +49,8 @@ common::Instance* MessagingExtension::CreateInstance() { LoggerD("Entered"); PlatformResult ret = extension::messaging::EmailManager::InitializeEmailService(); if (ret.IsError()) { - LoggerE("Initializing the email service failed (%s)", ret.message().c_str()); - return nullptr; + LoggerE("Initializing the email service failed (%s)", ret.message().c_str()); + return nullptr; } return new extension::messaging::MessagingInstance(); } diff --git a/src/messaging/messaging_extension.h b/src/messaging/messaging_extension.h old mode 100755 new mode 100644 index 6de078e..83c7d25 --- a/src/messaging/messaging_extension.h +++ b/src/messaging/messaging_extension.h @@ -28,5 +28,4 @@ class MessagingExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // MESSAGING_MESSAGING_EXTENSION_H_ - +#endif // MESSAGING_MESSAGING_EXTENSION_H_ diff --git a/src/messaging/messaging_instance.cc b/src/messaging/messaging_instance.cc old mode 100755 new mode 100644 index cd656a7..fb0ceec --- a/src/messaging/messaging_instance.cc +++ b/src/messaging/messaging_instance.cc @@ -16,26 +16,26 @@ #include "messaging_instance.h" +#include #include #include -#include #include "common/logger.h" #include "common/tools.h" #include "MsgCommon/AbstractFilter.h" -#include "messages_change_callback.h" #include "conversations_change_callback.h" -#include "folders_change_callback.h" -#include "messages_callback_user_data.h" +#include "email_manager.h" #include "find_msg_callback_user_data.h" #include "folders_callback_data.h" +#include "folders_change_callback.h" +#include "message.h" +#include "message_storage.h" +#include "messages_callback_user_data.h" +#include "messages_change_callback.h" #include "messaging_manager.h" #include "messaging_util.h" -#include "message_storage.h" -#include "message.h" #include "short_message_manager.h" -#include "email_manager.h" using common::ErrorCode; using common::TypeMismatchException; @@ -44,11 +44,11 @@ using common::PlatformResult; namespace extension { namespace messaging { -namespace{ +namespace { const char* FUN_GET_MESSAGE_SERVICES = "Messaging_getMessageServices"; const char* GET_MESSAGE_SERVICES_ARGS_MESSAGE_SERVICE_TYPE = "messageServiceType"; -const char* FUN_MESSAGE_SERVICE_SEND_MESSAGE = "MessageService_sendMessage"; +const char* FUN_MESSAGE_SERVICE_SEND_MESSAGE = "MessageService_sendMessage"; const char* SEND_MESSAGE_ARGS_MESSAGE = "message"; const char* SEND_MESSAGE_ARGS_SIMINDEX = "simIndex"; @@ -93,13 +93,13 @@ const char* FIND_FOLDERS_ARGS_LIMIT = "limit"; const char* FIND_FOLDERS_ARGS_OFFSET = "offset"; const char* FUN_MESSAGE_STORAGE_ADD_MESSAGES_CHANGE_LISTENER = - "MessageStorage_addMessagesChangeListener"; + "MessageStorage_addMessagesChangeListener"; const char* FUN_MESSAGE_STORAGE_ADD_CONVERSATIONS_CHANGE_LISTENER = - "MessageStorage_addConversationsChangeListener"; + "MessageStorage_addConversationsChangeListener"; const char* FUN_MESSAGE_STORAGE_ADD_FOLDER_CHANGE_LISTENER = - "MessageStorage_addFoldersChangeListener"; + "MessageStorage_addFoldersChangeListener"; const char* FUN_MESSAGE_STORAGE_REMOVE_CHANGE_LISTENER = "MessageStorage_removeChangeListener"; const char* REMOVE_CHANGE_LISTENER_ARGS_WATCHID = "watchId"; @@ -109,700 +109,668 @@ const char* FUN_MESSAGE_GET_MESSAGE_STATUS = "Message_messageStatus"; const char* FUN_MESSAGE_MESSAGING_EMAIL = "messaging.email"; auto getServiceIdFromJSON = [](picojson::object& data) -> int { - std::string serviceStrId; - try { - serviceStrId = - MessagingUtil::getValueFromJSONObject(data,FUNCTIONS_HIDDEN_ARGS_SERVICE_ID); - return std::stoi(serviceStrId); - } - catch(...) { - return -1; - } + std::string serviceStrId; + try { + serviceStrId = + MessagingUtil::getValueFromJSONObject(data, FUNCTIONS_HIDDEN_ARGS_SERVICE_ID); + return std::stoi(serviceStrId); + } catch (...) { + return -1; + } }; -const std::string kPrivilegeMessagingRead = "http://tizen.org/privilege/messaging.read"; +const std::string kPrivilegeMessagingRead = "http://tizen.org/privilege/messaging.read"; const std::string kPrivilegeMessagingWrite = "http://tizen.org/privilege/messaging.write"; -const long kDumbCallbackId= -1; +const long kDumbCallbackId = -1; } -MessagingInstance::MessagingInstance(): - manager_(*this), - queue_(*this) -{ - LoggerD("Entered"); - using std::placeholders::_1; - using std::placeholders::_2; - #define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&MessagingInstance::x, this, _1, _2)); - REGISTER_ASYNC(FUN_GET_MESSAGE_SERVICES, GetMessageServices); - REGISTER_ASYNC(FUN_MESSAGE_SERVICE_SEND_MESSAGE, MessageServiceSendMessage); - REGISTER_ASYNC(FUN_MESSAGE_SERVICE_LOAD_MESSAGE_BODY, MessageServiceLoadMessageBody); - REGISTER_ASYNC(FUN_MESSAGE_SERVICE_LOAD_MESSAGE_ATTACHMENT, MessageServiceLoadMessageAttachment); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_ADD_DRAFT_MESSAGE, MessageStorageAddDraft); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_MESSAGES, MessageStorageFindMessages); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_REMOVE_MESSAGES, MessageStorageRemoveMessages); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_UPDATE_MESSAGES, MessageStorageUpdateMessages); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_CONVERSATIONS, MessageStorageFindConversations); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_REMOVE_CONVERSATIONS, MessageStorageRemoveConversations); - REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_FOLDERS, MessageStorageFindFolders); - #undef REGISTER_ASYNC - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&MessagingInstance::x, this, _1, _2)); - REGISTER_SYNC(FUN_MESSAGE_SERVICE_SYNC, MessageServiceSync); - REGISTER_SYNC(FUN_MESSAGE_SERVICE_STOP_SYNC, MessageServiceStopSync); - REGISTER_SYNC(FUN_MESSAGE_SERVICE_SYNC_FOLDER, MessageServiceSyncFolder); - REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_MESSAGES_CHANGE_LISTENER, MessageStorageAddMessagesChangeListener); - REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_CONVERSATIONS_CHANGE_LISTENER, MessageStorageAddConversationsChangeListener); - REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_FOLDER_CHANGE_LISTENER, MessageStorageAddFolderChangeListener); - REGISTER_SYNC(FUN_MESSAGE_STORAGE_REMOVE_CHANGE_LISTENER, MessageStorageRemoveChangeListener); - REGISTER_SYNC(FUN_MESSAGE_GET_MESSAGE_STATUS, MessageGetMessageStatus); - #undef REGISTER_SYNC +MessagingInstance::MessagingInstance() : manager_(*this), queue_(*this) { + LoggerD("Entered"); + using std::placeholders::_1; + using std::placeholders::_2; +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&MessagingInstance::x, this, _1, _2)); + REGISTER_ASYNC(FUN_GET_MESSAGE_SERVICES, GetMessageServices); + REGISTER_ASYNC(FUN_MESSAGE_SERVICE_SEND_MESSAGE, MessageServiceSendMessage); + REGISTER_ASYNC(FUN_MESSAGE_SERVICE_LOAD_MESSAGE_BODY, MessageServiceLoadMessageBody); + REGISTER_ASYNC(FUN_MESSAGE_SERVICE_LOAD_MESSAGE_ATTACHMENT, MessageServiceLoadMessageAttachment); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_ADD_DRAFT_MESSAGE, MessageStorageAddDraft); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_MESSAGES, MessageStorageFindMessages); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_REMOVE_MESSAGES, MessageStorageRemoveMessages); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_UPDATE_MESSAGES, MessageStorageUpdateMessages); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_CONVERSATIONS, MessageStorageFindConversations); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_REMOVE_CONVERSATIONS, MessageStorageRemoveConversations); + REGISTER_ASYNC(FUN_MESSAGE_STORAGE_FIND_FOLDERS, MessageStorageFindFolders); +#undef REGISTER_ASYNC +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&MessagingInstance::x, this, _1, _2)); + REGISTER_SYNC(FUN_MESSAGE_SERVICE_SYNC, MessageServiceSync); + REGISTER_SYNC(FUN_MESSAGE_SERVICE_STOP_SYNC, MessageServiceStopSync); + REGISTER_SYNC(FUN_MESSAGE_SERVICE_SYNC_FOLDER, MessageServiceSyncFolder); + REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_MESSAGES_CHANGE_LISTENER, + MessageStorageAddMessagesChangeListener); + REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_CONVERSATIONS_CHANGE_LISTENER, + MessageStorageAddConversationsChangeListener); + REGISTER_SYNC(FUN_MESSAGE_STORAGE_ADD_FOLDER_CHANGE_LISTENER, + MessageStorageAddFolderChangeListener); + REGISTER_SYNC(FUN_MESSAGE_STORAGE_REMOVE_CHANGE_LISTENER, MessageStorageRemoveChangeListener); + REGISTER_SYNC(FUN_MESSAGE_GET_MESSAGE_STATUS, MessageGetMessageStatus); +#undef REGISTER_SYNC } -MessagingInstance::~MessagingInstance() -{ - LoggerD("Entered"); +MessagingInstance::~MessagingInstance() { + LoggerD("Entered"); } -#define POST_AND_RETURN(ret, json, obj) \ - LogAndReportError(ret, &obj); \ - queue_.addAndResolve( \ - obj.at(JSON_CALLBACK_ID).get(), \ - PostPriority::HIGH, \ - json->serialize() \ - ); \ - return; +#define POST_AND_RETURN(ret, json, obj) \ + LogAndReportError(ret, &obj); \ + queue_.addAndResolve(obj.at(JSON_CALLBACK_ID).get(), PostPriority::HIGH, \ + json->serialize()); \ + return; -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - std::string message = std::string(name) + " is required argument";\ - LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, message), &out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + std::string message = std::string(name) + " is required argument"; \ + LogAndReportError(PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, message), &out); \ + return; \ + } -void MessagingInstance::GetMessageServices(const picojson::value& args, - picojson::object& out) -{ +void MessagingInstance::GetMessageServices(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::value serviceTag = args.get(). - at(GET_MESSAGE_SERVICES_ARGS_MESSAGE_SERVICE_TYPE); + picojson::value serviceTag = + args.get().at(GET_MESSAGE_SERVICES_ARGS_MESSAGE_SERVICE_TYPE); const double callbackId = args.get(JSON_CALLBACK_ID).get(); // above values should be validated in js manager_.getMessageServices(serviceTag.to_str(), callbackId); } void MessagingInstance::MessageServiceSendMessage(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); - - picojson::object data = args.get(); - picojson::value v_message = data.at(SEND_MESSAGE_ARGS_MESSAGE); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object& out) { + LoggerD("Entered"); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } + picojson::object data = args.get(); + picojson::value v_message = data.at(SEND_MESSAGE_ARGS_MESSAGE); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - MessageRecipientsCallbackData* callback = new MessageRecipientsCallbackData(queue_, callbackId); - long simIndex = 0; - int serviceId = 0; - - callback->setMessage(message); - serviceId = getServiceIdFromJSON(data); - callback->setAccountId(serviceId); - simIndex = static_cast - (MessagingUtil::getValueFromJSONObject(data,SEND_MESSAGE_ARGS_SIMINDEX)); - - bool cell_support = false; - system_info_get_platform_bool("http://tizen.org/feature/network.telephony", &cell_support); - if (cell_support) { - LoggerD("cell_support is true"); - if (!callback->setSimIndex(simIndex)) { - delete callback; - callback = nullptr; - POST_AND_RETURN(PlatformResult(ErrorCode::UNKNOWN_ERR, "set sim index failed"), - json, obj) - } - } else { - LoggerD("cell_support is false"); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } + + MessageRecipientsCallbackData* callback = new MessageRecipientsCallbackData(queue_, callbackId); + long simIndex = 0; + int serviceId = 0; + + callback->setMessage(message); + serviceId = getServiceIdFromJSON(data); + callback->setAccountId(serviceId); + simIndex = static_cast( + MessagingUtil::getValueFromJSONObject(data, SEND_MESSAGE_ARGS_SIMINDEX)); + + bool cell_support = false; + system_info_get_platform_bool("http://tizen.org/feature/network.telephony", &cell_support); + if (cell_support) { + LoggerD("cell_support is true"); + if (!callback->setSimIndex(simIndex)) { + delete callback; + callback = nullptr; + POST_AND_RETURN(PlatformResult(ErrorCode::UNKNOWN_ERR, "set sim index failed"), json, obj) } + } else { + LoggerD("cell_support is false"); + } - callback->AddToQueue(); - auto service = manager_.getMessageService(serviceId); + callback->AddToQueue(); + auto service = manager_.getMessageService(serviceId); - ret = service->sendMessage(callback); - if (!ret) { - POST_AND_RETURN(ret, json, obj) - } + ret = service->sendMessage(callback); + if (!ret) { + POST_AND_RETURN(ret, json, obj) + } } void MessagingInstance::MessageServiceLoadMessageBody(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); + picojson::object data = args.get(); - picojson::value json_message = data.at(ADD_DRAFT_MESSAGE_ARGS_MESSAGE); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::value json_message = data.at(ADD_DRAFT_MESSAGE_ARGS_MESSAGE); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(json_message, &message); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(json_message, &message); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } - MessageBodyCallbackData* callback = new MessageBodyCallbackData(queue_, callbackId); + MessageBodyCallbackData* callback = new MessageBodyCallbackData(queue_, callbackId); - callback->setMessage(message); + callback->setMessage(message); - callback->AddToQueue(); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - ret = service->loadMessageBody(callback); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } + callback->AddToQueue(); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + ret = service->loadMessageBody(callback); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } } void MessagingInstance::MessageServiceLoadMessageAttachment(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); - - picojson::object data = args.get(); - picojson::value attachment = data.at(LOAD_MESSAGE_ATTACHMENT_ARGS_ATTACHMENT); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); - - MessageAttachmentCallbackData* callback = new MessageAttachmentCallbackData(queue_, callbackId); - callback->setMessageAttachment(MessagingUtil::jsonToMessageAttachment(attachment)); - - callback->AddToQueue(); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - const auto result = service->loadMessageAttachment(callback); - if (result.IsError()) { - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - POST_AND_RETURN(result, json, obj) - } -} + picojson::object& out) { + LoggerD("Entered"); -void MessagingInstance::MessageServiceSync(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + picojson::object data = args.get(); + picojson::value attachment = data.at(LOAD_MESSAGE_ATTACHMENT_ARGS_ATTACHMENT); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - picojson::object data = args.get(); - picojson::value v_id = data.at(SYNC_ARGS_ID); - picojson::value v_limit = data.at(SYNC_ARGS_LIMIT); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + MessageAttachmentCallbackData* callback = new MessageAttachmentCallbackData(queue_, callbackId); + callback->setMessageAttachment(MessagingUtil::jsonToMessageAttachment(attachment)); - int id = -1; - try { - id = std::stoi(v_id.get()); - } catch(...) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, - ("Problem with MessageService")); - return; - } - long limit = 0; - if (v_limit.is()) { - limit = static_cast(v_limit.get()); - } + callback->AddToQueue(); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + const auto result = service->loadMessageAttachment(callback); + if (result.IsError()) { + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + POST_AND_RETURN(result, json, obj) + } +} - SyncCallbackData *callback = new SyncCallbackData(queue_, callbackId); - callback->setAccountId(id); - callback->setLimit(limit); +void MessagingInstance::MessageServiceSync(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); - callback->AddToQueue(); - long op_id = -1; + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - const auto result = manager_.getMessageService(id)->sync(callback, &op_id); + picojson::object data = args.get(); + picojson::value v_id = data.at(SYNC_ARGS_ID); + picojson::value v_limit = data.at(SYNC_ARGS_LIMIT); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - if (result) { - ReportSuccess(picojson::value(static_cast(op_id)), out); - } else { - LogAndReportError(result, &out); - } + int id = -1; + try { + id = std::stoi(v_id.get()); + } catch (...) { + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, + ("Problem with MessageService")); + return; + } + long limit = 0; + if (v_limit.is()) { + limit = static_cast(v_limit.get()); + } + + SyncCallbackData* callback = new SyncCallbackData(queue_, callbackId); + callback->setAccountId(id); + callback->setLimit(limit); + + callback->AddToQueue(); + long op_id = -1; + + const auto result = manager_.getMessageService(id)->sync(callback, &op_id); + + if (result) { + ReportSuccess(picojson::value(static_cast(op_id)), out); + } else { + LogAndReportError(result, &out); + } } void MessagingInstance::MessageServiceSyncFolder(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); + + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); + + picojson::object data = args.get(); + picojson::value v_id = data.at(SYNC_FOLDER_ARGS_ID); + picojson::value v_folder = data.at(SYNC_FOLDER_ARGS_FOLDER); + picojson::value v_limit = data.at(SYNC_FOLDER_ARGS_LIMIT); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + + int id = -1; + try { + id = std::stoi(v_id.get()); + } catch (...) { + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, + ("Problem with MessageService")); + return; + } + + long limit = 0; + if (v_limit.is()) { + limit = static_cast(v_limit.get()); + } + + SyncFolderCallbackData* callback = new SyncFolderCallbackData(queue_, callbackId); + callback->setAccountId(id); + callback->setMessageFolder(MessagingUtil::jsonToMessageFolder(v_folder)); + callback->setLimit(limit); + + callback->AddToQueue(); + long op_id = -1; + + const auto result = manager_.getMessageService(id)->syncFolder(callback, &op_id); + if (result) { + ReportSuccess(picojson::value(static_cast(op_id)), out); + } else { + LogAndReportError(result, &out); + } +} + +void MessagingInstance::MessageServiceStopSync(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); + CHECK_EXIST(args, STOP_SYNC_ARGS_OPID, out); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + picojson::object data = args.get(); - picojson::object data = args.get(); - picojson::value v_id = data.at(SYNC_FOLDER_ARGS_ID); - picojson::value v_folder = data.at(SYNC_FOLDER_ARGS_FOLDER); - picojson::value v_limit = data.at(SYNC_FOLDER_ARGS_LIMIT); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + if (data.find(STOP_SYNC_ARGS_ID) != data.end()) { + picojson::value v_id = data.at(STOP_SYNC_ARGS_ID); + picojson::value v_op_id = data.at(STOP_SYNC_ARGS_OPID); int id = -1; try { - id = std::stoi(v_id.get()); - } catch(...) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, - ("Problem with MessageService")); - return; + id = std::stoi(v_id.get()); + } catch (...) { + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, + ("Problem with MessageService")); + return; } - long limit = 0; - if (v_limit.is()) { - limit = static_cast(v_limit.get()); + long op_id = 0; + if (v_op_id.is()) { + op_id = static_cast(v_op_id.get()); } - SyncFolderCallbackData *callback = new SyncFolderCallbackData(queue_, callbackId); - callback->setAccountId(id); - callback->setMessageFolder(MessagingUtil::jsonToMessageFolder(v_folder)); - callback->setLimit(limit); - - callback->AddToQueue(); - long op_id = -1; + const auto result = manager_.getMessageService(id)->stopSync(op_id); - const auto result = manager_.getMessageService(id)->syncFolder(callback, &op_id); if (result) { - ReportSuccess(picojson::value(static_cast(op_id)), out); + ReportSuccess(out); } else { - LogAndReportError(result, &out); + LogAndReportError(result, &out); } + } else { + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, ("Unknown error")); + } } -void MessagingInstance::MessageServiceStopSync(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); - CHECK_EXIST(args, STOP_SYNC_ARGS_OPID, out); - - picojson::object data = args.get(); - - if (data.find(STOP_SYNC_ARGS_ID) != data.end()) { - picojson::value v_id = data.at(STOP_SYNC_ARGS_ID); - picojson::value v_op_id = data.at(STOP_SYNC_ARGS_OPID); - - int id = -1; - try { - id = std::stoi(v_id.get()); - } catch(...) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, - ("Problem with MessageService")); - return; - } - - long op_id = 0; - if (v_op_id.is()) { - op_id = static_cast(v_op_id.get()); - } - - const auto result = manager_.getMessageService(id)->stopSync(op_id); - - if (result) { - ReportSuccess(out); - } else { - LogAndReportError(result, &out); - } - } else { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR), &out, - ("Unknown error")); - } -} +void MessagingInstance::MessageStorageAddDraft(const picojson::value& args, picojson::object& out) { + LoggerD("Entered"); -void MessagingInstance::MessageStorageAddDraft(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + picojson::object data = args.get(); + picojson::value v_message = data.at(ADD_DRAFT_MESSAGE_ARGS_MESSAGE); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - picojson::object data = args.get(); - picojson::value v_message = data.at(ADD_DRAFT_MESSAGE_ARGS_MESSAGE); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } + MessageCallbackUserData* callback = new MessageCallbackUserData(queue_, callbackId); + callback->setMessage(message); - MessageCallbackUserData* callback = new MessageCallbackUserData(queue_, callbackId); - callback->setMessage(message); + int serviceId = getServiceIdFromJSON(data); + callback->setAccountId(serviceId); - int serviceId = getServiceIdFromJSON(data); - callback->setAccountId(serviceId); - - callback->AddToQueue(); - auto service = manager_.getMessageService(serviceId); - service->getMsgStorage()->addDraftMessage(callback); + callback->AddToQueue(); + auto service = manager_.getMessageService(serviceId); + service->getMsgStorage()->addDraftMessage(callback); } void MessagingInstance::MessageStorageFindMessages(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object data = args.get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } - auto sortMode = MessagingUtil::jsonToSortMode(data); + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } + auto sortMode = MessagingUtil::jsonToSortMode(data); - long limit = static_cast - (MessagingUtil::getValueFromJSONObject(data, FIND_FOLDERS_ARGS_LIMIT)); + long limit = static_cast( + MessagingUtil::getValueFromJSONObject(data, FIND_FOLDERS_ARGS_LIMIT)); - long offset = static_cast - (MessagingUtil::getValueFromJSONObject(data, FIND_FOLDERS_ARGS_OFFSET)); + long offset = static_cast( + MessagingUtil::getValueFromJSONObject(data, FIND_FOLDERS_ARGS_OFFSET)); - int serviceId = getServiceIdFromJSON(data); - auto storage = manager_.getMessageService(serviceId)->getMsgStorage(); + int serviceId = getServiceIdFromJSON(data); + auto storage = manager_.getMessageService(serviceId)->getMsgStorage(); - FindMsgCallbackUserData* callback = new FindMsgCallbackUserData(queue_, callbackId); - callback->setFilter(filter); - callback->setLimit(limit); - callback->setOffset(offset); - callback->setAccountId(serviceId); - callback->setSortMode(sortMode); + FindMsgCallbackUserData* callback = new FindMsgCallbackUserData(queue_, callbackId); + callback->setFilter(filter); + callback->setLimit(limit); + callback->setOffset(offset); + callback->setAccountId(serviceId); + callback->setSortMode(sortMode); - callback->AddToQueue(); - storage->findMessages(callback); + callback->AddToQueue(); + storage->findMessages(callback); } void MessagingInstance::MessageStorageRemoveMessages(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); - picojson::array messages = data.at(REMOVE_MESSAGES_ARGS_MESSAGES).get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object data = args.get(); + picojson::array messages = data.at(REMOVE_MESSAGES_ARGS_MESSAGES).get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - MessagesCallbackUserData* callback = new MessagesCallbackUserData(queue_, callbackId); + MessagesCallbackUserData* callback = new MessagesCallbackUserData(queue_, callbackId); - auto each = [callback] (picojson::value& v)->void { - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); - if (ret.IsSuccess()) { - callback->addMessage(message); - } - }; + auto each = [callback](picojson::value& v) -> void { + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); + if (ret.IsSuccess()) { + callback->addMessage(message); + } + }; - for_each(messages.begin(), messages.end(), each); + for_each(messages.begin(), messages.end(), each); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - callback->AddToQueue(); - service->getMsgStorage()->removeMessages(callback); + callback->AddToQueue(); + service->getMsgStorage()->removeMessages(callback); } void MessagingInstance::MessageStorageUpdateMessages(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); - picojson::value pico_messages = data.at(UPDATE_MESSAGES_ARGS_MESSAGES); - auto pico_array = pico_messages.get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object data = args.get(); + picojson::value pico_messages = data.at(UPDATE_MESSAGES_ARGS_MESSAGES); + auto pico_array = pico_messages.get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto callback = new MessagesCallbackUserData(queue_, callbackId); + auto callback = new MessagesCallbackUserData(queue_, callbackId); - std::for_each(pico_array.begin(), pico_array.end(), [&callback](picojson::value& v)->void { - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); - if (ret.IsSuccess()) { - callback->addMessage(message); - } - }); + std::for_each(pico_array.begin(), pico_array.end(), [&callback](picojson::value& v) -> void { + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); + if (ret.IsSuccess()) { + callback->addMessage(message); + } + }); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - callback->AddToQueue(); - service->getMsgStorage()->updateMessages(callback); + callback->AddToQueue(); + service->getMsgStorage()->updateMessages(callback); } void MessagingInstance::MessageStorageFindConversations(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + picojson::object& out) { + LoggerD("Entered"); - picojson::object data = args.get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + picojson::object data = args.get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } - auto sortMode = MessagingUtil::jsonToSortMode(data); - long limit = static_cast - (MessagingUtil::getValueFromJSONObject(data, FIND_CONVERSATIONS_ARGS_LIMIT)); - long offset = static_cast - (MessagingUtil::getValueFromJSONObject(data, FIND_CONVERSATIONS_ARGS_OFFSET)); - - int serviceId = getServiceIdFromJSON(data); - - ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); - callback->setFilter(filter); - callback->setLimit(limit); - callback->setOffset(offset); - callback->setAccountId(serviceId); - callback->setSortMode(sortMode); - - callback->AddToQueue(); - auto storage = manager_.getMessageService(serviceId)->getMsgStorage(); - storage->findConversations(callback); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } + auto sortMode = MessagingUtil::jsonToSortMode(data); + long limit = static_cast( + MessagingUtil::getValueFromJSONObject(data, FIND_CONVERSATIONS_ARGS_LIMIT)); + long offset = static_cast( + MessagingUtil::getValueFromJSONObject(data, FIND_CONVERSATIONS_ARGS_OFFSET)); + + int serviceId = getServiceIdFromJSON(data); + + ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); + callback->setFilter(filter); + callback->setLimit(limit); + callback->setOffset(offset); + callback->setAccountId(serviceId); + callback->setSortMode(sortMode); + + callback->AddToQueue(); + auto storage = manager_.getMessageService(serviceId)->getMsgStorage(); + storage->findConversations(callback); } void MessagingInstance::MessageStorageRemoveConversations(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); - picojson::array conversations = data.at(REMOVE_CONVERSATIONS_ARGS_CONVERSATIONS).get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object data = args.get(); + picojson::array conversations = + data.at(REMOVE_CONVERSATIONS_ARGS_CONVERSATIONS).get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); - - PlatformResult ret(ErrorCode::NO_ERROR); - for (auto it = conversations.begin(); it != conversations.end(); ++it) { - std::shared_ptr conversation; - ret = MessagingUtil::jsonToMessageConversation(*it, &conversation); - if (ret.IsError()) { - delete callback; - POST_AND_RETURN(ret, json, obj) - } - callback->addConversation(conversation); + ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); + + PlatformResult ret(ErrorCode::NO_ERROR); + for (auto it = conversations.begin(); it != conversations.end(); ++it) { + std::shared_ptr conversation; + ret = MessagingUtil::jsonToMessageConversation(*it, &conversation); + if (ret.IsError()) { + delete callback; + POST_AND_RETURN(ret, json, obj) } + callback->addConversation(conversation); + } - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - callback->AddToQueue(); - service->getMsgStorage()->removeConversations(callback); + callback->AddToQueue(); + service->getMsgStorage()->removeConversations(callback); } void MessagingInstance::MessageStorageFindFolders(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - CHECK_EXIST(args, JSON_CALLBACK_ID, out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_EXIST(args, JSON_CALLBACK_ID, out); - picojson::object data = args.get(); - const double callbackId = args.get(JSON_CALLBACK_ID).get(); + picojson::object data = args.get(); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - POST_AND_RETURN(ret, json, obj) - } + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + POST_AND_RETURN(ret, json, obj) + } - FoldersCallbackData* callback = new FoldersCallbackData(queue_, callbackId); - callback->setFilter(filter); + FoldersCallbackData* callback = new FoldersCallbackData(queue_, callbackId); + callback->setFilter(filter); - callback->AddToQueue(); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - service->getMsgStorage()->findFolders(callback); + callback->AddToQueue(); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + service->getMsgStorage()->findFolders(callback); } void MessagingInstance::MessageStorageAddMessagesChangeListener(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - picojson::object data = args.get(); + picojson::object data = args.get(); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - ReportError(ret, &out); - return; - } + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + ReportError(ret, &out); + return; + } - int serviceId = getServiceIdFromJSON(data); + int serviceId = getServiceIdFromJSON(data); - auto service = manager_.getMessageService(serviceId); + auto service = manager_.getMessageService(serviceId); - std::shared_ptr callback(new MessagesChangeCallback( - kDumbCallbackId, serviceId, service->getMsgServiceType(),queue_)); + std::shared_ptr callback( + new MessagesChangeCallback(kDumbCallbackId, serviceId, service->getMsgServiceType(), queue_)); - callback->setFilter(filter); + callback->setFilter(filter); - long op_id = service->getMsgStorage()->addMessagesChangeListener(callback); + long op_id = service->getMsgStorage()->addMessagesChangeListener(callback); - picojson::value v(static_cast(op_id)); - ReportSuccess(v, out); + picojson::value v(static_cast(op_id)); + ReportSuccess(v, out); } void MessagingInstance::MessageStorageAddConversationsChangeListener(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - picojson::object data = args.get(); + picojson::object data = args.get(); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - ReportError(ret, &out); - return; - } + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + ReportError(ret, &out); + return; + } - int serviceId = getServiceIdFromJSON(data); + int serviceId = getServiceIdFromJSON(data); - auto service = manager_.getMessageService(serviceId); + auto service = manager_.getMessageService(serviceId); - std::shared_ptr callback(new ConversationsChangeCallback( - static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); + std::shared_ptr callback(new ConversationsChangeCallback( + static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); - callback->setFilter(filter); + callback->setFilter(filter); - long op_id = service->getMsgStorage()->addConversationsChangeListener(callback); + long op_id = service->getMsgStorage()->addConversationsChangeListener(callback); - picojson::value v(static_cast(op_id)); - ReportSuccess(v, out); + picojson::value v(static_cast(op_id)); + ReportSuccess(v, out); } void MessagingInstance::MessageStorageAddFolderChangeListener(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - picojson::object data = args.get(); + picojson::object data = args.get(); - AbstractFilterPtr filter; - PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); - if (ret.IsError()) { - ReportError(ret, &out); - return; - } + AbstractFilterPtr filter; + PlatformResult ret = MessagingUtil::jsonToAbstractFilter(data, &filter); + if (ret.IsError()) { + ReportError(ret, &out); + return; + } - int serviceId = getServiceIdFromJSON(data); + int serviceId = getServiceIdFromJSON(data); - auto service = manager_.getMessageService(serviceId); + auto service = manager_.getMessageService(serviceId); - std::shared_ptr callback(new FoldersChangeCallback( - static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); + std::shared_ptr callback(new FoldersChangeCallback( + static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); - callback->setFilter(filter); + callback->setFilter(filter); - long op_id = service->getMsgStorage()->addFoldersChangeListener(callback); + long op_id = service->getMsgStorage()->addFoldersChangeListener(callback); - picojson::value v(static_cast(op_id)); - ReportSuccess(v, out); + picojson::value v(static_cast(op_id)); + ReportSuccess(v, out); } void MessagingInstance::MessageStorageRemoveChangeListener(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); - picojson::object data = args.get(); - const long watchId = static_cast( - data.at(REMOVE_CHANGE_LISTENER_ARGS_WATCHID).get()); + picojson::object data = args.get(); + const long watchId = + static_cast(data.at(REMOVE_CHANGE_LISTENER_ARGS_WATCHID).get()); - auto service = manager_.getMessageService(getServiceIdFromJSON(data)); + auto service = manager_.getMessageService(getServiceIdFromJSON(data)); - service->getMsgStorage()->removeChangeListener(watchId); - ReportSuccess(out); + service->getMsgStorage()->removeChangeListener(watchId); + ReportSuccess(out); } void MessagingInstance::MessageGetMessageStatus(const picojson::value& args, - picojson::object& out) -{ - LoggerD("Entered"); + picojson::object& out) { + LoggerD("Entered"); - picojson::object data = args.get(); - const int id = stoi(data.at("id").get()); - const std::string& type = data.at("type").get(); + picojson::object data = args.get(); + const int id = stoi(data.at("id").get()); + const std::string& type = data.at("type").get(); - std::string status; - if (FUN_MESSAGE_MESSAGING_EMAIL == type) { - status = EmailManager::getInstance().getMessageStatus(id); - } else { - status = ShortMsgManager::getInstance().getMessageStatus(id); - } + std::string status; + if (FUN_MESSAGE_MESSAGING_EMAIL == type) { + status = EmailManager::getInstance().getMessageStatus(id); + } else { + status = ShortMsgManager::getInstance().getMessageStatus(id); + } - ReportSuccess(picojson::value(status), out); + ReportSuccess(picojson::value(status), out); } -} // namespace messaging -} // namespace extension - +} // namespace messaging +} // namespace extension diff --git a/src/messaging/messaging_instance.h b/src/messaging/messaging_instance.h old mode 100755 new mode 100644 index 09b88d0..531af88 --- a/src/messaging/messaging_instance.h +++ b/src/messaging/messaging_instance.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGING_INSTANCE_H_ #define MESSAGING_MESSAGING_INSTANCE_H_ @@ -25,55 +25,40 @@ namespace extension { namespace messaging { -class MessagingInstance: public common::ParsedInstance { -public: +class MessagingInstance : public common::ParsedInstance { + public: MessagingInstance(); virtual ~MessagingInstance(); -private: - void GetMessageServices(const picojson::value& args, picojson::object& out); - void MessageServiceSendMessage(const picojson::value& args, - picojson::object& out); - void MessageServiceLoadMessageBody(const picojson::value& args, - picojson::object& out); - void MessageServiceLoadMessageAttachment(const picojson::value& args, - picojson::object& out); - void MessageServiceSync(const picojson::value& args, picojson::object& out); - void MessageServiceSyncFolder(const picojson::value& args, - picojson::object& out); - void MessageServiceStopSync(const picojson::value& args, - picojson::object& out); + private: + void GetMessageServices(const picojson::value& args, picojson::object& out); + + void MessageServiceSendMessage(const picojson::value& args, picojson::object& out); + void MessageServiceLoadMessageBody(const picojson::value& args, picojson::object& out); + void MessageServiceLoadMessageAttachment(const picojson::value& args, picojson::object& out); + void MessageServiceSync(const picojson::value& args, picojson::object& out); + void MessageServiceSyncFolder(const picojson::value& args, picojson::object& out); + void MessageServiceStopSync(const picojson::value& args, picojson::object& out); - void MessageStorageAddDraft(const picojson::value& args, - picojson::object& out); - void MessageStorageFindMessages(const picojson::value& args, - picojson::object& out); - void MessageStorageRemoveMessages(const picojson::value& args, - picojson::object& out); - void MessageStorageUpdateMessages(const picojson::value& args, - picojson::object& out); - void MessageStorageFindConversations(const picojson::value& args, - picojson::object& out); - void MessageStorageRemoveConversations(const picojson::value& args, - picojson::object& out); - void MessageStorageFindFolders(const picojson::value& args, - picojson::object& out); - void MessageStorageAddMessagesChangeListener(const picojson::value& args, - picojson::object& out); - void MessageStorageAddConversationsChangeListener(const picojson::value& args, - picojson::object& out); - void MessageStorageAddFolderChangeListener(const picojson::value& args, - picojson::object& out); - void MessageStorageRemoveChangeListener(const picojson::value& args, - picojson::object& out); - void MessageGetMessageStatus(const picojson::value& args, - picojson::object& out); + void MessageStorageAddDraft(const picojson::value& args, picojson::object& out); + void MessageStorageFindMessages(const picojson::value& args, picojson::object& out); + void MessageStorageRemoveMessages(const picojson::value& args, picojson::object& out); + void MessageStorageUpdateMessages(const picojson::value& args, picojson::object& out); + void MessageStorageFindConversations(const picojson::value& args, picojson::object& out); + void MessageStorageRemoveConversations(const picojson::value& args, picojson::object& out); + void MessageStorageFindFolders(const picojson::value& args, picojson::object& out); + void MessageStorageAddMessagesChangeListener(const picojson::value& args, picojson::object& out); + void MessageStorageAddConversationsChangeListener(const picojson::value& args, + picojson::object& out); + void MessageStorageAddFolderChangeListener(const picojson::value& args, picojson::object& out); + void MessageStorageRemoveChangeListener(const picojson::value& args, picojson::object& out); + void MessageGetMessageStatus(const picojson::value& args, picojson::object& out); - MessagingManager manager_; - PostQueue queue_; + MessagingManager manager_; + PostQueue queue_; }; -} // namespace messaging -} // namespace extension +} // namespace messaging +} // namespace extension -#endif // MESSAGING_MESSAGING_INSTANCE_H_ +#endif // MESSAGING_MESSAGING_INSTANCE_H_ diff --git a/src/messaging/messaging_manager.cc b/src/messaging/messaging_manager.cc old mode 100755 new mode 100644 index a1e0e1b..e6e9d3b --- a/src/messaging/messaging_manager.cc +++ b/src/messaging/messaging_manager.cc @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "messaging_manager.h" #include @@ -31,8 +31,8 @@ #include "common/tools.h" #include "messaging_instance.h" -#include "short_message_manager.h" #include "messaging_util.h" +#include "short_message_manager.h" using common::ErrorCode; using common::PlatformResult; @@ -46,63 +46,55 @@ namespace { const int UNDEFINED_MESSAGE_SERVICE = -1; } -MsgManagerCallbackData::MsgManagerCallbackData(MessagingInstance& instance): - json(nullptr), - services_map(nullptr), - sms_service(nullptr), - mms_service(nullptr), - instance_(instance) { - LoggerD("Entered"); +MsgManagerCallbackData::MsgManagerCallbackData(MessagingInstance& instance) + : json(nullptr), + services_map(nullptr), + sms_service(nullptr), + mms_service(nullptr), + instance_(instance) { + LoggerD("Entered"); } -MessagingManager::MessagingManager(MessagingInstance& instance): - instance_(instance) -{ - LoggerD("Entered"); - int ret = msg_open_msg_handle(&m_msg_handle); - if (ret != MSG_SUCCESS) { - LoggerE("Cannot get message handle: %d", ret); - } else { - ShortMsgManager::getInstance().registerStatusCallback(m_msg_handle); - } +MessagingManager::MessagingManager(MessagingInstance& instance) : instance_(instance) { + LoggerD("Entered"); + int ret = msg_open_msg_handle(&m_msg_handle); + if (ret != MSG_SUCCESS) { + LoggerE("Cannot get message handle: %d", ret); + } else { + ShortMsgManager::getInstance().registerStatusCallback(m_msg_handle); + } - m_sms_service = std::make_pair(UNDEFINED_MESSAGE_SERVICE, nullptr); - m_mms_service = std::make_pair(UNDEFINED_MESSAGE_SERVICE, nullptr); + m_sms_service = std::make_pair(UNDEFINED_MESSAGE_SERVICE, nullptr); + m_mms_service = std::make_pair(UNDEFINED_MESSAGE_SERVICE, nullptr); } -MessagingManager::~MessagingManager() -{ - LoggerD("Entered"); - int ret = msg_close_msg_handle(&m_msg_handle); - if (ret != MSG_SUCCESS) { - LoggerW("Cannot close message handle: %d", ret); - } +MessagingManager::~MessagingManager() { + LoggerD("Entered"); + int ret = msg_close_msg_handle(&m_msg_handle); + if (ret != MSG_SUCCESS) { + LoggerW("Cannot close message handle: %d", ret); + } - std::for_each(m_email_services.begin(), m_email_services.end(), - [](std::pair el) { - delete el.second; - } - ); - m_email_services.clear(); + std::for_each(m_email_services.begin(), m_email_services.end(), + [](std::pair el) { delete el.second; }); + m_email_services.clear(); - if (m_sms_service.second) { - delete m_sms_service.second; - } - if (m_mms_service.second) { - delete m_mms_service.second; - } + if (m_sms_service.second) { + delete m_sms_service.second; + } + if (m_mms_service.second) { + delete m_mms_service.second; + } } -static gboolean callbackCompleted(const std::shared_ptr& user_data) -{ - LoggerD("Entered"); - std::shared_ptr response = user_data->json; - common::Instance::PostMessage(&user_data->instance_, response->serialize().c_str()); - return false; +static gboolean callbackCompleted(const std::shared_ptr& user_data) { + LoggerD("Entered"); + std::shared_ptr response = user_data->json; + common::Instance::PostMessage(&user_data->instance_, response->serialize().c_str()); + return false; } -static void* getMsgServicesThread(const std::shared_ptr& user_data) -{ +static void* getMsgServicesThread(const std::shared_ptr& user_data) { LoggerD("Entered"); std::shared_ptr response = user_data->json; @@ -110,7 +102,7 @@ static void* getMsgServicesThread(const std::shared_ptr& MessageType type = MessageType::UNDEFINED; auto platform_result = MessagingUtil::stringToMessageType(user_data->type, &type); - //after extraction of input data, remove it + // after extraction of input data, remove it if (platform_result) { switch (type) { @@ -124,8 +116,8 @@ static void* getMsgServicesThread(const std::shared_ptr& MessageService* service = MessageServiceShortMsg::GetSmsMessageService(); if (!service) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "MessageService for SMS creation failed"); + platform_result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "MessageService for SMS creation failed"); } else { *(user_data->sms_service) = std::make_pair(service->getMsgServiceId(), service); @@ -149,8 +141,8 @@ static void* getMsgServicesThread(const std::shared_ptr& MessageService* service = MessageServiceShortMsg::GetMmsMessageService(); if (!service) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "MessageService for SMS creation failed"); + platform_result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "MessageService for SMS creation failed"); } else { *(user_data->mms_service) = std::make_pair(service->getMsgServiceId(), service); @@ -173,8 +165,8 @@ static void* getMsgServicesThread(const std::shared_ptr& int ntv_ret = email_get_account_list(&email_accounts, &count); if (ntv_ret != EMAIL_ERROR_NONE) { platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error during getting account list", - ("email_get_account_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Error during getting account list", + ("email_get_account_list error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } else { std::vector msgServices; @@ -185,20 +177,18 @@ static void* getMsgServicesThread(const std::shared_ptr& } name += "] "; name += email_accounts[i].incoming_server_user_name; - LoggerD("Account[%d/%d] id: %d, name: %s", i, count, - email_accounts[i].account_id, name.c_str()); + LoggerD("Account[%d/%d] id: %d, name: %s", i, count, email_accounts[i].account_id, + name.c_str()); - MessageService* service = new (std::nothrow) MessageServiceEmail(email_accounts[i].account_id, - name.c_str()); + MessageService* service = new (std::nothrow) + MessageServiceEmail(email_accounts[i].account_id, name.c_str()); if (!service) { LoggerD("message service[%d] is NULL", i); std::for_each(msgServices.begin(), msgServices.end(), - [](MessageService* service) { - delete service; - }); + [](MessageService* service) { delete service; }); msgServices.clear(); - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "MessageService for email creation failed"); + platform_result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "MessageService for email creation failed"); } else { msgServices.push_back(service); } @@ -212,16 +202,15 @@ static void* getMsgServicesThread(const std::shared_ptr& if (platform_result) { std::map& email_services = *(user_data->services_map); std::for_each(email_services.begin(), email_services.end(), - [](std::pair el) { - delete el.second; - }); + [](std::pair el) { delete el.second; }); email_services.clear(); std::vector response; std::for_each(msgServices.begin(), msgServices.end(), [&response, &email_services](MessageService* service) { response.push_back(picojson::value(service->toPicoJS())); - email_services.insert(std::pair(service->getMsgServiceId(), service)); + email_services.insert(std::pair( + service->getMsgServiceId(), service)); }); ReportSuccess(picojson::value(response), obj); } @@ -243,35 +232,33 @@ static void* getMsgServicesThread(const std::shared_ptr& return nullptr; } -void MessagingManager::getMessageServices(const std::string& type, double callbackId) -{ - LoggerD("Entered"); +void MessagingManager::getMessageServices(const std::string& type, double callbackId) { + LoggerD("Entered"); - auto json = std::shared_ptr(new picojson::value(picojson::object())); - picojson::object& obj = json->get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - auto user_data = std::shared_ptr(new MsgManagerCallbackData(instance_)); - user_data->type = type; - user_data->json = json; - user_data->services_map = &m_email_services; - user_data->sms_service = &m_sms_service; - user_data->mms_service = &m_mms_service; + auto user_data = std::shared_ptr(new MsgManagerCallbackData(instance_)); + user_data->type = type; + user_data->json = json; + user_data->services_map = &m_email_services; + user_data->sms_service = &m_sms_service; + user_data->mms_service = &m_mms_service; - common::TaskQueue::GetInstance().Queue - (getMsgServicesThread, callbackCompleted, user_data); + common::TaskQueue::GetInstance().Queue(getMsgServicesThread, + callbackCompleted, user_data); } MessageService* MessagingManager::getMessageService(const int id) { - if (id == m_sms_service.first) { - return m_sms_service.second; - } else if (id == m_mms_service.first) { - return m_mms_service.second; - } else { - return m_email_services[id]; - } + if (id == m_sms_service.first) { + return m_sms_service.second; + } else if (id == m_mms_service.first) { + return m_mms_service.second; + } else { + return m_email_services[id]; + } } -} // namespace messaging -} // namespace extension - +} // namespace messaging +} // namespace extension diff --git a/src/messaging/messaging_manager.h b/src/messaging/messaging_manager.h old mode 100755 new mode 100644 index 68e1ddb..220c23f --- a/src/messaging/messaging_manager.h +++ b/src/messaging/messaging_manager.h @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef MESSAGING_MESSAGING_MANAGER_H_ #define MESSAGING_MESSAGING_MANAGER_H_ #include -#include #include +#include #include "message_service_email.h" #include "message_service_short_msg.h" @@ -30,38 +30,37 @@ namespace messaging { class MessagingInstance; class MsgManagerCallbackData { -public: - explicit MsgManagerCallbackData(MessagingInstance& instance_); - std::string type; - std::shared_ptr json; - std::map* services_map; - std::pair* sms_service; - std::pair* mms_service; - MessagingInstance& instance_; + public: + explicit MsgManagerCallbackData(MessagingInstance& instance_); + std::string type; + std::shared_ptr json; + std::map* services_map; + std::pair* sms_service; + std::pair* mms_service; + MessagingInstance& instance_; }; class MessagingManager { -public: + public: explicit MessagingManager(MessagingInstance& instance); - MessagingManager(const MessagingManager &); + MessagingManager(const MessagingManager&); virtual ~MessagingManager(); void getMessageServices(const std::string& type, double callbackId); MessageService* getMessageService(const int id); -private: - void operator=(const MessagingManager &); + private: + void operator=(const MessagingManager&); - msg_handle_t m_msg_handle; - std::map m_email_services; - std::pair m_sms_service; - std::pair m_mms_service; + msg_handle_t m_msg_handle; + std::map m_email_services; + std::pair m_sms_service; + std::pair m_mms_service; - MessagingInstance& instance_; + MessagingInstance& instance_; }; -} // namespace messaging -} // namespace extension - -#endif // MESSAGING_MESSAGING_MANAGER_H_ +} // namespace messaging +} // namespace extension +#endif // MESSAGING_MESSAGING_MANAGER_H_ diff --git a/src/messaging/messaging_util.cc b/src/messaging/messaging_util.cc old mode 100755 new mode 100644 index f6a3c7a..73f50f0 --- a/src/messaging/messaging_util.cc +++ b/src/messaging/messaging_util.cc @@ -13,30 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include "messaging_util.h" #include +#include #include +#include #include #include -#include -#include #include +#include "message_conversation.h" #include "message_email.h" -#include "message_sms.h" #include "message_mms.h" -#include "message_conversation.h" -#include "messaging_instance.h" +#include "message_sms.h" #include "messaging/email_manager.h" +#include "messaging_instance.h" -#include "tizen/tizen.h" +#include "common/assert.h" #include "common/logger.h" #include "common/platform_exception.h" #include "common/scope_exit.h" -#include "common/assert.h" +#include "tizen/tizen.h" using common::ErrorCode; using common::PlatformResult; @@ -61,13 +61,13 @@ const char* MESSAGE_ATTRIBUTE_FOLDER_ID = "folderId"; const char* MESSAGE_ATTRIBUTE_TYPE = "type"; const char* MESSAGE_ATTRIBUTE_TIMESTAMP = "timestamp"; const char* MESSAGE_ATTRIBUTE_FROM = "from"; -const char* MESSAGE_ATTRIBUTE_TO = "to"; // used also in dictionary -const char* MESSAGE_ATTRIBUTE_CC = "cc"; // used also in dictionary -const char* MESSAGE_ATTRIBUTE_BCC = "bcc"; // used also in dictionary +const char* MESSAGE_ATTRIBUTE_TO = "to"; // used also in dictionary +const char* MESSAGE_ATTRIBUTE_CC = "cc"; // used also in dictionary +const char* MESSAGE_ATTRIBUTE_BCC = "bcc"; // used also in dictionary const char* MESSAGE_ATTRIBUTE_BODY = "body"; const char* MESSAGE_ATTRIBUTE_IS_READ = "isRead"; -const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY = "isHighPriority"; // used also in dictionary -const char* MESSAGE_ATTRIBUTE_SUBJECT = "subject"; // used also in dictionary +const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY = "isHighPriority"; // used also in dictionary +const char* MESSAGE_ATTRIBUTE_SUBJECT = "subject"; // used also in dictionary const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO = "inResponseTo"; const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS = "messageStatus"; const char* MESSAGE_ATTRIBUTE_ATTACHMENTS = "attachments"; @@ -135,83 +135,71 @@ const char* JSON_FILTER_ATTRIBUTE_RANGE_TYPE = "AttributeRangeFilter"; const char* JSON_FILTER_COMPOSITE_TYPE = "CompositeFilter"; const std::map stringToTypeMap = { - {TYPE_SMS, MessageType::SMS}, - {TYPE_MMS, MessageType::MMS}, - {TYPE_EMAIL, MessageType::EMAIL} -}; + {TYPE_SMS, MessageType::SMS}, {TYPE_MMS, MessageType::MMS}, {TYPE_EMAIL, MessageType::EMAIL}}; const std::map typeToStringMap = { - {MessageType::SMS, TYPE_SMS}, - {MessageType::MMS, TYPE_MMS}, - {MessageType::EMAIL, TYPE_EMAIL} -}; + {MessageType::SMS, TYPE_SMS}, {MessageType::MMS, TYPE_MMS}, {MessageType::EMAIL, TYPE_EMAIL}}; const std::string FOLDER_TYPE_INBOX = "INBOX"; const std::string FOLDER_TYPE_OUTBOX = "OUTBOX"; const std::string FOLDER_TYPE_DRAFTS = "DRAFTS"; const std::string FOLDER_TYPE_SENTBOX = "SENTBOX"; -} // namespace - -std::string MessagingUtil::messageFolderTypeToString(MessageFolderType type) -{ - LoggerD("Entered"); - switch(type) { - case MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX: - return FOLDER_TYPE_INBOX; - case MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX: - return FOLDER_TYPE_OUTBOX; - case MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS: - return FOLDER_TYPE_DRAFTS; - case MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX: - return FOLDER_TYPE_SENTBOX; - default: - return ""; - } +} // namespace + +std::string MessagingUtil::messageFolderTypeToString(MessageFolderType type) { + LoggerD("Entered"); + switch (type) { + case MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX: + return FOLDER_TYPE_INBOX; + case MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX: + return FOLDER_TYPE_OUTBOX; + case MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS: + return FOLDER_TYPE_DRAFTS; + case MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX: + return FOLDER_TYPE_SENTBOX; + default: + return ""; + } } -MessageFolderType MessagingUtil::stringToMessageFolderType(std::string type) -{ - LoggerD("Entered"); - if (FOLDER_TYPE_INBOX == type) { - return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; - } - if (FOLDER_TYPE_OUTBOX == type) { - return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX; - } - if (FOLDER_TYPE_DRAFTS == type) { - return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS; - } - if (FOLDER_TYPE_SENTBOX == type) { - return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX; - } - return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; +MessageFolderType MessagingUtil::stringToMessageFolderType(std::string type) { + LoggerD("Entered"); + if (FOLDER_TYPE_INBOX == type) { + return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; + } + if (FOLDER_TYPE_OUTBOX == type) { + return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX; + } + if (FOLDER_TYPE_DRAFTS == type) { + return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS; + } + if (FOLDER_TYPE_SENTBOX == type) { + return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX; + } + return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD; } -PlatformResult MessagingUtil::stringToMessageType(const std::string& str, MessageType* out) -{ +PlatformResult MessagingUtil::stringToMessageType(const std::string& str, MessageType* out) { LoggerD("Entered"); const auto it = stringToTypeMap.find(str); if (it == stringToTypeMap.end()) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Not supported type: " + str, - ("Not supported type: %s", str.c_str())); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Not supported type: " + str, + ("Not supported type: %s", str.c_str())); } else { *out = it->second; return PlatformResult(ErrorCode::NO_ERROR); } } -common::PlatformResult MessagingUtil::messageTypeToString(MessageType type, std::string* out) -{ +common::PlatformResult MessagingUtil::messageTypeToString(MessageType type, std::string* out) { LoggerD("Entered"); const auto it = typeToStringMap.find(type); if (it == typeToStringMap.end()) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Invalid MessageType", - ("Invalid MessageType: %d", type)); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid MessageType", + ("Invalid MessageType: %d", type)); } else { *out = it->second; return PlatformResult(ErrorCode::NO_ERROR); @@ -226,76 +214,71 @@ std::string MessagingUtil::messageTypeToString(MessageType type) { return type_str; } -std::string MessagingUtil::ltrim(const std::string& input) -{ - LoggerD("Entered"); - std::string str = input; - std::string::iterator i; - for (i = str.begin(); i != str.end(); ++i) { - if (!isspace(*i)) { - break; - } - } - if (i == str.end()) { - str.clear(); - } else { - str.erase(str.begin(), i); +std::string MessagingUtil::ltrim(const std::string& input) { + LoggerD("Entered"); + std::string str = input; + std::string::iterator i; + for (i = str.begin(); i != str.end(); ++i) { + if (!isspace(*i)) { + break; } - return str; + } + if (i == str.end()) { + str.clear(); + } else { + str.erase(str.begin(), i); + } + return str; } -std::string MessagingUtil::extractSingleEmailAddress(const std::string& address) -{ - LoggerD("Entered"); - std::size_t found_begin = address.rfind('<'); - std::size_t found_end = address.rfind('>'); - // if both '<' and '>' bracket found and '<' is before '>' - // then extract email address from the inside - if(found_begin != std::string::npos && - found_end != std::string::npos && - found_begin < found_end) { - return address.substr(found_begin+1, found_end-found_begin-1); - } - else { - // return unmodified source string - return address; - } +std::string MessagingUtil::extractSingleEmailAddress(const std::string& address) { + LoggerD("Entered"); + std::size_t found_begin = address.rfind('<'); + std::size_t found_end = address.rfind('>'); + // if both '<' and '>' bracket found and '<' is before '>' + // then extract email address from the inside + if (found_begin != std::string::npos && found_end != std::string::npos && + found_begin < found_end) { + return address.substr(found_begin + 1, found_end - found_begin - 1); + } else { + // return unmodified source string + return address; + } } std::vector MessagingUtil::extractEmailAddresses( - const std::vector& addresses) -{ - LoggerD("Entered"); - std::vector extractedAddresses; - for(auto it = addresses.begin(); it != addresses.end(); ++it) { - extractedAddresses.push_back(MessagingUtil::extractSingleEmailAddress(*it)); - } + const std::vector& addresses) { + LoggerD("Entered"); + std::vector extractedAddresses; + for (auto it = addresses.begin(); it != addresses.end(); ++it) { + extractedAddresses.push_back(MessagingUtil::extractSingleEmailAddress(*it)); + } - return extractedAddresses; + return extractedAddresses; } -PlatformResult MessagingUtil::loadFileContentToString(const std::string& file_path, std::string* result) -{ - LoggerD("Entered"); - std::ifstream input_file; - input_file.open(file_path, std::ios::in); - - if (input_file.is_open()) { - std::string outString; - input_file.seekg(0, std::ios::end); - outString.reserve(input_file.tellg()); - input_file.seekg(0, std::ios::beg); - - outString.assign((std::istreambuf_iterator(input_file)), - std::istreambuf_iterator()); - input_file.close(); - *result = ConvertToUtf8(file_path, outString); - } else { - std::stringstream ss_error_msg; - ss_error_msg << "Failed to open file: " << file_path; - return LogAndCreateResult(ErrorCode::IO_ERR, ss_error_msg.str().c_str()); - } - return PlatformResult(ErrorCode::NO_ERROR); +PlatformResult MessagingUtil::loadFileContentToString(const std::string& file_path, + std::string* result) { + LoggerD("Entered"); + std::ifstream input_file; + input_file.open(file_path, std::ios::in); + + if (input_file.is_open()) { + std::string outString; + input_file.seekg(0, std::ios::end); + outString.reserve(input_file.tellg()); + input_file.seekg(0, std::ios::beg); + + outString.assign((std::istreambuf_iterator(input_file)), + std::istreambuf_iterator()); + input_file.close(); + *result = ConvertToUtf8(file_path, outString); + } else { + std::stringstream ss_error_msg; + ss_error_msg << "Failed to open file: " << file_path; + return LogAndCreateResult(ErrorCode::IO_ERR, ss_error_msg.str().c_str()); + } + return PlatformResult(ErrorCode::NO_ERROR); } namespace { @@ -364,18 +347,16 @@ std::string PerformConversion(const std::string& input, const gchar* from_charse done = TRUE; break; - case E2BIG: - { - LoggerD("E2BIG"); - gsize used = outp - dest; + case E2BIG: { + LoggerD("E2BIG"); + gsize used = outp - dest; - outbuf_size *= 2; - dest = static_cast(g_realloc(dest, outbuf_size)); + outbuf_size *= 2; + dest = static_cast(g_realloc(dest, outbuf_size)); - outp = dest + used; - outbytes_remaining = outbuf_size - used - kNulTerminatorLength; - } - break; + outp = dest + used; + outbytes_remaining = outbuf_size - used - kNulTerminatorLength; + } break; case EILSEQ: if (0 == inbytes_remaining) { @@ -422,7 +403,8 @@ std::string PerformConversion(const std::string& input, const gchar* from_charse } // namespace -std::string MessagingUtil::ConvertToUtf8(const std::string& file_path, const std::string& contents) { +std::string MessagingUtil::ConvertToUtf8(const std::string& file_path, + const std::string& contents) { LoggerD("Entered"); // in case of messages, encoding of the file contents is stored as its filename @@ -483,883 +465,817 @@ std::string MessagingUtil::ConvertToUtf8(const std::string& file_path, const std } std::string MessagingUtil::messageStatusToString(MessageStatus status) { - LoggerD("Converting MessageStatus %d to string.", (int)status); - switch(status) { - case STATUS_SENT: - return SENT; - case STATUS_SENDING: - return SENDING; - case STATUS_FAILED: - return FAILED; - case STATUS_DRAFT: - return DRAFT; - default: - // According to Web API documentation: If the status of the current - // message does not correspond to any item from the list, an empty - // value is returned. - LoggerD("Unsupported or undefined MessageStatus"); - return ""; - } + LoggerD("Converting MessageStatus %d to string.", (int)status); + switch (status) { + case STATUS_SENT: + return SENT; + case STATUS_SENDING: + return SENDING; + case STATUS_FAILED: + return FAILED; + case STATUS_DRAFT: + return DRAFT; + default: + // According to Web API documentation: If the status of the current + // message does not correspond to any item from the list, an empty + // value is returned. + LoggerD("Unsupported or undefined MessageStatus"); + return ""; + } } -picojson::value MessagingUtil::messageBodyToJson(std::shared_ptr body) -{ - LoggerD("Entered"); - picojson::object b; - b[MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID] = picojson::value(std::to_string(body->getMessageId())); - b[MESSAGE_BODY_ATTRIBUTE_LOADED] = picojson::value(body->getLoaded()); - b[MESSAGE_BODY_ATTRIBUTE_PLAIN_BODY] = picojson::value(body->getPlainBody()); - b[MESSAGE_BODY_ATTRIBUTE_HTML_BODY] = picojson::value(body->getHtmlBody()); +picojson::value MessagingUtil::messageBodyToJson(std::shared_ptr body) { + LoggerD("Entered"); + picojson::object b; + b[MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID] = picojson::value(std::to_string(body->getMessageId())); + b[MESSAGE_BODY_ATTRIBUTE_LOADED] = picojson::value(body->getLoaded()); + b[MESSAGE_BODY_ATTRIBUTE_PLAIN_BODY] = picojson::value(body->getPlainBody()); + b[MESSAGE_BODY_ATTRIBUTE_HTML_BODY] = picojson::value(body->getHtmlBody()); - std::vector array; + std::vector array; - auto vectorToAttachmentArray = [&array] (std::shared_ptr& a)->void { - array.push_back(MessagingUtil::messageAttachmentToJson(a)); - }; - auto inlineAttachments = body->getInlineAttachments(); - for_each(inlineAttachments.begin(), inlineAttachments.end(), vectorToAttachmentArray); + auto vectorToAttachmentArray = [&array](std::shared_ptr& a) -> void { + array.push_back(MessagingUtil::messageAttachmentToJson(a)); + }; + auto inlineAttachments = body->getInlineAttachments(); + for_each(inlineAttachments.begin(), inlineAttachments.end(), vectorToAttachmentArray); - b[MESSAGE_BODY_ATTRIBUTE_INLINE_ATTACHMENTS] = picojson::value(array); - array.clear(); + b[MESSAGE_BODY_ATTRIBUTE_INLINE_ATTACHMENTS] = picojson::value(array); + array.clear(); - picojson::value v(b); - return v; + picojson::value v(b); + return v; } -picojson::value MessagingUtil::messageToJson(std::shared_ptr message) -{ - LoggerD("Entered"); - picojson::object o; +picojson::value MessagingUtil::messageToJson(std::shared_ptr message) { + LoggerD("Entered"); + picojson::object o; - std::vector array; - std::vector bcc, cc; - auto vectorToArray = [&array] (std::string& s)->void { - array.push_back(picojson::value(s)); - }; + std::vector array; + std::vector bcc, cc; + auto vectorToArray = [&array](std::string& s) -> void { array.push_back(picojson::value(s)); }; - switch (message->getType()) { + switch (message->getType()) { case MessageType::SMS: - break; + break; case MessageType::MMS: - o[MESSAGE_ATTRIBUTE_HAS_ATTACHMENT] = picojson::value(message->getHasAttachment()); - o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(message->getSubject()); - o[MESSAGE_ATTRIBUTE_OLD_ID] = picojson::value(std::to_string(message->getOldId())); - break; + o[MESSAGE_ATTRIBUTE_HAS_ATTACHMENT] = picojson::value(message->getHasAttachment()); + o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(message->getSubject()); + o[MESSAGE_ATTRIBUTE_OLD_ID] = picojson::value(std::to_string(message->getOldId())); + break; case MessageType::EMAIL: - cc = message->getCC(); - for_each(cc.begin(), cc.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_CC] = picojson::value(array); - array.clear(); + cc = message->getCC(); + for_each(cc.begin(), cc.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_CC] = picojson::value(array); + array.clear(); - bcc = message->getBCC(); - for_each(bcc.begin(), bcc.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_BCC] = picojson::value(array); - array.clear(); + bcc = message->getBCC(); + for_each(bcc.begin(), bcc.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_BCC] = picojson::value(array); + array.clear(); - o[MESSAGE_ATTRIBUTE_HAS_ATTACHMENT] = picojson::value(message->getHasAttachment()); - o[MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY] = picojson::value(message->getIsHighPriority()); - o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(message->getSubject()); - o[MESSAGE_ATTRIBUTE_OLD_ID] = picojson::value(std::to_string(message->getOldId())); + o[MESSAGE_ATTRIBUTE_HAS_ATTACHMENT] = picojson::value(message->getHasAttachment()); + o[MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY] = picojson::value(message->getIsHighPriority()); + o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(message->getSubject()); + o[MESSAGE_ATTRIBUTE_OLD_ID] = picojson::value(std::to_string(message->getOldId())); - break; + break; default: - LoggerW("Unsupported message type"); - break; - } + LoggerW("Unsupported message type"); + break; + } - o[MESSAGE_ATTRIBUTE_ID] = - message->is_id_set() - ? picojson::value(std::to_string(message->getId())) - : picojson::value(); - o[MESSAGE_ATTRIBUTE_CONVERSATION_ID]= - message->is_conversation_id_set() - ? picojson::value(std::to_string(message->getConversationId())) - : picojson::value(); - o[MESSAGE_ATTRIBUTE_FOLDER_ID] = - message->is_folder_id_set() - ? picojson::value(std::to_string(message->getFolderIdForUser())) - : picojson::value(); - o[MESSAGE_ATTRIBUTE_TYPE] = picojson::value(message->getTypeString()); - o[MESSAGE_ATTRIBUTE_TIMESTAMP] = - message->is_timestamp_set() - ? picojson::value(static_cast(message->getTimestamp())) - : picojson::value(); - o[MESSAGE_ATTRIBUTE_FROM] = - message->is_from_set() - ? picojson::value(message->getFrom()) - : picojson::value(std::string("")); - - std::vector to = message->getTO(); - for_each(to.begin(), to.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_TO] = picojson::value(array); - array.clear(); - - o[MESSAGE_ATTRIBUTE_IS_READ] = picojson::value(message->getIsRead()); - o[MESSAGE_ATTRIBUTE_IN_RESPONSE_TO] = - message->is_in_response_set() - ? picojson::value(std::to_string(message->getInResponseTo())) - : picojson::value(); - - std::shared_ptr body = message->getBody(); - o[MESSAGE_ATTRIBUTE_BODY] = MessagingUtil::messageBodyToJson(body); - - auto vectorToAttachmentArray = [&array] (std::shared_ptr& a)->void { - array.push_back(MessagingUtil::messageAttachmentToJson(a)); - }; - auto attachments = message->getMessageAttachments(); - for_each(attachments.begin(), attachments.end(), vectorToAttachmentArray); - o[MESSAGE_ATTRIBUTE_ATTACHMENTS] = picojson::value(array); - array.clear(); - - picojson::value v(o); - return v; + o[MESSAGE_ATTRIBUTE_ID] = + message->is_id_set() ? picojson::value(std::to_string(message->getId())) : picojson::value(); + o[MESSAGE_ATTRIBUTE_CONVERSATION_ID] = + message->is_conversation_id_set() + ? picojson::value(std::to_string(message->getConversationId())) + : picojson::value(); + o[MESSAGE_ATTRIBUTE_FOLDER_ID] = + message->is_folder_id_set() ? picojson::value(std::to_string(message->getFolderIdForUser())) + : picojson::value(); + o[MESSAGE_ATTRIBUTE_TYPE] = picojson::value(message->getTypeString()); + o[MESSAGE_ATTRIBUTE_TIMESTAMP] = + message->is_timestamp_set() ? picojson::value(static_cast(message->getTimestamp())) + : picojson::value(); + o[MESSAGE_ATTRIBUTE_FROM] = message->is_from_set() ? picojson::value(message->getFrom()) + : picojson::value(std::string("")); + + std::vector to = message->getTO(); + for_each(to.begin(), to.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_TO] = picojson::value(array); + array.clear(); + + o[MESSAGE_ATTRIBUTE_IS_READ] = picojson::value(message->getIsRead()); + o[MESSAGE_ATTRIBUTE_IN_RESPONSE_TO] = + message->is_in_response_set() ? picojson::value(std::to_string(message->getInResponseTo())) + : picojson::value(); + + std::shared_ptr body = message->getBody(); + o[MESSAGE_ATTRIBUTE_BODY] = MessagingUtil::messageBodyToJson(body); + + auto vectorToAttachmentArray = [&array](std::shared_ptr& a) -> void { + array.push_back(MessagingUtil::messageAttachmentToJson(a)); + }; + auto attachments = message->getMessageAttachments(); + for_each(attachments.begin(), attachments.end(), vectorToAttachmentArray); + o[MESSAGE_ATTRIBUTE_ATTACHMENTS] = picojson::value(array); + array.clear(); + + picojson::value v(o); + return v; } -picojson::value MessagingUtil::conversationToJson(std::shared_ptr conversation) -{ - LoggerD("Entered"); - picojson::object o; +picojson::value MessagingUtil::conversationToJson( + std::shared_ptr conversation) { + LoggerD("Entered"); + picojson::object o; - o[MESSAGE_CONVERSATION_ATTRIBUTE_ID] = picojson::value(std::to_string(conversation->getConversationId())); + o[MESSAGE_CONVERSATION_ATTRIBUTE_ID] = + picojson::value(std::to_string(conversation->getConversationId())); - o[MESSAGE_CONVERSATION_ATTRIBUTE_TYPE] = picojson::value(conversation->getTypeString()); + o[MESSAGE_CONVERSATION_ATTRIBUTE_TYPE] = picojson::value(conversation->getTypeString()); - o[MESSAGE_CONVERSATION_ATTRIBUTE_TIMESTAMP] = - picojson::value(static_cast(conversation->getTimestamp())); + o[MESSAGE_CONVERSATION_ATTRIBUTE_TIMESTAMP] = + picojson::value(static_cast(conversation->getTimestamp())); - o[MESSAGE_CONVERSATION_ATTRIBUTE_MESSAGE_COUNT] = - picojson::value(static_cast(conversation->getMessageCount())); + o[MESSAGE_CONVERSATION_ATTRIBUTE_MESSAGE_COUNT] = + picojson::value(static_cast(conversation->getMessageCount())); - o[MESSAGE_CONVERSATION_ATTRIBUTE_UNREAD_MESSAGES] = - picojson::value(static_cast(conversation->getUnreadMessages())); + o[MESSAGE_CONVERSATION_ATTRIBUTE_UNREAD_MESSAGES] = + picojson::value(static_cast(conversation->getUnreadMessages())); - o[MESSAGE_CONVERSATION_ATTRIBUTE_PREVIEW] = - picojson::value(conversation->getPreview()); + o[MESSAGE_CONVERSATION_ATTRIBUTE_PREVIEW] = picojson::value(conversation->getPreview()); - o[MESSAGE_CONVERSATION_ATTRIBUTE_IS_READ] = - picojson::value(conversation->getIsRead()); + o[MESSAGE_CONVERSATION_ATTRIBUTE_IS_READ] = picojson::value(conversation->getIsRead()); - o[MESSAGE_CONVERSATION_ATTRIBUTE_FROM] = - picojson::value(conversation->getFrom()); + o[MESSAGE_CONVERSATION_ATTRIBUTE_FROM] = picojson::value(conversation->getFrom()); - o[MESSAGE_CONVERSATION_ATTRIBUTE_LAST_MESSAGE_ID] = - picojson::value(std::to_string(conversation->getLastMessageId())); + o[MESSAGE_CONVERSATION_ATTRIBUTE_LAST_MESSAGE_ID] = + picojson::value(std::to_string(conversation->getLastMessageId())); - std::vector array; - auto vectorToArray = [&array] (std::string& s)->void { - array.push_back(picojson::value(s)); - }; + std::vector array; + auto vectorToArray = [&array](std::string& s) -> void { array.push_back(picojson::value(s)); }; - std::vector to = conversation->getTo(); - for_each(to.begin(), to.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_TO] = picojson::value(array); - array.clear(); - std::vector cc, bcc; + std::vector to = conversation->getTo(); + for_each(to.begin(), to.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_TO] = picojson::value(array); + array.clear(); + std::vector cc, bcc; - switch (conversation->getType()) { - case MessageType::SMS: - break; - case MessageType::MMS: - o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(conversation->getSubject()); - break; - case MessageType::EMAIL: - o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(conversation->getSubject()); + switch (conversation->getType()) { + case MessageType::SMS: + break; + case MessageType::MMS: + o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(conversation->getSubject()); + break; + case MessageType::EMAIL: + o[MESSAGE_ATTRIBUTE_SUBJECT] = picojson::value(conversation->getSubject()); - cc = conversation->getCC(); - for_each(cc.begin(), cc.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_CC] = picojson::value(array); - array.clear(); + cc = conversation->getCC(); + for_each(cc.begin(), cc.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_CC] = picojson::value(array); + array.clear(); - bcc = conversation->getBCC(); - for_each(bcc.begin(), bcc.end(), vectorToArray); - o[MESSAGE_ATTRIBUTE_BCC] = picojson::value(array); - array.clear(); + bcc = conversation->getBCC(); + for_each(bcc.begin(), bcc.end(), vectorToArray); + o[MESSAGE_ATTRIBUTE_BCC] = picojson::value(array); + array.clear(); - break; - default: - LoggerW("Unsupported message type"); - break; - } + break; + default: + LoggerW("Unsupported message type"); + break; + } - picojson::value v(o); - return v; + picojson::value v(o); + return v; } -picojson::value MessagingUtil::folderToJson(std::shared_ptr folder) -{ - LoggerD("Entered"); - - picojson::object o; - - o[MESSAGE_FOLDER_ATTRIBUTE_ID] = picojson::value(folder->getId()); - o[MESSAGE_FOLDER_ATTRIBUTE_PARENT_ID] = - folder->isParentIdSet() - ? picojson::value(folder->getParentId()) - : picojson::value(); - o[MESSAGE_FOLDER_ATTRIBUTE_SERVICE_ID] = picojson::value(folder->getServiceId()); - o[MESSAGE_FOLDER_ATTRIBUTE_CONTENT_TYPE] = picojson::value(folder->getContentType()); - o[MESSAGE_FOLDER_ATTRIBUTE_NAME] = picojson::value(folder->getName()); - o[MESSAGE_FOLDER_ATTRIBUTE_PATH] = picojson::value(folder->getPath()); - o[MESSAGE_FOLDER_ATTRIBUTE_TYPE] = - picojson::value(MessagingUtil::messageFolderTypeToString(folder->getType())); - o[MESSAGE_FOLDER_ATTRIBUTE_SYNCHRONIZABLE] = picojson::value(folder->getSynchronizable()); - - picojson::value v(o); - return v; +picojson::value MessagingUtil::folderToJson(std::shared_ptr folder) { + LoggerD("Entered"); + + picojson::object o; + + o[MESSAGE_FOLDER_ATTRIBUTE_ID] = picojson::value(folder->getId()); + o[MESSAGE_FOLDER_ATTRIBUTE_PARENT_ID] = + folder->isParentIdSet() ? picojson::value(folder->getParentId()) : picojson::value(); + o[MESSAGE_FOLDER_ATTRIBUTE_SERVICE_ID] = picojson::value(folder->getServiceId()); + o[MESSAGE_FOLDER_ATTRIBUTE_CONTENT_TYPE] = picojson::value(folder->getContentType()); + o[MESSAGE_FOLDER_ATTRIBUTE_NAME] = picojson::value(folder->getName()); + o[MESSAGE_FOLDER_ATTRIBUTE_PATH] = picojson::value(folder->getPath()); + o[MESSAGE_FOLDER_ATTRIBUTE_TYPE] = + picojson::value(MessagingUtil::messageFolderTypeToString(folder->getType())); + o[MESSAGE_FOLDER_ATTRIBUTE_SYNCHRONIZABLE] = picojson::value(folder->getSynchronizable()); + + picojson::value v(o); + return v; } PlatformResult MessagingUtil::jsonToMessage(const picojson::value& json, - std::shared_ptr* result_message) -{ - LoggerD("Entered"); - std::shared_ptr message; - picojson::object data = json.get(); - std::string type = data.at("type").get(); - MessageType mtype = UNDEFINED; - auto platform_result = MessagingUtil::stringToMessageType(type, &mtype); - - if (!platform_result) { - return platform_result; - } + std::shared_ptr* result_message) { + LoggerD("Entered"); + std::shared_ptr message; + picojson::object data = json.get(); + std::string type = data.at("type").get(); + MessageType mtype = UNDEFINED; + auto platform_result = MessagingUtil::stringToMessageType(type, &mtype); + + if (!platform_result) { + return platform_result; + } - switch (mtype) { + switch (mtype) { case MessageType::SMS: - LoggerD("SMS type"); - if(data.at(MESSAGE_ATTRIBUTE_ID).is()) { - message = std::shared_ptr(new MessageSMS()); - break; - } - case MessageType::MMS: - LoggerD("MMS type"); - if(data.at(MESSAGE_ATTRIBUTE_ID).is()) { - message = std::shared_ptr(new MessageMMS()); - } else { - std::string mid = data.at(MESSAGE_ATTRIBUTE_ID).get(); - int message_id = std::atoi(mid.c_str()); - platform_result = Message::findShortMessageById(message_id, &message); - if (!platform_result) return platform_result; - } + LoggerD("SMS type"); + if (data.at(MESSAGE_ATTRIBUTE_ID).is()) { + message = std::shared_ptr(new MessageSMS()); break; + } + case MessageType::MMS: + LoggerD("MMS type"); + if (data.at(MESSAGE_ATTRIBUTE_ID).is()) { + message = std::shared_ptr(new MessageMMS()); + } else { + std::string mid = data.at(MESSAGE_ATTRIBUTE_ID).get(); + int message_id = std::atoi(mid.c_str()); + platform_result = Message::findShortMessageById(message_id, &message); + if (!platform_result) return platform_result; + } + break; case MessageType::EMAIL: - if (!data.at(MESSAGE_ATTRIBUTE_ID).is()) { - std::string mid = data.at(MESSAGE_ATTRIBUTE_ID).get(); - int mail_id = std::atoi(mid.c_str()); - email_mail_data_t* mail = NULL; - if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail)) { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Failed to find specified email.", - ("Fatal error: message not found: %d!", mail_id)); - } else { - platform_result = Message::convertPlatformEmailToObject(*mail, &message); - email_free_mail_data(&mail,1); - if (!platform_result) return platform_result; - } + if (!data.at(MESSAGE_ATTRIBUTE_ID).is()) { + std::string mid = data.at(MESSAGE_ATTRIBUTE_ID).get(); + int mail_id = std::atoi(mid.c_str()); + email_mail_data_t* mail = NULL; + if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail)) { + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Failed to find specified email.", + ("Fatal error: message not found: %d!", mail_id)); } else { - message = std::shared_ptr(new MessageEmail()); + platform_result = Message::convertPlatformEmailToObject(*mail, &message); + email_free_mail_data(&mail, 1); + if (!platform_result) return platform_result; } - break; - default: - LoggerE("Not supported message type"); - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, "Not supported message type"); - break; - } - - std::vector result; - PlatformResult conv_res(ErrorCode::NO_ERROR); - auto arrayVectorStringConverter = [&result, &conv_res] (picojson::value& v)->void { - if (!v.is()) { - const std::string message = "Passed array holds incorrect values " - + v.serialize() + " is not a correct string value"; - conv_res = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); - } - if (conv_res.IsError()) { - return; + } else { + message = std::shared_ptr(new MessageEmail()); } - result.push_back(v.get()); - }; - - auto subject = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_ATTRIBUTE_SUBJECT); - message->setSubject(subject); + break; + default: + LoggerE("Not supported message type"); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Not supported message type"); + break; + } - auto toJS = MessagingUtil::getValueFromJSONObject>(data, - MESSAGE_ATTRIBUTE_TO); - for_each(toJS.begin(), toJS.end(), arrayVectorStringConverter); - if (conv_res.IsError()) { - return conv_res; + std::vector result; + PlatformResult conv_res(ErrorCode::NO_ERROR); + auto arrayVectorStringConverter = [&result, &conv_res](picojson::value& v) -> void { + if (!v.is()) { + const std::string message = + "Passed array holds incorrect values " + v.serialize() + " is not a correct string value"; + conv_res = LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } - message->setTO(result); - result.clear(); - - - auto ccJS = MessagingUtil::getValueFromJSONObject< - std::vector>(data, MESSAGE_ATTRIBUTE_CC); - for_each(ccJS.begin(), ccJS.end(), arrayVectorStringConverter); if (conv_res.IsError()) { - return conv_res; + return; } - message->setCC(result); - result.clear(); + result.push_back(v.get()); + }; - auto bccJS = MessagingUtil::getValueFromJSONObject< - std::vector>(data, MESSAGE_ATTRIBUTE_BCC); - for_each(bccJS.begin(), bccJS.end(), arrayVectorStringConverter); - if (conv_res.IsError()) { - return conv_res; - } - message->setBCC(result); - result.clear(); + auto subject = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_ATTRIBUTE_SUBJECT); + message->setSubject(subject); - auto priority = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY); - message->setIsHighPriority(priority); + auto toJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_ATTRIBUTE_TO); + for_each(toJS.begin(), toJS.end(), arrayVectorStringConverter); + if (conv_res.IsError()) { + return conv_res; + } + message->setTO(result); + result.clear(); + + auto ccJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_ATTRIBUTE_CC); + for_each(ccJS.begin(), ccJS.end(), arrayVectorStringConverter); + if (conv_res.IsError()) { + return conv_res; + } + message->setCC(result); + result.clear(); + + auto bccJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_ATTRIBUTE_BCC); + for_each(bccJS.begin(), bccJS.end(), arrayVectorStringConverter); + if (conv_res.IsError()) { + return conv_res; + } + message->setBCC(result); + result.clear(); - auto isRead = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_ATTRIBUTE_IS_READ); - message->setIsRead(isRead); + auto priority = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY); + message->setIsHighPriority(priority); - std::shared_ptr body = MessagingUtil::jsonToMessageBody( - data[MESSAGE_ATTRIBUTE_MESSAGE_BODY]); - message->setBody(body); + auto isRead = MessagingUtil::getValueFromJSONObject(data, MESSAGE_ATTRIBUTE_IS_READ); + message->setIsRead(isRead); - AttachmentPtrVector attachments; - auto ma = data.at(MESSAGE_ATTRIBUTE_MESSAGE_ATTACHMENTS).get>(); + std::shared_ptr body = + MessagingUtil::jsonToMessageBody(data[MESSAGE_ATTRIBUTE_MESSAGE_BODY]); + message->setBody(body); - auto arrayVectorAttachmentConverter = [&attachments] (picojson::value& v)->void - { - std::shared_ptr attachment = - MessagingUtil::jsonToMessageAttachment(v); + AttachmentPtrVector attachments; + auto ma = data.at(MESSAGE_ATTRIBUTE_MESSAGE_ATTACHMENTS).get>(); - attachments.push_back(attachment); - }; + auto arrayVectorAttachmentConverter = [&attachments](picojson::value& v) -> void { + std::shared_ptr attachment = MessagingUtil::jsonToMessageAttachment(v); - for_each(ma.begin(), ma.end(), arrayVectorAttachmentConverter); - message->setMessageAttachments(attachments); + attachments.push_back(attachment); + }; - *result_message = message; - return PlatformResult(ErrorCode::NO_ERROR); + for_each(ma.begin(), ma.end(), arrayVectorAttachmentConverter); + message->setMessageAttachments(attachments); + + *result_message = message; + return PlatformResult(ErrorCode::NO_ERROR); } -std::shared_ptr MessagingUtil::jsonToMessageBody(const picojson::value& json) -{ - LoggerD("Entered"); +std::shared_ptr MessagingUtil::jsonToMessageBody(const picojson::value& json) { + LoggerD("Entered"); - std::shared_ptr body = std::shared_ptr(new MessageBody()); - picojson::object data = json.get(); + std::shared_ptr body = std::shared_ptr(new MessageBody()); + picojson::object data = json.get(); - bool loaded = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_BODY_ATTRIBUTE_LOADED); - body->setLoaded(loaded); + bool loaded = MessagingUtil::getValueFromJSONObject(data, MESSAGE_BODY_ATTRIBUTE_LOADED); + body->setLoaded(loaded); - std::string html = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_BODY_ATTRIBUTE_HTML_BODY); - body->setHtmlBody(html); + std::string html = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_BODY_ATTRIBUTE_HTML_BODY); + body->setHtmlBody(html); - std::string plain = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_BODY_ATTRIBUTE_PLAIN_BODY); - body->setPlainBody(plain); + std::string plain = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_BODY_ATTRIBUTE_PLAIN_BODY); + body->setPlainBody(plain); - if (!data.at(MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID).is()) { - int messageId = std::atoi(MessagingUtil::getValueFromJSONObject(data, - MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID).c_str()); - body->setMessageId(messageId); - } + if (!data.at(MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID).is()) { + int messageId = std::atoi( + MessagingUtil::getValueFromJSONObject(data, MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID) + .c_str()); + body->setMessageId(messageId); + } - AttachmentPtrVector inlineAttachments; - auto ma = data.at(MESSAGE_BODY_ATTRIBUTE_INLINE_ATTACHMENTS ).get(); + AttachmentPtrVector inlineAttachments; + auto ma = data.at(MESSAGE_BODY_ATTRIBUTE_INLINE_ATTACHMENTS).get(); - auto arrayVectorAttachmentConverter = [&inlineAttachments] (picojson::value& v)->void - { - inlineAttachments.push_back(jsonToMessageAttachment(v)); - }; + auto arrayVectorAttachmentConverter = [&inlineAttachments](picojson::value& v) -> void { + inlineAttachments.push_back(jsonToMessageAttachment(v)); + }; - for_each(ma.begin(), ma.end(), arrayVectorAttachmentConverter); - body->setInlineAttachments(inlineAttachments); + for_each(ma.begin(), ma.end(), arrayVectorAttachmentConverter); + body->setInlineAttachments(inlineAttachments); - return body; + return body; } -std::shared_ptr MessagingUtil::jsonToMessageFolder(const picojson::value& json) -{ - LoggerD("Entered"); +std::shared_ptr MessagingUtil::jsonToMessageFolder(const picojson::value& json) { + LoggerD("Entered"); - picojson::object data = json.get(); + picojson::object data = json.get(); - std::string id = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_ID).c_str(); + std::string id = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_ID).c_str(); - std::string parent_id = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_PARENT_ID).c_str(); + std::string parent_id = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_PARENT_ID) + .c_str(); - std::string service_id = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_SERVICE_ID).c_str(); + std::string service_id = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_SERVICE_ID) + .c_str(); - std::string content_type = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_CONTENT_TYPE).c_str(); + std::string content_type = MessagingUtil::getValueFromJSONObject( + data, MESSAGE_FOLDER_ATTRIBUTE_CONTENT_TYPE) + .c_str(); - std::string name = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_NAME).c_str(); + std::string name = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_NAME) + .c_str(); - std::string path = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_PATH).c_str(); + std::string path = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_PATH) + .c_str(); - std::string type_str = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_TYPE).c_str(); - MessageFolderType type = MessagingUtil::stringToMessageFolderType(type_str); + std::string type_str = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_TYPE) + .c_str(); + MessageFolderType type = MessagingUtil::stringToMessageFolderType(type_str); - bool synchronizable = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_FOLDER_ATTRIBUTE_SYNCHRONIZABLE); + bool synchronizable = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_FOLDER_ATTRIBUTE_SYNCHRONIZABLE); - std::shared_ptr folder = std::shared_ptr( - new MessageFolder( - id, - parent_id, - service_id, - content_type, - name, - path, - type, - synchronizable)); + std::shared_ptr folder = std::shared_ptr( + new MessageFolder(id, parent_id, service_id, content_type, name, path, type, synchronizable)); - return folder; + return folder; } -tizen::SortModePtr MessagingUtil::jsonToSortMode(const picojson::object& json) -{ - LoggerD("Entered"); - using namespace tizen; +tizen::SortModePtr MessagingUtil::jsonToSortMode(const picojson::object& json) { + LoggerD("Entered"); + using namespace tizen; - const auto it = json.find(JSON_TO_SORT); + const auto it = json.find(JSON_TO_SORT); - if (json.end() == it || it->second.is()) { - return SortModePtr(); - } + if (json.end() == it || it->second.is()) { + return SortModePtr(); + } - auto dataSort = getValueFromJSONObject(json, JSON_TO_SORT); - auto name = getValueFromJSONObject(dataSort, JSON_TO_ATTRIBUTE_NAME); - auto ord = getValueFromJSONObject(dataSort, JSON_TO_ORDER); - SortModeOrder order = ( ord == STR_SORT_DESC) ? SortModeOrder::DESC : SortModeOrder::ASC; - return SortModePtr(new SortMode(name, order)); + auto dataSort = getValueFromJSONObject(json, JSON_TO_SORT); + auto name = getValueFromJSONObject(dataSort, JSON_TO_ATTRIBUTE_NAME); + auto ord = getValueFromJSONObject(dataSort, JSON_TO_ORDER); + SortModeOrder order = (ord == STR_SORT_DESC) ? SortModeOrder::DESC : SortModeOrder::ASC; + return SortModePtr(new SortMode(name, order)); } PlatformResult MessagingUtil::jsonToAbstractFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result) -{ - LoggerD("Entered"); + tizen::AbstractFilterPtr* result) { + LoggerD("Entered"); - const auto it = json.find(JSON_TO_FILTER); + const auto it = json.find(JSON_TO_FILTER); - if (json.end() == it || it->second.is()) { - *result = AbstractFilterPtr(); - return PlatformResult(ErrorCode::NO_ERROR); - } + if (json.end() == it || it->second.is()) { + *result = AbstractFilterPtr(); + return PlatformResult(ErrorCode::NO_ERROR); + } - return jsonFilterToAbstractFilter(json.at(JSON_TO_FILTER).get(), result); + return jsonFilterToAbstractFilter(json.at(JSON_TO_FILTER).get(), result); } PlatformResult MessagingUtil::jsonFilterToAbstractFilter(const picojson::object& filter, - tizen::AbstractFilterPtr* result) -{ - LoggerD("Entered"); - const auto& type = filter.at(JSON_FILTER_TYPE).get(); - - if (JSON_FILTER_ATTRIBUTE_TYPE == type) { + tizen::AbstractFilterPtr* result) { + LoggerD("Entered"); + const auto& type = filter.at(JSON_FILTER_TYPE).get(); - return jsonFilterToAttributeFilter(filter, result); - } - if (JSON_FILTER_ATTRIBUTE_RANGE_TYPE == type) { - return jsonFilterToAttributeRangeFilter(filter, result); - } - if (JSON_FILTER_COMPOSITE_TYPE == type) { - return jsonFilterToCompositeFilter(filter, result); - } + if (JSON_FILTER_ATTRIBUTE_TYPE == type) { + return jsonFilterToAttributeFilter(filter, result); + } + if (JSON_FILTER_ATTRIBUTE_RANGE_TYPE == type) { + return jsonFilterToAttributeRangeFilter(filter, result); + } + if (JSON_FILTER_COMPOSITE_TYPE == type) { + return jsonFilterToCompositeFilter(filter, result); + } - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Unsupported filter type", - ("Unsupported filter type: %s", type.c_str())); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Unsupported filter type", + ("Unsupported filter type: %s", type.c_str())); } PlatformResult MessagingUtil::jsonFilterToAttributeFilter(const picojson::object& filter, - tizen::AbstractFilterPtr* result) -{ - LoggerD("Entered"); - - using namespace tizen; - - auto name = getValueFromJSONObject(filter, JSON_TO_ATTRIBUTE_NAME); - auto matchFlagStr = getValueFromJSONObject(filter, JSON_TO_MATCH_FLAG); - - FilterMatchFlag filterMatch; + tizen::AbstractFilterPtr* result) { + LoggerD("Entered"); - if (STR_MATCH_EXACTLY == matchFlagStr) { - filterMatch = FilterMatchFlag::EXACTLY; - } - else if (STR_MATCH_FULLSTRING == matchFlagStr) { - filterMatch = FilterMatchFlag::FULLSTRING; - } - else if (STR_MATCH_CONTAINS == matchFlagStr) { - filterMatch = FilterMatchFlag::CONTAINS; - } - else if (STR_MATCH_STARTSWITH == matchFlagStr) { - filterMatch = FilterMatchFlag::STARTSWITH; - } - else if (STR_MATCH_ENDSWITH == matchFlagStr) { - filterMatch = FilterMatchFlag::ENDSWITH; - } - else if (STR_MATCH_EXISTS == matchFlagStr) { - filterMatch = FilterMatchFlag::EXISTS; - } - else { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Filter name is not recognized", - ("Filter name is not recognized: %s", matchFlagStr.c_str())); - } + using namespace tizen; + + auto name = getValueFromJSONObject(filter, JSON_TO_ATTRIBUTE_NAME); + auto matchFlagStr = getValueFromJSONObject(filter, JSON_TO_MATCH_FLAG); + + FilterMatchFlag filterMatch; + + if (STR_MATCH_EXACTLY == matchFlagStr) { + filterMatch = FilterMatchFlag::EXACTLY; + } else if (STR_MATCH_FULLSTRING == matchFlagStr) { + filterMatch = FilterMatchFlag::FULLSTRING; + } else if (STR_MATCH_CONTAINS == matchFlagStr) { + filterMatch = FilterMatchFlag::CONTAINS; + } else if (STR_MATCH_STARTSWITH == matchFlagStr) { + filterMatch = FilterMatchFlag::STARTSWITH; + } else if (STR_MATCH_ENDSWITH == matchFlagStr) { + filterMatch = FilterMatchFlag::ENDSWITH; + } else if (STR_MATCH_EXISTS == matchFlagStr) { + filterMatch = FilterMatchFlag::EXISTS; + } else { + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Filter name is not recognized", + ("Filter name is not recognized: %s", matchFlagStr.c_str())); + } - auto attributePtr = new AttributeFilter(name); - attributePtr->setMatchFlag(filterMatch); - attributePtr->setMatchValue(AnyPtr(new Any(filter.at(JSON_TO_MATCH_VALUE)))); - (*result).reset(attributePtr); - return PlatformResult(ErrorCode::NO_ERROR); + auto attributePtr = new AttributeFilter(name); + attributePtr->setMatchFlag(filterMatch); + attributePtr->setMatchValue(AnyPtr(new Any(filter.at(JSON_TO_MATCH_VALUE)))); + (*result).reset(attributePtr); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MessagingUtil::jsonFilterToAttributeRangeFilter(const picojson::object& filter, - tizen::AbstractFilterPtr* result) -{ - LoggerD("Entered"); + tizen::AbstractFilterPtr* result) { + LoggerD("Entered"); - auto name = getValueFromJSONObject(filter, JSON_TO_ATTRIBUTE_NAME); + auto name = getValueFromJSONObject(filter, JSON_TO_ATTRIBUTE_NAME); - auto attributeRangePtr = new tizen::AttributeRangeFilter(name); - attributeRangePtr->setInitialValue(AnyPtr(new Any(filter.at(JSON_TO_INITIAL_VALUE)))); - attributeRangePtr->setEndValue(AnyPtr(new Any(filter.at(JSON_TO_END_VALUE)))); + auto attributeRangePtr = new tizen::AttributeRangeFilter(name); + attributeRangePtr->setInitialValue(AnyPtr(new Any(filter.at(JSON_TO_INITIAL_VALUE)))); + attributeRangePtr->setEndValue(AnyPtr(new Any(filter.at(JSON_TO_END_VALUE)))); - (*result).reset(attributeRangePtr); - return PlatformResult(ErrorCode::NO_ERROR); + (*result).reset(attributeRangePtr); + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult MessagingUtil::jsonFilterToCompositeFilter(const picojson::object& filter, - tizen::AbstractFilterPtr* result) -{ - LoggerD("Entered"); + tizen::AbstractFilterPtr* result) { + LoggerD("Entered"); - using namespace tizen; + using namespace tizen; - const auto& type = filter.at(JSON_TO_TYPE).get(); + const auto& type = filter.at(JSON_TO_TYPE).get(); - CompositeFilterType filterType = CompositeFilterType::UNION; + CompositeFilterType filterType = CompositeFilterType::UNION; - if (STR_FILTEROP_OR == type) { - filterType = CompositeFilterType::UNION; - } - else if (STR_FILTEROP_AND == type) { - filterType = CompositeFilterType::INTERSECTION; - } - else { - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Composite filter type is not recognized", - ("Composite filter type is not recognized: %s", type.c_str())); - } + if (STR_FILTEROP_OR == type) { + filterType = CompositeFilterType::UNION; + } else if (STR_FILTEROP_AND == type) { + filterType = CompositeFilterType::INTERSECTION; + } else { + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, + "Composite filter type is not recognized", + ("Composite filter type is not recognized: %s", type.c_str())); + } - auto compositeFilter = new CompositeFilter(filterType); + auto compositeFilter = new CompositeFilter(filterType); - for (const auto& a : filter.at(JSON_TO_FILTER_ARRAY).get()) { - AbstractFilterPtr filter; - PlatformResult ret = jsonFilterToAbstractFilter(a.get(), &filter); - if (ret.IsError()) { - delete compositeFilter; - LoggerD("Convert JSON filter to Abstract filter failed (%s)", ret.message().c_str()); - return ret; - } - compositeFilter->addFilter(filter); + for (const auto& a : filter.at(JSON_TO_FILTER_ARRAY).get()) { + AbstractFilterPtr filter; + PlatformResult ret = jsonFilterToAbstractFilter(a.get(), &filter); + if (ret.IsError()) { + delete compositeFilter; + LoggerD("Convert JSON filter to Abstract filter failed (%s)", ret.message().c_str()); + return ret; } + compositeFilter->addFilter(filter); + } - (*result).reset(compositeFilter); - return PlatformResult(ErrorCode::NO_ERROR); + (*result).reset(compositeFilter); + return PlatformResult(ErrorCode::NO_ERROR); } -std::shared_ptr MessagingUtil::jsonToMessageAttachment(const picojson::value& json) -{ - LoggerD("Entered"); - - picojson::object data = json.get(); - int attachmentId = std::atoi(getValueFromJSONObject(data, - MESSAGE_ATTACHMENT_ATTRIBUTE_ID).c_str()); - int messageId = std::atoi(getValueFromJSONObject(data, - MESSAGE_ATTACHMENT_ATTRIBUTE_MESSAGE_ID).c_str()); - std::string mimeType = - getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_MIME_TYPE); - std::string filePath = - getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_FILE_PATH); - auto attachmentPtr = std::shared_ptr(new MessageAttachment()); - - attachmentPtr->setId(attachmentId); - attachmentPtr->setMessageId(messageId); - attachmentPtr->setMimeType(mimeType); - attachmentPtr->setFilePath(filePath); - - return attachmentPtr; +std::shared_ptr MessagingUtil::jsonToMessageAttachment( + const picojson::value& json) { + LoggerD("Entered"); + + picojson::object data = json.get(); + int attachmentId = + std::atoi(getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_ID).c_str()); + int messageId = std::atoi( + getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_MESSAGE_ID).c_str()); + std::string mimeType = + getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_MIME_TYPE); + std::string filePath = + getValueFromJSONObject(data, MESSAGE_ATTACHMENT_ATTRIBUTE_FILE_PATH); + auto attachmentPtr = std::shared_ptr(new MessageAttachment()); + + attachmentPtr->setId(attachmentId); + attachmentPtr->setMessageId(messageId); + attachmentPtr->setMimeType(mimeType); + attachmentPtr->setFilePath(filePath); + + return attachmentPtr; } -picojson::value MessagingUtil::messageAttachmentToJson(std::shared_ptr attachment) -{ - LoggerD("Entered"); +picojson::value MessagingUtil::messageAttachmentToJson( + std::shared_ptr attachment) { + LoggerD("Entered"); - picojson::object o; - o[MESSAGE_ATTACHMENT_ATTRIBUTE_ID] = - attachment->isIdSet() - ? picojson::value(std::to_string(attachment->getId())) - : picojson::value(); + picojson::object o; + o[MESSAGE_ATTACHMENT_ATTRIBUTE_ID] = attachment->isIdSet() + ? picojson::value(std::to_string(attachment->getId())) + : picojson::value(); - o[MESSAGE_ATTACHMENT_ATTRIBUTE_MESSAGE_ID] = - attachment->isMessageIdSet() - ? picojson::value(std::to_string(attachment->getMessageId())) - : picojson::value(); + o[MESSAGE_ATTACHMENT_ATTRIBUTE_MESSAGE_ID] = + attachment->isMessageIdSet() ? picojson::value(std::to_string(attachment->getMessageId())) + : picojson::value(); - o[MESSAGE_ATTACHMENT_ATTRIBUTE_MIME_TYPE] = - attachment->isMimeTypeSet() - ? picojson::value(attachment->getMimeType()) - : picojson::value(); + o[MESSAGE_ATTACHMENT_ATTRIBUTE_MIME_TYPE] = + attachment->isMimeTypeSet() ? picojson::value(attachment->getMimeType()) : picojson::value(); - o[MESSAGE_ATTACHMENT_ATTRIBUTE_FILE_PATH] = - attachment->isFilePathSet() - ? picojson::value(attachment->getFilePath()) - : picojson::value(); + o[MESSAGE_ATTACHMENT_ATTRIBUTE_FILE_PATH] = + attachment->isFilePathSet() ? picojson::value(attachment->getFilePath()) : picojson::value(); - return picojson::value(o); + return picojson::value(o); } -PlatformResult MessagingUtil::jsonToMessageConversation(const picojson::value& json, - std::shared_ptr* result_conversation) -{ - LoggerD("Entered"); - std::shared_ptr conversation; - picojson::object data = json.get(); - std::string type = data.at("type").get(); - MessageType mtype = UNDEFINED; - auto platform_result = MessagingUtil::stringToMessageType(type, &mtype); - - if (!platform_result) return platform_result; - - conversation = std::shared_ptr(new MessageConversation()); - - conversation->setType(mtype); - - int id = std::atoi(MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_ID).c_str()); - conversation->setConversationId(id); - - /// MESSAGE_CONVERSATION_ATTRIBUTE_TIMESTAMP ? +PlatformResult MessagingUtil::jsonToMessageConversation( + const picojson::value& json, std::shared_ptr* result_conversation) { + LoggerD("Entered"); + std::shared_ptr conversation; + picojson::object data = json.get(); + std::string type = data.at("type").get(); + MessageType mtype = UNDEFINED; + auto platform_result = MessagingUtil::stringToMessageType(type, &mtype); - int messageCount = std::atoi(MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_MESSAGE_COUNT).c_str()); - conversation->setMessageCount(messageCount); + if (!platform_result) return platform_result; - int unreadMessages = std::atoi(MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_UNREAD_MESSAGES).c_str()); - conversation->setUnreadMessages(unreadMessages); + conversation = std::shared_ptr(new MessageConversation()); - std::string preview = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_PREVIEW); - conversation->setPreview(preview); + conversation->setType(mtype); - std::string subject = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_SUBJECT); - conversation->setSubject(subject); + int id = std::atoi( + MessagingUtil::getValueFromJSONObject(data, MESSAGE_CONVERSATION_ATTRIBUTE_ID) + .c_str()); + conversation->setConversationId(id); - /// MESSAGE_CONVERSATION_ATTRIBUTE_IS_READ ? + /// MESSAGE_CONVERSATION_ATTRIBUTE_TIMESTAMP ? - std::vector result; - auto arrayVectorStringConverter = [&result] (picojson::value& v)->void { - result.push_back(v.get()); - }; + int messageCount = std::atoi(MessagingUtil::getValueFromJSONObject( + data, MESSAGE_CONVERSATION_ATTRIBUTE_MESSAGE_COUNT) + .c_str()); + conversation->setMessageCount(messageCount); - std::string from = MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_FROM); - conversation->setFrom(from); + int unreadMessages = std::atoi(MessagingUtil::getValueFromJSONObject( + data, MESSAGE_CONVERSATION_ATTRIBUTE_UNREAD_MESSAGES) + .c_str()); + conversation->setUnreadMessages(unreadMessages); - auto toJS = MessagingUtil::getValueFromJSONObject>( - data, MESSAGE_CONVERSATION_ATTRIBUTE_TO); - for_each(toJS.begin(), toJS.end(), arrayVectorStringConverter); - conversation->setTo(result); - result.clear(); + std::string preview = MessagingUtil::getValueFromJSONObject( + data, MESSAGE_CONVERSATION_ATTRIBUTE_PREVIEW); + conversation->setPreview(preview); - auto ccJS = MessagingUtil::getValueFromJSONObject< - std::vector>(data, MESSAGE_ATTRIBUTE_CC); - for_each(ccJS.begin(), ccJS.end(), arrayVectorStringConverter); - conversation->setCC(result); - result.clear(); + std::string subject = MessagingUtil::getValueFromJSONObject( + data, MESSAGE_CONVERSATION_ATTRIBUTE_SUBJECT); + conversation->setSubject(subject); - auto bccJS = MessagingUtil::getValueFromJSONObject< - std::vector>(data, MESSAGE_ATTRIBUTE_BCC); - for_each(bccJS.begin(), bccJS.end(), arrayVectorStringConverter); - conversation->setBCC(result); - result.clear(); + /// MESSAGE_CONVERSATION_ATTRIBUTE_IS_READ ? - int lastMessageId = std::atoi(MessagingUtil::getValueFromJSONObject(data, - MESSAGE_CONVERSATION_ATTRIBUTE_LAST_MESSAGE_ID).c_str()); - conversation->setLastMessageId(lastMessageId); + std::vector result; + auto arrayVectorStringConverter = [&result](picojson::value& v) -> void { + result.push_back(v.get()); + }; - *result_conversation = conversation; - return PlatformResult(ErrorCode::NO_ERROR); + std::string from = + MessagingUtil::getValueFromJSONObject(data, MESSAGE_CONVERSATION_ATTRIBUTE_FROM); + conversation->setFrom(from); + + auto toJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_CONVERSATION_ATTRIBUTE_TO); + for_each(toJS.begin(), toJS.end(), arrayVectorStringConverter); + conversation->setTo(result); + result.clear(); + + auto ccJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_ATTRIBUTE_CC); + for_each(ccJS.begin(), ccJS.end(), arrayVectorStringConverter); + conversation->setCC(result); + result.clear(); + + auto bccJS = MessagingUtil::getValueFromJSONObject>( + data, MESSAGE_ATTRIBUTE_BCC); + for_each(bccJS.begin(), bccJS.end(), arrayVectorStringConverter); + conversation->setBCC(result); + result.clear(); + + int lastMessageId = std::atoi(MessagingUtil::getValueFromJSONObject( + data, MESSAGE_CONVERSATION_ATTRIBUTE_LAST_MESSAGE_ID) + .c_str()); + conversation->setLastMessageId(lastMessageId); + + *result_conversation = conversation; + return PlatformResult(ErrorCode::NO_ERROR); } -PostQueue::PostQueue(MessagingInstance& instance): instance_(instance) -{ - LoggerD("Entered: [%p]", this); +PostQueue::PostQueue(MessagingInstance& instance) : instance_(instance) { + LoggerD("Entered: [%p]", this); } -PostQueue::~PostQueue() -{ - LoggerD("Entered: [%p]", this); +PostQueue::~PostQueue() { + LoggerD("Entered: [%p]", this); - EmailManager::getInstance().RemoveCallbacksByQueue(*this); + EmailManager::getInstance().RemoveCallbacksByQueue(*this); } -void PostQueue::addAndResolve(const long cid, PostPriority priority, const std::string &json) -{ - LoggerD("Entered"); +void PostQueue::addAndResolve(const long cid, PostPriority priority, const std::string& json) { + LoggerD("Entered"); - std::shared_ptr t(new PostTask(priority)); - t->attach(json); - tasks_mutex_.lock(); - tasks_.push_back(std::make_pair(cid, t)); - tasks_mutex_.unlock(); + std::shared_ptr t(new PostTask(priority)); + t->attach(json); + tasks_mutex_.lock(); + tasks_.push_back(std::make_pair(cid, t)); + tasks_mutex_.unlock(); - resolve(PostPriority::HIGH); + resolve(PostPriority::HIGH); - return; + return; } -void PostQueue::add(const long cid, PostPriority priority) -{ - LoggerD("Entered"); +void PostQueue::add(const long cid, PostPriority priority) { + LoggerD("Entered"); - tasks_mutex_.lock(); - tasks_.push_back(std::make_pair(cid, std::shared_ptr(new PostTask(priority)))); - tasks_mutex_.unlock(); + tasks_mutex_.lock(); + tasks_.push_back(std::make_pair(cid, std::shared_ptr(new PostTask(priority)))); + tasks_mutex_.unlock(); - return; + return; } -void PostQueue::resolve(const long cid, const std::string &json) -{ - LoggerD("Entered: [%p]", this); +void PostQueue::resolve(const long cid, const std::string& json) { + LoggerD("Entered: [%p]", this); - tasks_mutex_.lock(); + tasks_mutex_.lock(); - TasksCollection::iterator i; - i = std::find_if(tasks_.begin(), tasks_.end(), [&cid] (TasksCollectionItem item)->bool { - return (cid == item.first); - }); + TasksCollection::iterator i; + i = std::find_if(tasks_.begin(), tasks_.end(), + [&cid](TasksCollectionItem item) -> bool { return (cid == item.first); }); - if (tasks_.end() == i) { - LoggerD("Not found cid"); - tasks_mutex_.unlock(); - return; - } - - i->second->attach(json); + if (tasks_.end() == i) { + LoggerD("Not found cid"); tasks_mutex_.unlock(); - - resolve(PostPriority::HIGH); return; + } + + i->second->attach(json); + tasks_mutex_.unlock(); + + resolve(PostPriority::HIGH); + return; } -void PostQueue::resolve(PostPriority p) -{ - LoggerD("Entered: [%p]", this); +void PostQueue::resolve(PostPriority p) { + LoggerD("Entered: [%p]", this); - TasksCollection::iterator i; + TasksCollection::iterator i; - tasks_mutex_.lock(); - i = std::find_if(tasks_.begin(), tasks_.end(), [&p] (TasksCollectionItem item)->bool { - return (p == item.second->priority()); - }); + tasks_mutex_.lock(); + i = std::find_if(tasks_.begin(), tasks_.end(), [&p](TasksCollectionItem item) -> bool { + return (p == item.second->priority()); + }); - if (tasks_.end() == i) { - // not found - tasks_mutex_.unlock(); + if (tasks_.end() == i) { + // not found + tasks_mutex_.unlock(); - if (PostPriority::LAST != p) { - return resolve(static_cast(p-1)); - } else { - return; - } + if (PostPriority::LAST != p) { + return resolve(static_cast(p - 1)); + } else { + return; } + } - if (TaskState::READY == i->second->state()) { - i->second->resolve(); - std::string json = i->second->json(); + if (TaskState::READY == i->second->state()) { + i->second->resolve(); + std::string json = i->second->json(); - i = tasks_.erase(i); - tasks_mutex_.unlock(); + i = tasks_.erase(i); + tasks_mutex_.unlock(); - Instance::PostMessage(&instance_, json.c_str()); - } else if (TaskState::NEW == i->second->state()) { - tasks_mutex_.unlock(); + Instance::PostMessage(&instance_, json.c_str()); + } else if (TaskState::NEW == i->second->state()) { + tasks_mutex_.unlock(); - return; - } else if (TaskState::DONE == i->second->state()) { - i = tasks_.erase(i); - tasks_mutex_.unlock(); - } + return; + } else if (TaskState::DONE == i->second->state()) { + i = tasks_.erase(i); + tasks_mutex_.unlock(); + } - return resolve(static_cast(p)); + return resolve(static_cast(p)); } -PostQueue::PostTask::PostTask() -{ - LoggerD("Entered"); - priority_ = PostPriority::LOW; - state_ = TaskState::NEW; +PostQueue::PostTask::PostTask() { + LoggerD("Entered"); + priority_ = PostPriority::LOW; + state_ = TaskState::NEW; } -PostQueue::PostTask::PostTask(PostPriority p) -{ - LoggerD("Entered"); - priority_ = p; - state_ = TaskState::NEW; +PostQueue::PostTask::PostTask(PostPriority p) { + LoggerD("Entered"); + priority_ = p; + state_ = TaskState::NEW; } -PostQueue::PostTask::~PostTask() -{ - LoggerD("Entered"); +PostQueue::PostTask::~PostTask() { + LoggerD("Entered"); } -void PostQueue::PostTask::attach(const std::string &j) -{ - LoggerD("Entered"); - if (TaskState::DONE == state_) { - return; - } - json_ = j; - state_ = TaskState::READY; +void PostQueue::PostTask::attach(const std::string& j) { + LoggerD("Entered"); + if (TaskState::DONE == state_) { return; + } + json_ = j; + state_ = TaskState::READY; + return; } -PostPriority PostQueue::PostTask::priority() -{ - return priority_; +PostPriority PostQueue::PostTask::priority() { + return priority_; } -PostQueue::TaskState PostQueue::PostTask::state() -{ - return state_; +PostQueue::TaskState PostQueue::PostTask::state() { + return state_; } -std::string PostQueue::PostTask::json() -{ - return json_; +std::string PostQueue::PostTask::json() { + return json_; } -void PostQueue::PostTask::resolve() -{ - LoggerD("Entered"); - if (TaskState::READY == state_) { - state_ = TaskState::DONE; - } - return; +void PostQueue::PostTask::resolve() { + LoggerD("Entered"); + if (TaskState::READY == state_) { + state_ = TaskState::DONE; + } + return; } - -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/messaging_util.h b/src/messaging/messaging_util.h index 136a5eb..bbd8926 100644 --- a/src/messaging/messaging_util.h +++ b/src/messaging/messaging_util.h @@ -17,23 +17,23 @@ #ifndef MESSAGING_MESSAGING_UTIL_H_ #define MESSAGING_MESSAGING_UTIL_H_ -#include -#include +#include #include #include -#include #include +#include +#include #include "common/logger.h" #include "common/picojson.h" #include "common/platform_result.h" -#include "MsgCommon/SortMode.h" -#include "MsgCommon/AttributeFilter.h" #include "MsgCommon/AbstractFilter.h" +#include "MsgCommon/AttributeFilter.h" +#include "MsgCommon/SortMode.h" -#include "message_folder.h" -#include "message_attachment.h" #include "common/platform_result.h" +#include "message_attachment.h" +#include "message_folder.h" namespace extension { namespace messaging { @@ -53,13 +53,13 @@ extern const char* MESSAGE_ATTRIBUTE_FOLDER_ID; extern const char* MESSAGE_ATTRIBUTE_TYPE; extern const char* MESSAGE_ATTRIBUTE_TIMESTAMP; extern const char* MESSAGE_ATTRIBUTE_FROM; -extern const char* MESSAGE_ATTRIBUTE_TO; // used also in dictionary -extern const char* MESSAGE_ATTRIBUTE_CC; // used also in dictionary -extern const char* MESSAGE_ATTRIBUTE_BCC; // used also in dictionary +extern const char* MESSAGE_ATTRIBUTE_TO; // used also in dictionary +extern const char* MESSAGE_ATTRIBUTE_CC; // used also in dictionary +extern const char* MESSAGE_ATTRIBUTE_BCC; // used also in dictionary extern const char* MESSAGE_ATTRIBUTE_BODY; extern const char* MESSAGE_ATTRIBUTE_IS_READ; -extern const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY; // used also in dictionary -extern const char* MESSAGE_ATTRIBUTE_SUBJECT; // used also in dictionary +extern const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY; // used also in dictionary +extern const char* MESSAGE_ATTRIBUTE_SUBJECT; // used also in dictionary extern const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO; extern const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS; extern const char* MESSAGE_ATTRIBUTE_ATTACHMENTS; @@ -94,20 +94,15 @@ extern const char* MESSAGE_CONVERSATION_ATTRIBUTE_CC; extern const char* MESSAGE_CONVERSATION_ATTRIBUTE_BCC; extern const char* MESSAGE_CONVERSATION_ATTRIBUTE_LAST_MESSAGE_ID; -enum MessageType { - UNDEFINED = 0, - SMS, - MMS, - EMAIL -}; +enum MessageType { UNDEFINED = 0, SMS, MMS, EMAIL }; enum MessageStatus { - STATUS_UNDEFINED = 0, - STATUS_DRAFT, - STATUS_SENDING, - STATUS_SENT, - STATUS_LOADED, - STATUS_FAILED + STATUS_UNDEFINED = 0, + STATUS_DRAFT, + STATUS_SENDING, + STATUS_SENT, + STATUS_LOADED, + STATUS_FAILED }; class Conversation; @@ -117,124 +112,115 @@ class MessageBody; class MessagingInstance; class MessagingUtil { -public: - static std::string messageFolderTypeToString(MessageFolderType); - static MessageFolderType stringToMessageFolderType(std::string type); - static common::PlatformResult stringToMessageType(const std::string& str, MessageType* out); - static common::PlatformResult messageTypeToString(MessageType type, std::string* out); - static std::string messageTypeToString(MessageType type); - static std::string ltrim(const std::string& input); - static std::string extractSingleEmailAddress(const std::string& address); - static std::vector extractEmailAddresses( - const std::vector& addresses); - - static picojson::value messageBodyToJson(std::shared_ptr body); - static picojson::value messageToJson(std::shared_ptr message); - static picojson::value messageAttachmentToJson(std::shared_ptr attachment); - static picojson::value conversationToJson(std::shared_ptr conversation); - static picojson::value folderToJson(std::shared_ptr folder); - static common::PlatformResult jsonToMessage(const picojson::value& json, - std::shared_ptr* result); - static std::shared_ptr jsonToMessageBody(const picojson::value& json); - static std::shared_ptr jsonToMessageFolder(const picojson::value& json); - static tizen::SortModePtr jsonToSortMode(const picojson::object& json); - static common::PlatformResult jsonToAbstractFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result); - static common::PlatformResult jsonToMessageConversation(const picojson::value& json, - std::shared_ptr* result_conversation); - static std::shared_ptr jsonToMessageAttachment(const picojson::value& json); - - template - static T getValueFromJSONObject(const picojson::object& v, const std::string& key) - { - picojson::value value; - try{ - value = v.at(key); - } catch(const std::out_of_range& e){ - return T(); - } - - if (value.is()) { - return value.get(); - } else { - return T(); - } + public: + static std::string messageFolderTypeToString(MessageFolderType); + static MessageFolderType stringToMessageFolderType(std::string type); + static common::PlatformResult stringToMessageType(const std::string& str, MessageType* out); + static common::PlatformResult messageTypeToString(MessageType type, std::string* out); + static std::string messageTypeToString(MessageType type); + static std::string ltrim(const std::string& input); + static std::string extractSingleEmailAddress(const std::string& address); + static std::vector extractEmailAddresses(const std::vector& addresses); + + static picojson::value messageBodyToJson(std::shared_ptr body); + static picojson::value messageToJson(std::shared_ptr message); + static picojson::value messageAttachmentToJson(std::shared_ptr attachment); + static picojson::value conversationToJson(std::shared_ptr conversation); + static picojson::value folderToJson(std::shared_ptr folder); + static common::PlatformResult jsonToMessage(const picojson::value& json, + std::shared_ptr* result); + static std::shared_ptr jsonToMessageBody(const picojson::value& json); + static std::shared_ptr jsonToMessageFolder(const picojson::value& json); + static tizen::SortModePtr jsonToSortMode(const picojson::object& json); + static common::PlatformResult jsonToAbstractFilter(const picojson::object& json, + tizen::AbstractFilterPtr* result); + static common::PlatformResult jsonToMessageConversation( + const picojson::value& json, std::shared_ptr* result_conversation); + static std::shared_ptr jsonToMessageAttachment(const picojson::value& json); + + template + static T getValueFromJSONObject(const picojson::object& v, const std::string& key) { + picojson::value value; + try { + value = v.at(key); + } catch (const std::out_of_range& e) { + return T(); } - /** - * Throws Common::IOException when file cannot be opened. - * - * To increase performance invoke this function this way: - * std::string result = loadFileContentToString(...); - * Reason: no copy constructor will be invoked on return. - */ - static common::PlatformResult loadFileContentToString(const std::string& file_path, std::string* result); - static std::string messageStatusToString(MessageStatus status); - -private: - static common::PlatformResult jsonFilterToAbstractFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result); - static common::PlatformResult jsonFilterToAttributeFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result); - static common::PlatformResult jsonFilterToAttributeRangeFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result); - static common::PlatformResult jsonFilterToCompositeFilter(const picojson::object& json, - tizen::AbstractFilterPtr* result); - - static std::string ConvertToUtf8(const std::string& file_path, const std::string& contents); -}; -enum PostPriority { - LAST = 0, - LOW, - MEDIUM, - HIGH + if (value.is()) { + return value.get(); + } else { + return T(); + } + } + /** + * Throws Common::IOException when file cannot be opened. + * + * To increase performance invoke this function this way: + * std::string result = loadFileContentToString(...); + * Reason: no copy constructor will be invoked on return. + */ + static common::PlatformResult loadFileContentToString(const std::string& file_path, + std::string* result); + static std::string messageStatusToString(MessageStatus status); + + private: + static common::PlatformResult jsonFilterToAbstractFilter(const picojson::object& json, + tizen::AbstractFilterPtr* result); + static common::PlatformResult jsonFilterToAttributeFilter(const picojson::object& json, + tizen::AbstractFilterPtr* result); + static common::PlatformResult jsonFilterToAttributeRangeFilter(const picojson::object& json, + tizen::AbstractFilterPtr* result); + static common::PlatformResult jsonFilterToCompositeFilter(const picojson::object& json, + tizen::AbstractFilterPtr* result); + + static std::string ConvertToUtf8(const std::string& file_path, const std::string& contents); }; +enum PostPriority { LAST = 0, LOW, MEDIUM, HIGH }; + class PostQueue { -public: - explicit PostQueue(MessagingInstance& instance); - ~PostQueue(); - - void addAndResolve(const long cid, PostPriority priority, const std::string &json); - void add(const long cid, PostPriority priority = PostPriority::LAST); - void resolve(const long cid, const std::string &json); - - enum TaskState { - NEW = 0, - READY, - DONE - }; - -private: - class PostTask; - typedef std::pair> TasksCollectionItem; - typedef std::vector TasksCollection; - - PostQueue(const PostQueue &); - void operator=(const PostQueue &); - void resolve(PostPriority p); - TasksCollection tasks_; - std::mutex tasks_mutex_; - - MessagingInstance& instance_; - - class PostTask { - public: - PostTask(); - PostTask(PostPriority p); - ~PostTask(); - void attach(const std::string &j); - PostPriority priority(); - TaskState state(); - std::string json(); - void resolve(); - private: - std::string json_; - PostPriority priority_; - TaskState state_; - }; + public: + explicit PostQueue(MessagingInstance& instance); + ~PostQueue(); + + void addAndResolve(const long cid, PostPriority priority, const std::string& json); + void add(const long cid, PostPriority priority = PostPriority::LAST); + void resolve(const long cid, const std::string& json); + + enum TaskState { NEW = 0, READY, DONE }; + + private: + class PostTask; + typedef std::pair> TasksCollectionItem; + typedef std::vector TasksCollection; + + PostQueue(const PostQueue&); + void operator=(const PostQueue&); + void resolve(PostPriority p); + TasksCollection tasks_; + std::mutex tasks_mutex_; + + MessagingInstance& instance_; + + class PostTask { + public: + PostTask(); + PostTask(PostPriority p); + ~PostTask(); + void attach(const std::string& j); + PostPriority priority(); + TaskState state(); + std::string json(); + void resolve(); + + private: + std::string json_; + PostPriority priority_; + TaskState state_; + }; }; -} // messaging -} // extension -#endif // MESSAGING_MESSAGING_UTIL_H_ +} // messaging +} // extension +#endif // MESSAGING_MESSAGING_UTIL_H_ diff --git a/src/messaging/short_message_manager.cc b/src/messaging/short_message_manager.cc old mode 100755 new mode 100644 index bf9ca8f..238d697 --- a/src/messaging/short_message_manager.cc +++ b/src/messaging/short_message_manager.cc @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #include -#include #include +#include #include -#include "common/platform_exception.h" #include "common/logger.h" +#include "common/platform_exception.h" #include "common/scope_exit.h" -#include "messaging_util.h" -#include "messaging_instance.h" #include "message_service.h" #include "message_sms.h" +#include "messaging_instance.h" +#include "messaging_util.h" //#include "MessageMMS.h" //#include "JSMessageConversation.h" #include "messaging_database_manager.h" @@ -39,167 +39,158 @@ using common::PlatformResult; namespace extension { namespace messaging { -ShortMsgManager& ShortMsgManager::getInstance() -{ - LoggerD("Entered"); +ShortMsgManager& ShortMsgManager::getInstance() { + LoggerD("Entered"); - static ShortMsgManager instance; - return instance; + static ShortMsgManager instance; + return instance; } -static gboolean sendMessageCompleteCB(void* data) -{ - LoggerD("Entered callback:%p", data); +static gboolean sendMessageCompleteCB(void* data) { + LoggerD("Entered callback:%p", data); - MessageRecipientsCallbackData* callback = - static_cast(data); - if (!callback) { - LoggerE("Callback is null"); - return false; - } + MessageRecipientsCallbackData* callback = static_cast(data); + if (!callback) { + LoggerE("Callback is null"); + return false; + } - if (callback->IsError()) { - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); - } - else { - std::shared_ptr message = callback->getMessage(); + if (callback->IsError()) { + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); + } else { + std::shared_ptr message = callback->getMessage(); - LoggerD("Calling success callback with: %d recipients", message->getTO().size()); + LoggerD("Calling success callback with: %d recipients", message->getTO().size()); - std::vector recipients; - auto addToRecipients = [&recipients](std::string& e)->void { - recipients.push_back(picojson::value(e)); - }; + std::vector recipients; + auto addToRecipients = [&recipients](std::string& e) -> void { + recipients.push_back(picojson::value(e)); + }; - auto toVect = callback->getMessage()->getTO(); - std::for_each(toVect.begin(), toVect.end(), addToRecipients); + auto toVect = callback->getMessage()->getTO(); + std::for_each(toVect.begin(), toVect.end(), addToRecipients); - picojson::object data; - data[JSON_DATA_RECIPIENTS] = picojson::value(recipients); - data[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(message); + picojson::object data; + data[JSON_DATA_RECIPIENTS] = picojson::value(recipients); + data[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(message); - callback->SetSuccess(picojson::value(data)); - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT); - } + callback->SetSuccess(picojson::value(data)); + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return false; + return false; } -static gboolean addDraftMessageCompleteCB(void *data) -{ - LoggerD("Enter"); - auto callback = static_cast(data); - if (!callback) { - LoggerE("Callback is null"); - return FALSE; - } +static gboolean addDraftMessageCompleteCB(void* data) { + LoggerD("Enter"); + auto callback = static_cast(data); + if (!callback) { + LoggerE("Callback is null"); + return FALSE; + } - if (callback->IsError()) { - LoggerD("Calling error callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); - callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); - } else { - LoggerD("Calling success callback"); + callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED); + } else { + LoggerD("Calling success callback"); - picojson::object args; - args[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); + picojson::object args; + args[JSON_DATA_MESSAGE] = MessagingUtil::messageToJson(callback->getMessage()); - callback->SetSuccess(picojson::value(args)); - } + callback->SetSuccess(picojson::value(args)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; - return FALSE; + return FALSE; } +PlatformResult ShortMsgManager::addDraftMessagePlatform(std::shared_ptr message) { + LoggerD("Add new message(%p)", message.get()); -PlatformResult ShortMsgManager::addDraftMessagePlatform(std::shared_ptr message) -{ - LoggerD("Add new message(%p)", message.get()); - - // Save platform msg to get ID - msg_struct_t platform_msg = nullptr; - PlatformResult ret = Message::convertPlatformShortMessageToStruct(message.get(), - m_msg_handle, &platform_msg); - if (ret.IsError()) { - LoggerD("Convert Platform Short Message to Struct failed (%s)", ret.message().c_str()); - return ret; - } + // Save platform msg to get ID + msg_struct_t platform_msg = nullptr; + PlatformResult ret = + Message::convertPlatformShortMessageToStruct(message.get(), m_msg_handle, &platform_msg); + if (ret.IsError()) { + LoggerD("Convert Platform Short Message to Struct failed (%s)", ret.message().c_str()); + return ret; + } - if (NULL == platform_msg) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot prepare platform message"); - } + if (NULL == platform_msg) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot prepare platform message"); + } - msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); - msg_set_bool_value(send_opt, MSG_SEND_OPT_SETTING_BOOL, false); - const int msg_id = msg_add_message(m_msg_handle, platform_msg, send_opt); - if (msg_id < MSG_SUCCESS) { - msg_release_struct(&send_opt); - msg_release_struct(&platform_msg); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot add message to draft", - ("Message(%p): Failed to add draft, error: %d", message.get(), msg_id)); - } + msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); + msg_set_bool_value(send_opt, MSG_SEND_OPT_SETTING_BOOL, false); + const int msg_id = msg_add_message(m_msg_handle, platform_msg, send_opt); + if (msg_id < MSG_SUCCESS) { + msg_release_struct(&send_opt); + msg_release_struct(&platform_msg); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Cannot add message to draft", + ("Message(%p): Failed to add draft, error: %d", message.get(), msg_id)); + } - LoggerD("Message(%p): New message ID: %d", message.get(), msg_id); - msg_set_int_value(platform_msg, MSG_MESSAGE_ID_INT, msg_id); - message->setId(msg_id); - message->setMessageStatus(MessageStatus::STATUS_DRAFT); - - msg_struct_t msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO); - msg_error_t err = msg_get_conversation(m_msg_handle, msg_id, msg_conv); - if (MSG_SUCCESS == err) { - int conversationId = 0; - msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, &conversationId); - message->setConversationId(conversationId); - } else { - LoggerE("Message(%p): Failed to get conv: %d (%s)", message.get(), err, get_error_message(err)); - } - Message* msgInfo = nullptr; - ret = Message::convertPlatformShortMessageToObject( - platform_msg, &msgInfo); - if (ret.IsError()) { - LoggerD("Convert Platform Short Message to Object failed (%s)", ret.message().c_str()); - return ret; - } - const int folderId = msgInfo->getFolderId(); - message->setFolderId(folderId); - const time_t timestamp = msgInfo->getTimestamp(); - message->setTimeStamp(timestamp); + LoggerD("Message(%p): New message ID: %d", message.get(), msg_id); + msg_set_int_value(platform_msg, MSG_MESSAGE_ID_INT, msg_id); + message->setId(msg_id); + message->setMessageStatus(MessageStatus::STATUS_DRAFT); + + msg_struct_t msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO); + msg_error_t err = msg_get_conversation(m_msg_handle, msg_id, msg_conv); + if (MSG_SUCCESS == err) { + int conversationId = 0; + msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, &conversationId); + message->setConversationId(conversationId); + } else { + LoggerE("Message(%p): Failed to get conv: %d (%s)", message.get(), err, get_error_message(err)); + } + Message* msgInfo = nullptr; + ret = Message::convertPlatformShortMessageToObject(platform_msg, &msgInfo); + if (ret.IsError()) { + LoggerD("Convert Platform Short Message to Object failed (%s)", ret.message().c_str()); + return ret; + } + const int folderId = msgInfo->getFolderId(); + message->setFolderId(folderId); + const time_t timestamp = msgInfo->getTimestamp(); + message->setTimeStamp(timestamp); - const std::string from = msgInfo->getFrom(); - LoggerD("From: %s", from.c_str()); - message->setFrom(from); + const std::string from = msgInfo->getFrom(); + LoggerD("From: %s", from.c_str()); + message->setFrom(from); - const bool isRead = msgInfo->getIsRead(); - message->setIsRead(isRead); + const bool isRead = msgInfo->getIsRead(); + message->setIsRead(isRead); - const int inResponseTo = msgInfo->getInResponseTo(); - message->setInResponseTo(inResponseTo); + const int inResponseTo = msgInfo->getInResponseTo(); + message->setInResponseTo(inResponseTo); - if (msg_release_struct(&platform_msg) != MSG_SUCCESS) { - LoggerW("Platform message is already destroyed"); - } - if (msg_release_struct(&msg_conv) != MSG_SUCCESS) { - LoggerW("Platform message is already destroyed"); - } - if (msg_release_struct(&send_opt) != MSG_SUCCESS) { - LoggerW("Platform message is already destroyed"); - } - delete msgInfo; - return PlatformResult(ErrorCode::NO_ERROR); + if (msg_release_struct(&platform_msg) != MSG_SUCCESS) { + LoggerW("Platform message is already destroyed"); + } + if (msg_release_struct(&msg_conv) != MSG_SUCCESS) { + LoggerW("Platform message is already destroyed"); + } + if (msg_release_struct(&send_opt) != MSG_SUCCESS) { + LoggerW("Platform message is already destroyed"); + } + delete msgInfo; + return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackData* callback) -{ +PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackData* callback) { LoggerD("Entered"); std::lock_guard lock(m_mutex); @@ -218,12 +209,11 @@ PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackDat // if it is draft message just send it // in other case create new platform message // add it to draft and finally send it - if (!( message->is_id_set() && MessageStatus::STATUS_DRAFT == msg_status)) { + if (!(message->is_id_set() && MessageStatus::STATUS_DRAFT == msg_status)) { LoggerD("Add message to draft"); platform_result = addDraftMessagePlatform(message); - } - if(platform_result.IsSuccess()) { + if (platform_result.IsSuccess()) { msg_id = message->getId(); LoggerD("Message ID: %d", msg_id); @@ -232,9 +222,9 @@ PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackDat msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO); ret = msg_get_message(m_msg_handle, msg_id, platform_msg, send_opt); if (MSG_SUCCESS != ret) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure", - ("msg_get_message error: %d (%s)", ret, get_error_message(ret))); + platform_result = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure", + ("msg_get_message error: %d (%s)", ret, get_error_message(ret))); } else { // Send message message->setMessageStatus(MessageStatus::STATUS_SENDING); @@ -244,49 +234,45 @@ PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackDat int req_id = -1; ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id); if (MSG_SUCCESS != ret) { - platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get send request ID", - ("msg_get_int_value error: %d (%s)", ret, get_error_message(ret))); + platform_result = + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get send request ID", + ("msg_get_int_value error: %d (%s)", ret, get_error_message(ret))); } else { if (MessageType::MMS == message->getType()) { LoggerD("Send MMS message"); ret = msg_mms_send_message(m_msg_handle, req); - } - else if (MessageType::SMS == message->getType()) { + } else if (MessageType::SMS == message->getType()) { LoggerD("Send SMS message"); ret = msg_sms_send_message(m_msg_handle, req); - } - else { - platform_result = LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Invalid message type", - ("Invalid message type: %d", message->getType())); + } else { + platform_result = LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid message type", + ("Invalid message type: %d", message->getType())); } if (platform_result) { if (ret != MSG_SUCCESS) { platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to send message", - ("Failed to send message: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Failed to send message", + ("Failed to send message: %d (%s)", ret, get_error_message(ret))); } else { ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id); if (ret != MSG_SUCCESS) { platform_result = LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get send request", - ("Failed to get message request ID: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Failed to get send request", + ("Failed to get message request ID: %d (%s)", ret, get_error_message(ret))); } if (platform_result.IsSuccess()) { LoggerD("req_id: %d", req_id); - platform_result = Message::convertPlatformShortMessageToObject(platform_msg, &msgInfo); + platform_result = + Message::convertPlatformShortMessageToObject(platform_msg, &msgInfo); if (platform_result.IsSuccess()) { - int conversationId; ret = msg_get_conversation(m_msg_handle, msg_id, msg_conv); if (MSG_SUCCESS != ret) { LoggerE("Failed to get conv"); } - msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, - &conversationId); + msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, &conversationId); message->setConversationId(conversationId); int folderId = msgInfo->getFolderId(); @@ -333,11 +319,10 @@ PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackDat return platform_result; } -PlatformResult ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callback) -{ +PlatformResult ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callback) { LoggerD("Entered"); - if (!callback){ + if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } @@ -359,859 +344,806 @@ PlatformResult ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callb return platform_result; } -void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status) -{ - LoggerD("Entered"); - int reqId = 0; - int status = MSG_NETWORK_NOT_SEND; - - msg_get_int_value(sent_status, MSG_SENT_STATUS_REQUESTID_INT, &reqId); - LoggerD("Send msg %d", reqId); - msg_get_int_value(sent_status, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status); - LoggerD("Send msg status: %d", status); - - if(MSG_NETWORK_SEND_SUCCESS != status - && MSG_NETWORK_SEND_FAIL != status - && MSG_NETWORK_SEND_TIMEOUT != status) - { - LoggerD("Not final status, return"); - return; - } +void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status) { + LoggerD("Entered"); + int reqId = 0; + int status = MSG_NETWORK_NOT_SEND; - std::lock_guard lock(m_mutex); - SendReqMap::iterator it = m_sendRequests.find(reqId); - if (it != m_sendRequests.end()) { - LoggerD("Matching request found"); - - MessageRecipientsCallbackData* callback = it->second; - m_sendRequests.erase(it); - - if (MSG_NETWORK_SEND_FAIL == status - || MSG_NETWORK_SEND_TIMEOUT == status) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Send message failed", - ("req_id:%d : Failed sending Message(%p) with msg_id:%d msg status is: %s", - reqId, - callback->getMessage().get(), - callback->getMessage()->getId(), - (MSG_NETWORK_SEND_FAIL == status ? "FAIL" : "TIMEOUT")))); + msg_get_int_value(sent_status, MSG_SENT_STATUS_REQUESTID_INT, &reqId); + LoggerD("Send msg %d", reqId); + msg_get_int_value(sent_status, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status); + LoggerD("Send msg status: %d", status); - } + if (MSG_NETWORK_SEND_SUCCESS != status && MSG_NETWORK_SEND_FAIL != status && + MSG_NETWORK_SEND_TIMEOUT != status) { + LoggerD("Not final status, return"); + return; + } - if (!g_idle_add(sendMessageCompleteCB, static_cast(callback))) { - LoggerE("g_idle addition failed"); - delete callback; - callback = NULL; - } + std::lock_guard lock(m_mutex); + SendReqMap::iterator it = m_sendRequests.find(reqId); + if (it != m_sendRequests.end()) { + LoggerD("Matching request found"); + + MessageRecipientsCallbackData* callback = it->second; + m_sendRequests.erase(it); + + if (MSG_NETWORK_SEND_FAIL == status || MSG_NETWORK_SEND_TIMEOUT == status) { + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Send message failed", + ("req_id:%d : Failed sending Message(%p) with msg_id:%d msg status is: %s", reqId, + callback->getMessage().get(), callback->getMessage()->getId(), + (MSG_NETWORK_SEND_FAIL == status ? "FAIL" : "TIMEOUT")))); } - else { - LoggerE("No matching request found"); + + if (!g_idle_add(sendMessageCompleteCB, static_cast(callback))) { + LoggerE("g_idle addition failed"); + delete callback; + callback = NULL; } + } else { + LoggerE("No matching request found"); + } - return; + return; } -static void sent_status_cb(msg_handle_t handle, - msg_struct_t sent_status, - void *data) -{ - LoggerD("Entered"); - ShortMsgManager::getInstance().sendStatusCallback(sent_status); +static void sent_status_cb(msg_handle_t handle, msg_struct_t sent_status, void* data) { + LoggerD("Entered"); + ShortMsgManager::getInstance().sendStatusCallback(sent_status); - return; + return; } -PlatformResult ShortMsgManager::callProperEventMessages(EventMessages* event, - msg_storage_change_type_t storageChangeType) -{ - LoggerD("Entered event.items.size()=%d event.removed_conversations.size()=%d" - " sChangeType:%d", event->items.size(), - event->removed_conversations.size(), storageChangeType); +PlatformResult ShortMsgManager::callProperEventMessages( + EventMessages* event, msg_storage_change_type_t storageChangeType) { + LoggerD( + "Entered event.items.size()=%d event.removed_conversations.size()=%d" + " sChangeType:%d", + event->items.size(), event->removed_conversations.size(), storageChangeType); - EventConversations* eventConv = new EventConversations(); - eventConv->service_id = event->service_id; - eventConv->service_type = event->service_type; + EventConversations* eventConv = new EventConversations(); + eventConv->service_id = event->service_id; + eventConv->service_type = event->service_type; - if(MSG_STORAGE_CHANGE_DELETE == storageChangeType) { - eventConv->items = event->removed_conversations; - } else { - PlatformResult ret = ShortMsgManager::getConversationsForMessages( - event->items, storageChangeType, &(eventConv->items)); - if (ret.IsError()) { - LoggerD("Error while getting conversations for message"); - delete event; - delete eventConv; - return ret; - } + if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) { + eventConv->items = event->removed_conversations; + } else { + PlatformResult ret = ShortMsgManager::getConversationsForMessages( + event->items, storageChangeType, &(eventConv->items)); + if (ret.IsError()) { + LoggerD("Error while getting conversations for message"); + delete event; + delete eventConv; + return ret; } + } - switch (storageChangeType) { - case MSG_STORAGE_CHANGE_INSERT: { - ChangeListenerContainer::getInstance().callMessageAdded(event); - if (!eventConv->items.empty()) { - - ConversationPtrVector added_conv; - ConversationPtrVector updated_conv; - - for(ConversationPtrVector::iterator it = eventConv->items.begin(); - it != eventConv->items.end(); ++it) { - ConversationPtr cur_conv = *it; - const bool new_conv = (cur_conv->getMessageCount() <= 1); - if(new_conv) { - added_conv.push_back(cur_conv); - } else { - updated_conv.push_back(cur_conv); - } - - LoggerD("%s conversation with id:%d last_msg_id:d", - (new_conv ? "ADDED" : "UPDATED"), - cur_conv->getConversationId(), cur_conv->getLastMessageId()); - } + switch (storageChangeType) { + case MSG_STORAGE_CHANGE_INSERT: { + ChangeListenerContainer::getInstance().callMessageAdded(event); + if (!eventConv->items.empty()) { + ConversationPtrVector added_conv; + ConversationPtrVector updated_conv; + + for (ConversationPtrVector::iterator it = eventConv->items.begin(); + it != eventConv->items.end(); ++it) { + ConversationPtr cur_conv = *it; + const bool new_conv = (cur_conv->getMessageCount() <= 1); + if (new_conv) { + added_conv.push_back(cur_conv); + } else { + updated_conv.push_back(cur_conv); + } - LoggerD("num conversations:all=%d added=%d update=%d", eventConv->items.size(), - added_conv.size(), updated_conv.size()); + LoggerD("%s conversation with id:%d last_msg_id:d", (new_conv ? "ADDED" : "UPDATED"), + cur_conv->getConversationId(), cur_conv->getLastMessageId()); + } - if(false == added_conv.empty()) { - LoggerD("%d new conversations, calling onConversationAdded", - added_conv.size()); - eventConv->items = added_conv; - ChangeListenerContainer::getInstance().callConversationAdded( - eventConv); - } + LoggerD("num conversations:all=%d added=%d update=%d", eventConv->items.size(), + added_conv.size(), updated_conv.size()); - if(false == updated_conv.empty()) { - LoggerD("%d updated conversation, calling onConversationUpdated", - updated_conv.size()); - eventConv->items = updated_conv; - ChangeListenerContainer::getInstance().callConversationUpdated( - eventConv); - } + if (false == added_conv.empty()) { + LoggerD("%d new conversations, calling onConversationAdded", added_conv.size()); + eventConv->items = added_conv; + ChangeListenerContainer::getInstance().callConversationAdded(eventConv); + } - } - } break; - case MSG_STORAGE_CHANGE_DELETE: { - ChangeListenerContainer::getInstance().callMessageRemoved(event); - - if(false == eventConv->items.empty()) { - LoggerD("At least one conversation will be deleted, " - "triggering also onConversationRemoved"); - ChangeListenerContainer::getInstance().callConversationRemoved(eventConv); - } - } break; - case MSG_STORAGE_CHANGE_UPDATE: { - ChangeListenerContainer::getInstance().callMessageUpdated(event); - ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); - } break; - default: - LoggerW("Unknown storageChangeType: %d", storageChangeType); - } - delete event; - delete eventConv; - return PlatformResult(ErrorCode::NO_ERROR); + if (false == updated_conv.empty()) { + LoggerD("%d updated conversation, calling onConversationUpdated", updated_conv.size()); + eventConv->items = updated_conv; + ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); + } + } + } break; + case MSG_STORAGE_CHANGE_DELETE: { + ChangeListenerContainer::getInstance().callMessageRemoved(event); + + if (false == eventConv->items.empty()) { + LoggerD( + "At least one conversation will be deleted, " + "triggering also onConversationRemoved"); + ChangeListenerContainer::getInstance().callConversationRemoved(eventConv); + } + } break; + case MSG_STORAGE_CHANGE_UPDATE: { + ChangeListenerContainer::getInstance().callMessageUpdated(event); + ChangeListenerContainer::getInstance().callConversationUpdated(eventConv); + } break; + default: + LoggerW("Unknown storageChangeType: %d", storageChangeType); + } + delete event; + delete eventConv; + return PlatformResult(ErrorCode::NO_ERROR); } void ShortMsgManager::storage_change_cb(msg_handle_t handle, - msg_storage_change_type_t storageChangeType, - msg_id_list_s *pMsgIdList, - void* data) -{ - LoggerD("Entered handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType, - pMsgIdList->nCount); - - if (MSG_STORAGE_CHANGE_CONTACT == storageChangeType) { - LoggerD("storageChangeType is MSG_STORAGE_CHANGE_CONTACT, ignoring"); - return; - } + msg_storage_change_type_t storageChangeType, + msg_id_list_s* pMsgIdList, void* data) { + LoggerD("Entered handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType, + pMsgIdList->nCount); - if (pMsgIdList->nCount < 1) { - LoggerW("no messages in callback list"); - return; - } + if (MSG_STORAGE_CHANGE_CONTACT == storageChangeType) { + LoggerD("storageChangeType is MSG_STORAGE_CHANGE_CONTACT, ignoring"); + return; + } - LoggerD("Messages count %d", pMsgIdList->nCount); - - /* - * There is possibility that in one callback from msg service will come - * SMS and MMS messages in the same list. ChangeListenerContainer requires - * that messages in event have common service_id and service_type. So we - * create here 2 events: one for SMS and one for MMS. If one of events - * has empty message list, we won't trigger it. - */ - EventMessages* eventSMS = NULL; - EventMessages* eventMMS = NULL; - - // if allocation below fails than exception is thrown - no NULL check - eventSMS = new EventMessages(); - eventSMS->service_type = MessageType::SMS; - eventSMS->service_id = SMS_ACCOUNT_ID; - eventMMS = new EventMessages(); - eventMMS->service_type = MessageType::MMS; - eventMMS->service_id = MMS_ACCOUNT_ID; - - if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) { - - ShortMsgManager& msg_manager = ShortMsgManager::getInstance(); - std::lock_guard lock(msg_manager.m_mutex); - - std::map* rem_msgs[2] = { // Recently removed messages - &msg_manager.m_sms_removed_messages, - &msg_manager.m_mms_removed_messages }; - std::map* rem_convs[2] = { // Recently removed conversations - &msg_manager.m_sms_removed_msg_id_conv_id_map, - &msg_manager.m_mms_removed_msg_id_conv_id_map }; - EventMessages* dest_event[2] = { // SMS/MMS EventMessage to be propagated - eventSMS, - eventMMS }; - std::map* conv_map[2] = { //Map conversationId - object - &msg_manager.m_sms_removed_conv_id_object_map, - &msg_manager.m_mms_removed_conv_id_object_map }; - - for(int event_i = 0; event_i < 2; ++event_i) { - - std::map& cur_rem_msgs = *(rem_msgs[event_i]); - std::map& cur_rem_convs = *(rem_convs[event_i]); - EventMessages* cur_dest_event = dest_event[event_i]; - std::map& cur_conv_map = *(conv_map[event_i]); - std::unordered_set conv_rem_now; - - for (int i = 0; i < pMsgIdList->nCount; ++i) { - const msg_message_id_t& msg_id = pMsgIdList->msgIdList[i]; - LoggerD("pMsgIdList[%d] = %d", i, msg_id); - - std::map ::iterator it = cur_rem_msgs.find(msg_id); - if(it != cur_rem_msgs.end()) { - LoggerD("[%d] is %s, Pushing message with id:%d subject:%s", i, - (0 == i) ? "SMS" : "MMS", - it->second->getId(), - it->second->getSubject().c_str()); - cur_dest_event->items.push_back(it->second); - cur_rem_msgs.erase(it); - } + if (pMsgIdList->nCount < 1) { + LoggerW("no messages in callback list"); + return; + } - std::map::iterator cit = cur_rem_convs.find(msg_id); - if(cit != cur_rem_convs.end()) { - conv_rem_now.insert(cit->second); - cur_rem_convs.erase(cit); - } - } + LoggerD("Messages count %d", pMsgIdList->nCount); + + /* + * There is possibility that in one callback from msg service will come + * SMS and MMS messages in the same list. ChangeListenerContainer requires + * that messages in event have common service_id and service_type. So we + * create here 2 events: one for SMS and one for MMS. If one of events + * has empty message list, we won't trigger it. + */ + EventMessages* eventSMS = NULL; + EventMessages* eventMMS = NULL; + + // if allocation below fails than exception is thrown - no NULL check + eventSMS = new EventMessages(); + eventSMS->service_type = MessageType::SMS; + eventSMS->service_id = SMS_ACCOUNT_ID; + eventMMS = new EventMessages(); + eventMMS->service_type = MessageType::MMS; + eventMMS->service_id = MMS_ACCOUNT_ID; + + if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) { + ShortMsgManager& msg_manager = ShortMsgManager::getInstance(); + std::lock_guard lock(msg_manager.m_mutex); + + std::map* rem_msgs[2] = { + // Recently removed messages + &msg_manager.m_sms_removed_messages, &msg_manager.m_mms_removed_messages}; + std::map* rem_convs[2] = {// Recently removed conversations + &msg_manager.m_sms_removed_msg_id_conv_id_map, + &msg_manager.m_mms_removed_msg_id_conv_id_map}; + EventMessages* dest_event[2] = {// SMS/MMS EventMessage to be propagated + eventSMS, eventMMS}; + std::map* conv_map[2] = {// Map conversationId - object + &msg_manager.m_sms_removed_conv_id_object_map, + &msg_manager.m_mms_removed_conv_id_object_map}; + + for (int event_i = 0; event_i < 2; ++event_i) { + std::map& cur_rem_msgs = *(rem_msgs[event_i]); + std::map& cur_rem_convs = *(rem_convs[event_i]); + EventMessages* cur_dest_event = dest_event[event_i]; + std::map& cur_conv_map = *(conv_map[event_i]); + std::unordered_set conv_rem_now; + + for (int i = 0; i < pMsgIdList->nCount; ++i) { + const msg_message_id_t& msg_id = pMsgIdList->msgIdList[i]; + LoggerD("pMsgIdList[%d] = %d", i, msg_id); + + std::map::iterator it = cur_rem_msgs.find(msg_id); + if (it != cur_rem_msgs.end()) { + LoggerD("[%d] is %s, Pushing message with id:%d subject:%s", i, (0 == i) ? "SMS" : "MMS", + it->second->getId(), it->second->getSubject().c_str()); + cur_dest_event->items.push_back(it->second); + cur_rem_msgs.erase(it); + } - for (auto it = conv_rem_now.begin(); it != conv_rem_now.end(); it++) { - const int cur_rem_conv_id = *it; - - //--------------------------------------------------------------------- - // Check if we have removed last message from conversation - // - bool found = false; - for(auto it2 = cur_rem_convs.begin(); - it2 != cur_rem_convs.end(); - it2++) { - if( cur_rem_conv_id == it2->second) { - found = true; - break; - } - } + std::map::iterator cit = cur_rem_convs.find(msg_id); + if (cit != cur_rem_convs.end()) { + conv_rem_now.insert(cit->second); + cur_rem_convs.erase(cit); + } + } - if(false == found) { - //We have removed last message from conversation - - std::map::iterator conv_it = - cur_conv_map.find(cur_rem_conv_id); - if(conv_it != cur_conv_map.end()) { - LoggerD("Pushing removed %s MessageConversation(%p) with id:%d", - (0 == event_i) ? "SMS" : "MMS", - conv_it->second.get(), cur_rem_conv_id); - - cur_dest_event->removed_conversations.push_back( - conv_it->second); - cur_conv_map.erase(conv_it); - } else { - LoggerW("Couldn't find ConversationPtr object with id:%d", - cur_rem_conv_id); - } - } - } + for (auto it = conv_rem_now.begin(); it != conv_rem_now.end(); it++) { + const int cur_rem_conv_id = *it; + + //--------------------------------------------------------------------- + // Check if we have removed last message from conversation + // + bool found = false; + for (auto it2 = cur_rem_convs.begin(); it2 != cur_rem_convs.end(); it2++) { + if (cur_rem_conv_id == it2->second) { + found = true; + break; + } } - } else { - PlatformResult ret(ErrorCode::NO_ERROR); - for (int i = 0; i < pMsgIdList->nCount; ++i) { - - msg_struct_t msg; - ret = ShortMsgManager::getInstance().getMessage(pMsgIdList->msgIdList[i], &msg); - if (ret.IsError() || NULL == msg) { - LoggerE("Failed to load short message"); - delete eventSMS; - eventSMS = NULL; - delete eventMMS; - eventMMS = NULL; - return; - } - std::shared_ptr message; - Message* message_ptr = nullptr; - ret = Message::convertPlatformShortMessageToObject(msg, &message_ptr); - if (ret.IsError()) { - LoggerE("Failed to load short message"); - msg_release_struct(&msg); - delete eventSMS; - eventSMS = NULL; - delete eventMMS; - eventMMS = NULL; - return; - } - message.reset(message_ptr); - msg_release_struct(&msg); - switch (message->getType()) { - case MessageType::SMS: - eventSMS->items.push_back(message); - break; - case MessageType::MMS: - eventMMS->items.push_back(message); - break; - default: - LoggerE("Unsupported message type"); - delete eventSMS; - eventSMS = NULL; - delete eventMMS; - eventMMS = NULL; - return; - } + if (false == found) { + // We have removed last message from conversation + + std::map::iterator conv_it = cur_conv_map.find(cur_rem_conv_id); + if (conv_it != cur_conv_map.end()) { + LoggerD("Pushing removed %s MessageConversation(%p) with id:%d", + (0 == event_i) ? "SMS" : "MMS", conv_it->second.get(), cur_rem_conv_id); + + cur_dest_event->removed_conversations.push_back(conv_it->second); + cur_conv_map.erase(conv_it); + } else { + LoggerW("Couldn't find ConversationPtr object with id:%d", cur_rem_conv_id); + } } + } } - if (!eventSMS->items.empty() || !eventSMS->removed_conversations.empty()) { - PlatformResult ret = ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType); - //PlatformResult could be ignored here. eventSMS is deleted in callProperEventMessages() - } else { - LoggerD("No SMS messages, not triggering eventSMS"); + } else { + PlatformResult ret(ErrorCode::NO_ERROR); + for (int i = 0; i < pMsgIdList->nCount; ++i) { + msg_struct_t msg; + ret = ShortMsgManager::getInstance().getMessage(pMsgIdList->msgIdList[i], &msg); + if (ret.IsError() || NULL == msg) { + LoggerE("Failed to load short message"); + delete eventSMS; + eventSMS = NULL; + delete eventMMS; + eventMMS = NULL; + return; + } + std::shared_ptr message; + Message* message_ptr = nullptr; + ret = Message::convertPlatformShortMessageToObject(msg, &message_ptr); + if (ret.IsError()) { + LoggerE("Failed to load short message"); + msg_release_struct(&msg); delete eventSMS; eventSMS = NULL; - } - if (!eventMMS->items.empty() || !eventMMS->removed_conversations.empty()) { - PlatformResult ret = ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType); - //PlatformResult could be ignored here. eventMMS is deleted in callProperEventMessages() - } else { - LoggerD("No MMS messages, not triggering eventMMS"); delete eventMMS; eventMMS = NULL; + return; + } + message.reset(message_ptr); + msg_release_struct(&msg); + switch (message->getType()) { + case MessageType::SMS: + eventSMS->items.push_back(message); + break; + case MessageType::MMS: + eventMMS->items.push_back(message); + break; + default: + LoggerE("Unsupported message type"); + delete eventSMS; + eventSMS = NULL; + delete eventMMS; + eventMMS = NULL; + return; + } } + } + + if (!eventSMS->items.empty() || !eventSMS->removed_conversations.empty()) { + PlatformResult ret = ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType); + // PlatformResult could be ignored here. eventSMS is deleted in callProperEventMessages() + } else { + LoggerD("No SMS messages, not triggering eventSMS"); + delete eventSMS; + eventSMS = NULL; + } + if (!eventMMS->items.empty() || !eventMMS->removed_conversations.empty()) { + PlatformResult ret = ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType); + // PlatformResult could be ignored here. eventMMS is deleted in callProperEventMessages() + } else { + LoggerD("No MMS messages, not triggering eventMMS"); + delete eventMMS; + eventMMS = NULL; + } } -void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle) -{ - LoggerD("Entered"); - m_msg_handle = msg_handle; - // set message sent status callback - if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle, - &sent_status_cb, NULL)) { - LoggerE("sent status callback register error!!!"); - } - if (MSG_SUCCESS != msg_reg_storage_change_callback(m_msg_handle, - &storage_change_cb, NULL)) { - LoggerE("storage change callback register error!"); - } +void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle) { + LoggerD("Entered"); + m_msg_handle = msg_handle; + // set message sent status callback + if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle, &sent_status_cb, NULL)) { + LoggerE("sent status callback register error!!!"); + } + if (MSG_SUCCESS != msg_reg_storage_change_callback(m_msg_handle, &storage_change_cb, NULL)) { + LoggerE("storage change callback register error!"); + } } -void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback) -{ - LoggerD("Enter"); +void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback) { + LoggerD("Enter"); - if(!callback){ - LoggerE("Callback is null"); - return; - } - { - std::lock_guard lock(m_mutex); - std::shared_ptr message = callback->getMessage(); + if (!callback) { + LoggerE("Callback is null"); + return; + } + { + std::lock_guard lock(m_mutex); + std::shared_ptr message = callback->getMessage(); - PlatformResult ret = addDraftMessagePlatform(message); - if (ret.IsError()) { - LoggerE("%d (%s)", ret.error_code(), ret.message().c_str()); - callback->SetError(ret); - } + PlatformResult ret = addDraftMessagePlatform(message); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), ret.message().c_str()); + callback->SetError(ret); } + } - // Complete task - if (!g_idle_add(addDraftMessageCompleteCB, static_cast(callback))) { - LoggerE("g_idle addition failed"); - delete callback; - callback = NULL; - } + // Complete task + if (!g_idle_add(addDraftMessageCompleteCB, static_cast(callback))) { + LoggerE("g_idle addition failed"); + delete callback; + callback = NULL; + } } -void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; + if (!callback) { + LoggerE("Callback is null"); + return; + } + + std::vector> messages; + + { + std::lock_guard lock(m_mutex); + messages = callback->getMessages(); + MessageType type = callback->getMessageServiceType(); + for (auto it = messages.begin(); it != messages.end(); ++it) { + if ((*it)->getType() != type) { + callback->SetError(LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, + "Error while deleting message", + ("Invalid message type: %d", (*it)->getType()))); + break; + } } - std::vector> messages; - - { - std::lock_guard lock(m_mutex); - messages = callback->getMessages(); - MessageType type = callback->getMessageServiceType(); - for(auto it = messages.begin() ; it != messages.end(); ++it) { - if((*it)->getType() != type) { - callback->SetError(LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting message", - ("Invalid message type: %d", (*it)->getType()))); - break; - } + if (!callback->IsError()) { + for (auto it = messages.begin(); it != messages.end(); ++it) { + const int id = (*it)->getId(); + + // Store message object + LoggerD("Storing removed message (id:%d) in m_removed_messages", id); + switch ((*it)->getType()) { + case SMS: + m_sms_removed_messages[id] = (*it); + break; + case MMS: + m_mms_removed_messages[id] = (*it); + break; + default: + LoggerD("Unknown message type: %d", (*it)->getType()); + break; } - if (!callback->IsError()) { - for (auto it = messages.begin() ; it != messages.end(); ++it) { - const int id = (*it)->getId(); - - //Store message object - LoggerD("Storing removed message (id:%d) in m_removed_messages", id); - switch((*it)->getType()) { - - case SMS: m_sms_removed_messages[id] = (*it); break; - case MMS: m_mms_removed_messages[id] = (*it); break; - default: - LoggerD("Unknown message type: %d", (*it)->getType()); - break; - } - - int error = msg_delete_message(m_msg_handle, id); - if (MSG_SUCCESS != error) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting message", - ("msg_delete_message error: %d (%s)", error, get_error_message(error)))); - break; - } - } + int error = msg_delete_message(m_msg_handle, id); + if (MSG_SUCCESS != error) { + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while deleting message", + ("msg_delete_message error: %d (%s)", error, get_error_message(error)))); + break; } + } } + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); - callback->SetSuccess(); - } + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); + callback->SetSuccess(); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback) -{ - LoggerD("Entered"); +void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback) { + LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; + if (!callback) { + LoggerE("Callback is null"); + return; + } + + LoggerD("messages to update: %d", callback->getMessages().size()); + + { + std::lock_guard lock(m_mutex); + std::vector> messages = callback->getMessages(); + MessageType type = callback->getMessageServiceType(); + for (auto it = messages.begin(); it != messages.end(); ++it) { + if ((*it)->getType() != type) { + callback->SetError(LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, + "Error while updating message", + ("Invalid message type %d", (*it)->getType()))); + break; + } } + if (!callback->IsError()) { + for (auto it = messages.begin(); it != messages.end(); ++it) { + LoggerD("updating Message(%p) msg_id:%d", (*it).get(), (*it)->getId()); - LoggerD("messages to update: %d", callback->getMessages().size()); - - { - std::lock_guard lock(m_mutex); - std::vector> messages = callback->getMessages(); - MessageType type = callback->getMessageServiceType(); - for (auto it = messages.begin() ; it != messages.end(); ++it) { - if ((*it)->getType() != type) { - callback->SetError(LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while updating message", - ("Invalid message type %d", (*it)->getType()))); - break; - } + msg_struct_t platform_msg = nullptr; + PlatformResult ret = + Message::convertPlatformShortMessageToStruct(it->get(), m_msg_handle, &platform_msg); + if (ret.IsError()) { + LoggerE("%s", ret.message().c_str()); + callback->SetError(ret); + break; } - if (!callback->IsError()) { - for (auto it = messages.begin() ; it != messages.end(); ++it) { - LoggerD("updating Message(%p) msg_id:%d", (*it).get(), (*it)->getId()); - - msg_struct_t platform_msg = nullptr; - PlatformResult ret = Message::convertPlatformShortMessageToStruct(it->get(), m_msg_handle, &platform_msg); - if (ret.IsError()) { - LoggerE("%s", ret.message().c_str()); - callback->SetError(ret); - break; - } - if (NULL == platform_msg) { - callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot prepare platform message")); - break; - } - msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); - int error = msg_update_message(m_msg_handle, platform_msg, sendOpt); - msg_release_struct(&platform_msg); - msg_release_struct(&sendOpt); - if (error != MSG_SUCCESS) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while updating message", - ("Failed to update message %d", (*it)->getId()))); - break; - } - } + if (NULL == platform_msg) { + callback->SetError( + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot prepare platform message")); + break; } + msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); + int error = msg_update_message(m_msg_handle, platform_msg, sendOpt); + msg_release_struct(&platform_msg); + msg_release_struct(&sendOpt); + if (error != MSG_SUCCESS) { + callback->SetError(LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Error while updating message", + ("Failed to update message %d", (*it)->getId()))); + break; + } + } } + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - auto messages = callback->getMessages(); - picojson::array array; - auto each = [&array] (std::shared_ptr m)->void { - array.push_back(MessagingUtil::messageToJson(m)); - }; + auto messages = callback->getMessages(); + picojson::array array; + auto each = [&array](std::shared_ptr m) -> void { + array.push_back(MessagingUtil::messageToJson(m)); + }; - for_each(messages.begin(), messages.end(), each); + for_each(messages.begin(), messages.end(), each); - callback->SetSuccess(picojson::value(array)); - } + callback->SetSuccess(picojson::value(array)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -PlatformResult ShortMsgManager::getMessage(int msg_id, msg_struct_t* out_msg) -{ - LoggerD("Entered"); - msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); - msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); +PlatformResult ShortMsgManager::getMessage(int msg_id, msg_struct_t* out_msg) { + LoggerD("Entered"); + msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); + msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); - int error = msg_get_message(m_msg_handle, msg_id, msg, sendOpt); - if (MSG_SUCCESS != error) { - msg_release_struct(&sendOpt); - msg_release_struct(&msg); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Couldn't retrieve message from service", - ("Couldn't retrieve message from service, msgId: %d, error:%d", msg_id, error)); - } + int error = msg_get_message(m_msg_handle, msg_id, msg, sendOpt); + if (MSG_SUCCESS != error) { msg_release_struct(&sendOpt); - *out_msg = msg; - return PlatformResult(ErrorCode::NO_ERROR); + msg_release_struct(&msg); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Couldn't retrieve message from service", + ("Couldn't retrieve message from service, msgId: %d, error:%d", msg_id, error)); + } + msg_release_struct(&sendOpt); + *out_msg = msg; + return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult ShortMsgManager::getConversationsForMessages( - MessagePtrVector messages, - msg_storage_change_type_t storageChangeType, ConversationPtrVector* result) -{ - LoggerD("Entered messages.size()=%d storageChangeType=%d", messages.size(), - storageChangeType); - - std::unordered_set unique_conv_ids; - ConversationPtrVector convs; - for (auto it = messages.begin(); it != messages.end(); ++it) { - - MessagePtr msg = (*it); - const int conv_id = msg->getConversationId(); - const int count = unique_conv_ids.count(conv_id); - LoggerD("Message(%p) msg_id:%d conversationId: %d count:%d", msg.get(), - msg->getId(), conv_id, count); - - if (0 == count) { - //conversation isn't loaded yet - unique_conv_ids.insert(conv_id); - ConversationPtr conv; - PlatformResult ret = MessageConversation::convertMsgConversationToObject( - conv_id, ShortMsgManager::getInstance().m_msg_handle, &conv); - if (ret.IsError()) { - LoggerD("Convert msg conversation to object failed (%s)", ret.message().c_str()); - return ret; - } - LoggerD("Pushed conv=%p", conv.get()); - convs.push_back(conv); - } + MessagePtrVector messages, msg_storage_change_type_t storageChangeType, + ConversationPtrVector* result) { + LoggerD("Entered messages.size()=%d storageChangeType=%d", messages.size(), storageChangeType); + + std::unordered_set unique_conv_ids; + ConversationPtrVector convs; + for (auto it = messages.begin(); it != messages.end(); ++it) { + MessagePtr msg = (*it); + const int conv_id = msg->getConversationId(); + const int count = unique_conv_ids.count(conv_id); + LoggerD("Message(%p) msg_id:%d conversationId: %d count:%d", msg.get(), msg->getId(), conv_id, + count); + + if (0 == count) { + // conversation isn't loaded yet + unique_conv_ids.insert(conv_id); + ConversationPtr conv; + PlatformResult ret = MessageConversation::convertMsgConversationToObject( + conv_id, ShortMsgManager::getInstance().m_msg_handle, &conv); + if (ret.IsError()) { + LoggerD("Convert msg conversation to object failed (%s)", ret.message().c_str()); + return ret; + } + LoggerD("Pushed conv=%p", conv.get()); + convs.push_back(conv); } - *result = convs; - return PlatformResult(ErrorCode::NO_ERROR); + } + *result = convs; + return PlatformResult(ErrorCode::NO_ERROR); } -void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback) -{ - LoggerD("Entered"); +void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback) { + LoggerD("Entered"); - if(!callback){ - LoggerE("Callback is null"); - return; + if (!callback) { + LoggerE("Callback is null"); + return; + } + + { + std::lock_guard lock(m_mutex); + std::vector messagesIds; + PlatformResult ret = + MessagingDatabaseManager::getInstance().findShortMessages(callback, &messagesIds); + if (ret.IsError()) { + LoggerE("Failed to find short message: %s (%d)", ret.message().c_str(), ret.error_code()); + callback->SetError(ret); } - { - std::lock_guard lock(m_mutex); - std::vector messagesIds; - PlatformResult ret = MessagingDatabaseManager::getInstance().findShortMessages(callback, &messagesIds); - if (ret.IsError()) { - LoggerE("Failed to find short message: %s (%d)", ret.message().c_str(), ret.error_code()); - callback->SetError(ret); + if (!callback->IsError()) { + int msgListCount = messagesIds.size(); + LoggerD("Found %d messages", msgListCount); + + msg_struct_t msg; + msg_struct_t send_opt; + msg_error_t err; + for (int i = 0; i < msgListCount; i++) { + msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); + send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); + std::unique_ptr msg_ptr(&msg, msg_release_struct); + std::unique_ptr send_opt_ptr(&send_opt, + msg_release_struct); + + err = msg_get_message(m_msg_handle, messagesIds.at(i), msg, send_opt); + + if (MSG_SUCCESS != err) { + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure", + ("Failed to get platform message structure: %d (%s)", err, get_error_message(err)))); + break; } + Message* message = nullptr; + PlatformResult ret = Message::convertPlatformShortMessageToObject(msg, &message); + if (ret.IsError()) { + if (ErrorCode::INVALID_VALUES_ERR == ret.error_code()) { + LoggerW("Ignore messages with not supported/unrecognized type"); + continue; + } + callback->SetError( + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure")); + break; + } if (!callback->IsError()) { - int msgListCount = messagesIds.size(); - LoggerD("Found %d messages", msgListCount); - - msg_struct_t msg; - msg_struct_t send_opt; - msg_error_t err; - for (int i = 0; i < msgListCount; i++) { - msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); - send_opt = msg_create_struct(MSG_STRUCT_SENDOPT); - std::unique_ptr msg_ptr(&msg, msg_release_struct); - std::unique_ptr send_opt_ptr(&send_opt, msg_release_struct); - - err = msg_get_message(m_msg_handle, messagesIds.at(i), msg, send_opt); - - if (MSG_SUCCESS != err) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure", - ("Failed to get platform message structure: %d (%s)", err, get_error_message(err)))); - break; - } - - Message* message = nullptr; - PlatformResult ret = Message::convertPlatformShortMessageToObject(msg, &message); - if (ret.IsError()) { - if (ErrorCode::INVALID_VALUES_ERR == ret.error_code()) { - LoggerW("Ignore messages with not supported/unrecognized type"); - continue; - } - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get platform Message structure")); - break; - } - if (!callback->IsError()) { - callback->addMessage(std::shared_ptr{message}); - LoggerD("Created message with id %d:", messagesIds[i]); - } - } + callback->addMessage(std::shared_ptr{message}); + LoggerD("Created message with id %d:", messagesIds[i]); } + } } + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback with %d messages:", - callback->getMessages().size()); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback with %d messages:", callback->getMessages().size()); - std::vector response; - auto messages = callback->getMessages(); - std::for_each(messages.begin(), messages.end(), [&response](MessagePtr &message){ - response.push_back(MessagingUtil::messageToJson(message)); - }); + std::vector response; + auto messages = callback->getMessages(); + std::for_each(messages.begin(), messages.end(), [&response](MessagePtr& message) { + response.push_back(MessagingUtil::messageToJson(message)); + }); - callback->SetSuccess(picojson::value(response)); - } + callback->SetSuccess(picojson::value(response)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -void ShortMsgManager::findConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void ShortMsgManager::findConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if(!callback){ - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - { - std::lock_guard lock(m_mutex); - std::vector conversationsIds; - PlatformResult ret = MessagingDatabaseManager::getInstance(). - findShortMessageConversations(callback, &conversationsIds); - if (ret.IsError()) { - LoggerE("Cannot get platform Message structure"); - callback->SetError(ret); - } + { + std::lock_guard lock(m_mutex); + std::vector conversationsIds; + PlatformResult ret = MessagingDatabaseManager::getInstance().findShortMessageConversations( + callback, &conversationsIds); + if (ret.IsError()) { + LoggerE("Cannot get platform Message structure"); + callback->SetError(ret); + } - if (!callback->IsError()) { - int convListCount = conversationsIds.size(); - LoggerD("Found %d conversations", convListCount); - - for (int i = 0; i < convListCount; i++) { - std::shared_ptr conversation; - PlatformResult ret = MessageConversation::convertMsgConversationToObject( - conversationsIds.at(i), m_msg_handle, &conversation); - if (ret.IsSuccess()) { - callback->addConversation(conversation); - } else { - callback->SetError(ret); - } - } + if (!callback->IsError()) { + int convListCount = conversationsIds.size(); + LoggerD("Found %d conversations", convListCount); + + for (int i = 0; i < convListCount; i++) { + std::shared_ptr conversation; + PlatformResult ret = MessageConversation::convertMsgConversationToObject( + conversationsIds.at(i), m_msg_handle, &conversation); + if (ret.IsSuccess()) { + callback->addConversation(conversation); + } else { + callback->SetError(ret); } + } } + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - std::vector response; - auto conversations = callback->getConversations(); - std::for_each(conversations.begin(), conversations.end(), - [&response](std::shared_ptr &conversation) { + std::vector response; + auto conversations = callback->getConversations(); + std::for_each(conversations.begin(), conversations.end(), + [&response](std::shared_ptr& conversation) { response.push_back(MessagingUtil::conversationToJson(conversation)); - } - ); + }); - callback->SetSuccess(picojson::value(response)); - } + callback->SetSuccess(picojson::value(response)); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -void ShortMsgManager::removeConversations(ConversationCallbackData* callback) -{ - LoggerD("Entered"); +void ShortMsgManager::removeConversations(ConversationCallbackData* callback) { + LoggerD("Entered"); - if (!callback){ - LoggerE("Callback is null"); - return; - } + if (!callback) { + LoggerE("Callback is null"); + return; + } - int error = MSG_SUCCESS; - msg_handle_t handle = NULL; + int error = MSG_SUCCESS; + msg_handle_t handle = NULL; - { - std::lock_guard lock(m_mutex); - ConversationPtrVector conversations = callback->getConversations(); - const MessageType type = callback->getMessageServiceType(); + { + std::lock_guard lock(m_mutex); + ConversationPtrVector conversations = callback->getConversations(); + const MessageType type = callback->getMessageServiceType(); - std::map* msg_id_conv_id_map = NULL; - std::map* conv_id_object_map = NULL; + std::map* msg_id_conv_id_map = NULL; + std::map* conv_id_object_map = NULL; - error = msg_open_msg_handle(&handle); - if (MSG_SUCCESS != error) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while creatng message handle", - ("Open message handle error: %d (%s)", error, get_error_message(error)))); - } + error = msg_open_msg_handle(&handle); + if (MSG_SUCCESS != error) { + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while creatng message handle", + ("Open message handle error: %d (%s)", error, get_error_message(error)))); + } - if (!callback->IsError()) { - for(auto it = conversations.begin() ; it != conversations.end(); ++it) { - if((*it)->getType() != type) { - callback->SetError(LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Error while deleting message conversation", - ("Invalid message type %d", (*it)->getType()))); - break; - } - } + if (!callback->IsError()) { + for (auto it = conversations.begin(); it != conversations.end(); ++it) { + if ((*it)->getType() != type) { + callback->SetError(LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, + "Error while deleting message conversation", + ("Invalid message type %d", (*it)->getType()))); + break; } + } + } - if (!callback->IsError()) { - if(MessageType::SMS == type) { - msg_id_conv_id_map = &m_sms_removed_msg_id_conv_id_map; - conv_id_object_map = &m_sms_removed_conv_id_object_map; - } else if(MessageType::MMS == type) { - msg_id_conv_id_map = &m_mms_removed_msg_id_conv_id_map; - conv_id_object_map = &m_mms_removed_conv_id_object_map; + if (!callback->IsError()) { + if (MessageType::SMS == type) { + msg_id_conv_id_map = &m_sms_removed_msg_id_conv_id_map; + conv_id_object_map = &m_sms_removed_conv_id_object_map; + } else if (MessageType::MMS == type) { + msg_id_conv_id_map = &m_mms_removed_msg_id_conv_id_map; + conv_id_object_map = &m_mms_removed_conv_id_object_map; + } else { + callback->SetError( + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Invalid message type for ShortMsgManager!", + ("Invalid message type:%d for ShortMsgManager!", type))); + } + } + + if (!callback->IsError()) { + int conv_index = 0; + for (auto it = conversations.begin(); it != conversations.end(); ++it, ++conv_index) { + ConversationPtr conv = (*it); + msg_thread_id_t conv_id = conv->getConversationId(); + + LoggerD("[%d] MessageConversation(%p) conv_id:%d", conv_index, conv.get(), conv_id); + + msg_struct_list_s conv_view_list; + error = msg_get_conversation_view_list(handle, (msg_thread_id_t)conv_id, &conv_view_list); + if (MSG_SUCCESS == error) { + for (int msg_index = 0; msg_index < conv_view_list.nCount; ++msg_index) { + int cur_msg_id = 0; + error = msg_get_int_value(conv_view_list.msg_struct_info[msg_index], + MSG_CONV_MSG_ID_INT, &cur_msg_id); + + if (MSG_SUCCESS == error && cur_msg_id > 0) { + (*msg_id_conv_id_map)[cur_msg_id] = conv_id; + (*conv_id_object_map)[conv_id] = conv; + + LoggerD( + "[%d] message[%d] msg_id:%d," + "saved MessageConversation(%p) with conv_id:%d", + conv_index, msg_index, cur_msg_id, conv.get(), conv_id); } else { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Invalid message type for ShortMsgManager!", - ("Invalid message type:%d for ShortMsgManager!", type))); + LoggerE("[%d] Couldn't get msg_id, error: %d!", error); } + } + } else { + LoggerE("[%d] Couldn' get conversation view list for conv_id:%d error: %d", conv_index, + conv_id, error); } - if (!callback->IsError()) { - int conv_index = 0; - for (auto it = conversations.begin() ; it != conversations.end(); - ++it, ++conv_index) { - - ConversationPtr conv = (*it); - msg_thread_id_t conv_id = conv->getConversationId(); - - LoggerD("[%d] MessageConversation(%p) conv_id:%d", conv_index, conv.get(), - conv_id); - - msg_struct_list_s conv_view_list; - error = msg_get_conversation_view_list(handle, (msg_thread_id_t)conv_id, - &conv_view_list); - if (MSG_SUCCESS == error) { - for(int msg_index = 0; msg_index < conv_view_list.nCount; ++msg_index) - { - int cur_msg_id = 0; - error = msg_get_int_value(conv_view_list.msg_struct_info[msg_index], - MSG_CONV_MSG_ID_INT, &cur_msg_id); - - if(MSG_SUCCESS == error && cur_msg_id > 0) { - (*msg_id_conv_id_map)[cur_msg_id] = conv_id; - (*conv_id_object_map)[conv_id] = conv; - - LoggerD("[%d] message[%d] msg_id:%d," - "saved MessageConversation(%p) with conv_id:%d", - conv_index, msg_index, cur_msg_id, conv.get(), conv_id); - } else { - LoggerE("[%d] Couldn't get msg_id, error: %d!", error); - } - } - } else { - LoggerE("[%d] Couldn' get conversation view list for conv_id:%d error: %d", - conv_index, conv_id, error); - } + msg_release_list_struct(&conv_view_list); - msg_release_list_struct(&conv_view_list); - - error = msg_delete_thread_message_list(handle, (msg_thread_id_t) conv_id, - FALSE); - if (MSG_SUCCESS != error) { - callback->SetError(LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error while deleting message conversation", - ("msg_delete_thread_message_list error: %d (%s)", - error, get_error_message(error)))); - break; - } - } + error = msg_delete_thread_message_list(handle, (msg_thread_id_t)conv_id, FALSE); + if (MSG_SUCCESS != error) { + callback->SetError(LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Error while deleting message conversation", + ("msg_delete_thread_message_list error: %d (%s)", error, get_error_message(error)))); + break; } + } } + } - if (!callback->IsError()) { - error = msg_close_msg_handle(&handle); - if (MSG_SUCCESS != error) { - LoggerW("Cannot close message handle: %d", error); - } + if (!callback->IsError()) { + error = msg_close_msg_handle(&handle); + if (MSG_SUCCESS != error) { + LoggerW("Cannot close message handle: %d", error); } + } - if (callback->IsError()) { - LoggerD("Calling error callback"); - } else { - LoggerD("Calling success callback"); + if (callback->IsError()) { + LoggerD("Calling error callback"); + } else { + LoggerD("Calling success callback"); - callback->SetSuccess(); - } + callback->SetSuccess(); + } - callback->Post(); + callback->Post(); - delete callback; - callback = NULL; + delete callback; + callback = NULL; } -ShortMsgManager::ShortMsgManager() : m_msg_handle(NULL) -{ - LoggerD("Entered"); +ShortMsgManager::ShortMsgManager() : m_msg_handle(NULL) { + LoggerD("Entered"); } -ShortMsgManager::~ShortMsgManager() -{ - LoggerD("Entered"); - LoggerD("m_sms_removed_messages.size() = %d", - m_sms_removed_messages.size()); - LoggerD("m_mms_removed_messages.size() = %d", - m_mms_removed_messages.size()); - LoggerD("m_sms_removed_msg_id_conv_id_map.size() = %d", - m_sms_removed_msg_id_conv_id_map.size()); - LoggerD("m_sms_removed_conv_id_object_map.size() = %d", - m_sms_removed_conv_id_object_map.size()); - LoggerD("m_mms_removed_msg_id_conv_id_map.size() = %d", - m_mms_removed_msg_id_conv_id_map.size()); - LoggerD("m_mms_removed_conv_id_object_map.size() = %d", - m_mms_removed_conv_id_object_map.size()); +ShortMsgManager::~ShortMsgManager() { + LoggerD("Entered"); + LoggerD("m_sms_removed_messages.size() = %d", m_sms_removed_messages.size()); + LoggerD("m_mms_removed_messages.size() = %d", m_mms_removed_messages.size()); + LoggerD("m_sms_removed_msg_id_conv_id_map.size() = %d", m_sms_removed_msg_id_conv_id_map.size()); + LoggerD("m_sms_removed_conv_id_object_map.size() = %d", m_sms_removed_conv_id_object_map.size()); + LoggerD("m_mms_removed_msg_id_conv_id_map.size() = %d", m_mms_removed_msg_id_conv_id_map.size()); + LoggerD("m_mms_removed_conv_id_object_map.size() = %d", m_mms_removed_conv_id_object_map.size()); } std::string ShortMsgManager::getMessageStatus(int id) { LoggerD("Entered"); @@ -1237,8 +1169,8 @@ std::string ShortMsgManager::getMessageStatus(int id) { int ret = msg_get_message(m_msg_handle, id, msg, send_opt); if (MSG_SUCCESS != ret) { - LoggerE("Couldn't retrieve message from service, id: %d, error:%d", id, ret); - return ""; + LoggerE("Couldn't retrieve message from service, id: %d, error:%d", id, ret); + return ""; } int status_int; @@ -1263,7 +1195,7 @@ std::string ShortMsgManager::getMessageStatus(int id) { } else { ret = msg_get_int_value(msg, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status_int); if (MSG_SUCCESS == ret) { - switch(status_int) { + switch (status_int) { case MSG_NETWORK_SEND_SUCCESS: status = MessageStatus::STATUS_SENT; break; @@ -1286,5 +1218,5 @@ std::string ShortMsgManager::getMessageStatus(int id) { return MessagingUtil::messageStatusToString(status); } -} // messaging -} // extension +} // messaging +} // extension diff --git a/src/messaging/short_message_manager.h b/src/messaging/short_message_manager.h old mode 100755 new mode 100644 index dcdf05b..3af6142 --- a/src/messaging/short_message_manager.h +++ b/src/messaging/short_message_manager.h @@ -13,25 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + #ifndef __MESSAGING_SEND_SHORT_MSG_MANAGER_H__ #define __MESSAGING_SEND_SHORT_MSG_MANAGER_H__ #include -#include #include +#include #include #include //#include -#include "common/platform_result.h" #include "change_listener_container.h" -#include "messaging_util.h" +#include "common/platform_result.h" +#include "message_conversation.h" #include "message_service.h" #include "message_sms.h" -#include "message_conversation.h" +#include "messaging_util.h" namespace extension { namespace messaging { @@ -39,97 +39,94 @@ namespace messaging { class FindMsgCallbackUserData; class ShortMsgManager { -public: - static ShortMsgManager& getInstance(); - - common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); - void sendStatusCallback(msg_struct_t sent_status); - - void addDraftMessage(MessageCallbackUserData* callback); - void findMessages(FindMsgCallbackUserData* callback); - void findConversations(ConversationCallbackData* callback); - void removeConversations(ConversationCallbackData* callback); - - void registerStatusCallback(msg_handle_t msg_handle); - - void removeMessages(MessagesCallbackUserData* callback); - void updateMessages(MessagesCallbackUserData* callback); - common::PlatformResult getMessage(int msg_id, msg_struct_t* out_msg); - std::string getMessageStatus(int id); -private: - ShortMsgManager(); - ShortMsgManager(const ShortMsgManager &); - void operator=(const ShortMsgManager &); - virtual ~ShortMsgManager(); - - /** - * Listener for msg storage changes. Calls callbacks from ChangeListenerContainer. - * @param handle - * @param storageChangeType - * @param pMsgIdList - * @param data - */ - static void storage_change_cb(msg_handle_t handle, - msg_storage_change_type_t storageChangeType, - msg_id_list_s *pMsgIdList, - void* data); - - common::PlatformResult addDraftMessagePlatform(std::shared_ptr message); - common::PlatformResult SendMessagePlatform(MessageRecipientsCallbackData* callback); - /** - * Returns unique list of conversations for given vector of messages. - * storageChangeType is needed to filter conversations returned: - * - for MSG_STORAGE_CHANGE_UPDATE all conversations are fetched - * - for MSG_STORAGE_CHANGE_INSERT only conversations with 1 message are returned - * - for MSG_STORAGE_CHANGE_DELETE only conversations with 1 message are returned - * @param messages - * @param storageChangeType - * @return - */ - static common::PlatformResult getConversationsForMessages( - MessagePtrVector messages, - msg_storage_change_type_t storageChangeType, ConversationPtrVector* result); - static common::PlatformResult callProperEventMessages(EventMessages* event, - msg_storage_change_type_t storageChangeType); - typedef std::map SendReqMap; - SendReqMap m_sendRequests; - msg_handle_t m_msg_handle; - - /** - * Map MessageId - Message object of recently removed SMS messages - */ - std::map m_sms_removed_messages; - - /** - * Map MessageId - Message object of recently removed MMS messages - */ - std::map m_mms_removed_messages; - - - - /** - * Map MessageId - ConversationId for SMS messages (only from removed conversation) - */ - std::map m_sms_removed_msg_id_conv_id_map; - - /** - * Map ConversationId - ConversationPtr object (only removed) for SMS - */ - std::map m_sms_removed_conv_id_object_map; - - /** - * Map MessageId - ConversationId for MMS messages (only from removed conversation) - */ - std::map m_mms_removed_msg_id_conv_id_map; - - /** - * Map ConversationId - ConversationPtr object (only removed) for MMS - */ - std::map m_mms_removed_conv_id_object_map; - - std::mutex m_mutex; + public: + static ShortMsgManager& getInstance(); + + common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); + void sendStatusCallback(msg_struct_t sent_status); + + void addDraftMessage(MessageCallbackUserData* callback); + void findMessages(FindMsgCallbackUserData* callback); + void findConversations(ConversationCallbackData* callback); + void removeConversations(ConversationCallbackData* callback); + + void registerStatusCallback(msg_handle_t msg_handle); + + void removeMessages(MessagesCallbackUserData* callback); + void updateMessages(MessagesCallbackUserData* callback); + common::PlatformResult getMessage(int msg_id, msg_struct_t* out_msg); + std::string getMessageStatus(int id); + + private: + ShortMsgManager(); + ShortMsgManager(const ShortMsgManager&); + void operator=(const ShortMsgManager&); + virtual ~ShortMsgManager(); + + /** + * Listener for msg storage changes. Calls callbacks from ChangeListenerContainer. + * @param handle + * @param storageChangeType + * @param pMsgIdList + * @param data + */ + static void storage_change_cb(msg_handle_t handle, msg_storage_change_type_t storageChangeType, + msg_id_list_s* pMsgIdList, void* data); + + common::PlatformResult addDraftMessagePlatform(std::shared_ptr message); + common::PlatformResult SendMessagePlatform(MessageRecipientsCallbackData* callback); + /** + * Returns unique list of conversations for given vector of messages. + * storageChangeType is needed to filter conversations returned: + * - for MSG_STORAGE_CHANGE_UPDATE all conversations are fetched + * - for MSG_STORAGE_CHANGE_INSERT only conversations with 1 message are returned + * - for MSG_STORAGE_CHANGE_DELETE only conversations with 1 message are returned + * @param messages + * @param storageChangeType + * @return + */ + static common::PlatformResult getConversationsForMessages( + MessagePtrVector messages, msg_storage_change_type_t storageChangeType, + ConversationPtrVector* result); + static common::PlatformResult callProperEventMessages( + EventMessages* event, msg_storage_change_type_t storageChangeType); + typedef std::map SendReqMap; + SendReqMap m_sendRequests; + msg_handle_t m_msg_handle; + + /** + * Map MessageId - Message object of recently removed SMS messages + */ + std::map m_sms_removed_messages; + + /** + * Map MessageId - Message object of recently removed MMS messages + */ + std::map m_mms_removed_messages; + + /** + * Map MessageId - ConversationId for SMS messages (only from removed conversation) + */ + std::map m_sms_removed_msg_id_conv_id_map; + + /** + * Map ConversationId - ConversationPtr object (only removed) for SMS + */ + std::map m_sms_removed_conv_id_object_map; + + /** + * Map MessageId - ConversationId for MMS messages (only from removed conversation) + */ + std::map m_mms_removed_msg_id_conv_id_map; + + /** + * Map ConversationId - ConversationPtr object (only removed) for MMS + */ + std::map m_mms_removed_conv_id_object_map; + + std::mutex m_mutex; }; -} // messaging -} // extension -#endif // __MESSAGING_SEND_SHORT_MSG_MANAGER_H__ +} // messaging +} // extension +#endif // __MESSAGING_SEND_SHORT_MSG_MANAGER_H__ diff --git a/src/networkbearerselection/networkbearerselection_extension.cc b/src/networkbearerselection/networkbearerselection_extension.cc index 119e269..74f2143 100644 --- a/src/networkbearerselection/networkbearerselection_extension.cc +++ b/src/networkbearerselection/networkbearerselection_extension.cc @@ -30,7 +30,8 @@ NetworkBearerSelectionExtension::NetworkBearerSelectionExtension() { SetJavaScriptAPI(kSource_networkbearerselection_api); } -NetworkBearerSelectionExtension::~NetworkBearerSelectionExtension() {} +NetworkBearerSelectionExtension::~NetworkBearerSelectionExtension() { +} common::Instance* NetworkBearerSelectionExtension::CreateInstance() { return new extension::networkbearerselection::NetworkBearerSelectionInstance; diff --git a/src/networkbearerselection/networkbearerselection_instance.cc b/src/networkbearerselection/networkbearerselection_instance.cc index e8f0bd6..65a89d2 100644 --- a/src/networkbearerselection/networkbearerselection_instance.cc +++ b/src/networkbearerselection/networkbearerselection_instance.cc @@ -18,12 +18,12 @@ #include -#include "networkbearerselection_manager.h" -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" #include "common/task-queue.h" #include "common/tools.h" +#include "networkbearerselection_manager.h" namespace extension { namespace networkbearerselection { @@ -35,7 +35,7 @@ const std::string kPrivilegeInternet = "http://tizen.org/privilege/internet"; const std::vector kNbsPrivileges{kPrivilegeNBS, kPrivilegeInternet}; const std::string kNBSCallback = "NetworkBearerSelectionCallback_"; -} // namespace +} // namespace using namespace common; using namespace extension::networkbearerselection; @@ -46,11 +46,9 @@ NetworkBearerSelectionInstance::NetworkBearerSelectionInstance() { using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler( \ - c, std::bind(&NetworkBearerSelectionInstance::x, this, _1, _2)); + RegisterSyncHandler(c, std::bind(&NetworkBearerSelectionInstance::x, this, _1, _2)); #define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler( \ - c, std::bind(&NetworkBearerSelectionInstance::x, this, _1, _2)); + RegisterSyncHandler(c, std::bind(&NetworkBearerSelectionInstance::x, this, _1, _2)); REGISTER_SYNC("NetworkBearerSelection_requestRouteToHost", NetworkBearerSelectionRequestRouteToHost); REGISTER_ASYNC("NetworkBearerSelection_releaseRouteToHost", @@ -90,11 +88,11 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionRequestRouteToHost( const std::string& domain_name = args.get("domainName").get(); const int id = static_cast(args.get("id").get()); - auto request = [=]()->void { + auto request = [=]() -> void { auto response = [this, domain_name, id](const common::PlatformResult result) -> void { LoggerD("Entered"); - picojson::value value {picojson::object{}}; + picojson::value value{picojson::object{}}; picojson::object& obj = value.get(); obj["id"] = picojson::value(static_cast(id)); @@ -111,7 +109,6 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionRequestRouteToHost( }; NetworkBearerSelectionManager::GetInstance()->requestRouteToHost(domain_name, response); - }; common::TaskQueue::GetInstance().Async(request); ReportSuccess(out); @@ -137,11 +134,11 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionReleaseRouteToHost( } } - auto release = [=]()->void { + auto release = [=]() -> void { auto response = [this, domain_name, id](const common::PlatformResult result) -> void { LoggerD("Entered"); - picojson::value value {picojson::object{}}; + picojson::value value{picojson::object{}}; picojson::object& obj = value.get(); obj["callbackId"] = picojson::value(id); @@ -180,8 +177,8 @@ void NetworkBearerSelectionInstance::onNBSEvent(const std::string& status) { } } -void NetworkBearerSelectionInstance::addDomainListener( - const std::string& domain_name, int listener_id) { +void NetworkBearerSelectionInstance::addDomainListener(const std::string& domain_name, + int listener_id) { LoggerD("Entered"); std::lock_guard lock(m_listener_mutex_); diff --git a/src/networkbearerselection/networkbearerselection_instance.h b/src/networkbearerselection/networkbearerselection_instance.h index 7bc1d82..fffff10 100644 --- a/src/networkbearerselection/networkbearerselection_instance.h +++ b/src/networkbearerselection/networkbearerselection_instance.h @@ -17,9 +17,9 @@ #ifndef NETWORKBEARERSELECTION_NETWORKBEARERSELECTION_INSTANCE_H_ #define NETWORKBEARERSELECTION_NETWORKBEARERSELECTION_INSTANCE_H_ -#include "common/extension.h" #include #include +#include "common/extension.h" namespace extension { namespace networkbearerselection { @@ -30,6 +30,7 @@ class NetworkBearerSelectionInstance : public common::ParsedInstance { virtual ~NetworkBearerSelectionInstance(); void onNBSEvent(const std::string& status); + private: void NetworkBearerSelectionRequestRouteToHost(const picojson::value& args, picojson::object& out); void NetworkBearerSelectionReleaseRouteToHost(const picojson::value& args, picojson::object& out); diff --git a/src/networkbearerselection/networkbearerselection_manager.cc b/src/networkbearerselection/networkbearerselection_manager.cc index ae11594..37ecdc1 100644 --- a/src/networkbearerselection/networkbearerselection_manager.cc +++ b/src/networkbearerselection/networkbearerselection_manager.cc @@ -18,8 +18,8 @@ #include "common/logger.h" #include "common/scope_exit.h" -#include #include +#include #include #include @@ -37,9 +37,8 @@ struct NetworkBearerSelectionEvent { std::string domain_name; ReplyCallback callback; - NetworkBearerSelectionEvent(const std::string& dm, const ReplyCallback& cb): - domain_name(dm), - callback(cb) { + NetworkBearerSelectionEvent(const std::string& dm, const ReplyCallback& cb) + : domain_name(dm), callback(cb) { } }; @@ -108,8 +107,8 @@ void NetworkBearerSelectionManager::connection_state_changed_callback( } } -void NetworkBearerSelectionManager::connection_opened_callback( - connection_error_e result, void* user_data) { +void NetworkBearerSelectionManager::connection_opened_callback(connection_error_e result, + void* user_data) { LoggerD("Entered"); NetworkBearerSelectionEvent* event = static_cast(user_data); if (!event) { @@ -134,8 +133,8 @@ void NetworkBearerSelectionManager::connection_opened_callback( delete event; } -void NetworkBearerSelectionManager::connection_closed_callback( - connection_error_e result, void* user_data) { +void NetworkBearerSelectionManager::connection_closed_callback(connection_error_e result, + void* user_data) { LoggerD("Entered"); NetworkBearerSelectionEvent* event = static_cast(user_data); if (!event) { @@ -179,15 +178,15 @@ PlatformResult NetworkBearerSelectionManager::getCellularState() { return PlatformResult(ErrorCode::NO_ERROR); } -void NetworkBearerSelectionManager::callResultCallback( - const ReplyCallback& reply, const PlatformResult result) { +void NetworkBearerSelectionManager::callResultCallback(const ReplyCallback& reply, + const PlatformResult result) { LoggerD("Entered"); std::thread(reply, result).detach(); } -void NetworkBearerSelectionManager::requestRouteToHost( - const std::string& domain_name, const ReplyCallback& reply) { +void NetworkBearerSelectionManager::requestRouteToHost(const std::string& domain_name, + const ReplyCallback& reply) { LoggerD("Entered"); connection_profile_h profile_h = nullptr; @@ -210,8 +209,8 @@ void NetworkBearerSelectionManager::requestRouteToHost( } if (!createProfileHandler()) { - callResultCallback(reply, - LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get cellular profile")); + callResultCallback( + reply, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get cellular profile")); return; } @@ -283,16 +282,15 @@ bool NetworkBearerSelectionManager::removeDomainRoute( ret = connection_remove_route(m_connection_handle_, interface_name, domain_name); } else if (AF_INET6 == ai_family) { LoggerD("IPv6 address"); - ret = connection_profile_get_gateway_address( - m_profile_handle_, CONNECTION_ADDRESS_FAMILY_IPV6, &gateway); + ret = connection_profile_get_gateway_address(m_profile_handle_, CONNECTION_ADDRESS_FAMILY_IPV6, + &gateway); if (CONNECTION_ERROR_NONE != ret) { LoggerE("Failed to get gateway"); return false; } - ret = connection_remove_route_ipv6( - m_connection_handle_, interface_name, domain_name, gateway); + ret = connection_remove_route_ipv6(m_connection_handle_, interface_name, domain_name, gateway); } else { LoggerE("Incorrect family address"); return false; @@ -306,8 +304,8 @@ bool NetworkBearerSelectionManager::removeDomainRoute( return true; } -void NetworkBearerSelectionManager::releaseRouteToHost( - const std::string& domain_name, const ReplyCallback& reply) { +void NetworkBearerSelectionManager::releaseRouteToHost(const std::string& domain_name, + const ReplyCallback& reply) { LoggerD("Entered"); if (!m_profile_handle_) { @@ -318,14 +316,12 @@ void NetworkBearerSelectionManager::releaseRouteToHost( auto iter = m_domain_names_.find(domain_name); if (m_domain_names_.end() == iter) { - callResultCallback(reply, - LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Domain not found")); + callResultCallback(reply, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Domain not found")); return; } if (!removeDomainRoute(iter)) { - callResultCallback(reply, - LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to remove route")); + callResultCallback(reply, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to remove route")); return; } @@ -378,32 +374,34 @@ bool NetworkBearerSelectionManager::registerStateChangeListener(const std::strin return false; } - struct in_addr *addr = nullptr; + struct in_addr* addr = nullptr; if (AF_INET == serv_info->ai_family) { LoggerD("IPv4 address"); - struct sockaddr_in *ipv = (struct sockaddr_in *) serv_info->ai_addr; + struct sockaddr_in* ipv = (struct sockaddr_in*)serv_info->ai_addr; addr = &(ipv->sin_addr); } else if (AF_INET6 == serv_info->ai_family) { LoggerD("IPv6 address"); - struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *) serv_info->ai_addr; - addr = (struct in_addr*) &ipv6->sin6_addr; + struct sockaddr_in6* ipv6 = (struct sockaddr_in6*)serv_info->ai_addr; + addr = (struct in_addr*)&ipv6->sin6_addr; } else { LoggerE("Unknown ai_family address"); return false; } - std::unique_ptr host_addr_ptr(new char[serv_info->ai_addrlen + 1], &std::free); + std::unique_ptr host_addr_ptr(new char[serv_info->ai_addrlen + 1], + &std::free); - if (nullptr == inet_ntop(serv_info->ai_family, addr, host_addr_ptr.get(), serv_info->ai_addrlen)) { + if (nullptr == + inet_ntop(serv_info->ai_family, addr, host_addr_ptr.get(), serv_info->ai_addrlen)) { LoggerE("Failed to convert address"); return false; } LoggerD("hostAddr: %s", host_addr_ptr.get()); - ret = connection_profile_set_state_changed_cb( - m_profile_handle_, connection_state_changed_callback, nullptr); - if (CONNECTION_ERROR_NONE != ret ) { + ret = connection_profile_set_state_changed_cb(m_profile_handle_, + connection_state_changed_callback, nullptr); + if (CONNECTION_ERROR_NONE != ret) { LoggerE("Callback register is failed."); return false; } @@ -413,14 +411,16 @@ bool NetworkBearerSelectionManager::registerStateChangeListener(const std::strin ret = connection_add_route(m_connection_handle_, interface_name, host_addr_ptr.get()); } else { LoggerD("IPv6 add route"); - ret = connection_profile_get_gateway_address(m_profile_handle_, CONNECTION_ADDRESS_FAMILY_IPV6, &gateway); + ret = connection_profile_get_gateway_address(m_profile_handle_, CONNECTION_ADDRESS_FAMILY_IPV6, + &gateway); if (CONNECTION_ERROR_NONE != ret) { LoggerE("Error while getting gateway address %d", ret); return false; } - ret = connection_add_route_ipv6(m_connection_handle_, interface_name, host_addr_ptr.get(), gateway); + ret = connection_add_route_ipv6(m_connection_handle_, interface_name, host_addr_ptr.get(), + gateway); } if (CONNECTION_ERROR_NONE != ret) { @@ -489,7 +489,7 @@ ErrorCode NetworkBearerSelectionManager::GetNBSErrorCode(int error_code) { } bool NetworkBearerSelectionManager::createProfileHandler() { - LoggerD("Entered"); + LoggerD("Entered"); if (!m_connection_handle_) { LoggerE("Connection handle is not created"); diff --git a/src/networkbearerselection/networkbearerselection_manager.h b/src/networkbearerselection/networkbearerselection_manager.h index 3edad48..f950906 100644 --- a/src/networkbearerselection/networkbearerselection_manager.h +++ b/src/networkbearerselection/networkbearerselection_manager.h @@ -17,13 +17,13 @@ #ifndef NETWORKBEARERSELECTION_NETWORKBEARERSELECTION_MANAGER_H_ #define NETWORKBEARERSELECTION_NETWORKBEARERSELECTION_MANAGER_H_ -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include #include "common/platform_result.h" #include "networkbearerselection_instance.h" diff --git a/src/nfc/aid_data.cc b/src/nfc/aid_data.cc index 04babe2..239871f 100644 --- a/src/nfc/aid_data.cc +++ b/src/nfc/aid_data.cc @@ -22,10 +22,7 @@ namespace extension { namespace nfc { AIDData::AIDData(std::string se_type, std::string aid, bool read_only) - : se_type_(se_type), - aid_(aid), - read_only_(read_only) -{ + : se_type_(se_type), aid_(aid), read_only_(read_only) { LoggerD("Entered"); } diff --git a/src/nfc/defs.h b/src/nfc/defs.h index 5fa260c..6e3f2e8 100644 --- a/src/nfc/defs.h +++ b/src/nfc/defs.h @@ -17,19 +17,19 @@ #ifndef NFC_DEFS_H #define NFC_DEFS_H -#define JSON_AID "aid" -#define JSON_APDU "apdu" -#define JSON_CALLBACK_ID "callbackId" -#define JSON_CATEGORY "category" -#define JSON_DATA "data" -#define JSON_EVENT_TYPE "eventType" -#define JSON_LENGTH "length" -#define JSON_LISTENER_ID "listenerId" -#define JSON_MODE "mode" -#define JSON_TYPE "type" +#define JSON_AID "aid" +#define JSON_APDU "apdu" +#define JSON_CALLBACK_ID "callbackId" +#define JSON_CATEGORY "category" +#define JSON_DATA "data" +#define JSON_EVENT_TYPE "eventType" +#define JSON_LENGTH "length" +#define JSON_LISTENER_ID "listenerId" +#define JSON_MODE "mode" +#define JSON_TYPE "type" -#define DATA_NFC_SE_TYPE_ESE "ESE" -#define DATA_NFC_SE_TYPE_UICC "UICC" -#define DATA_NFC_SE_TYPE_HCE "HCE" +#define DATA_NFC_SE_TYPE_ESE "ESE" +#define DATA_NFC_SE_TYPE_UICC "UICC" +#define DATA_NFC_SE_TYPE_HCE "HCE" #endif // NFC_DEFS_H diff --git a/src/nfc/nfc_adapter.cc b/src/nfc/nfc_adapter.cc index be45d2f..5cf9331 100644 --- a/src/nfc/nfc_adapter.cc +++ b/src/nfc/nfc_adapter.cc @@ -52,11 +52,8 @@ const std::string TRANSACTION_EVENT_LISTENER_UICC = "TransactionEventListener_UI const std::string PEER_LISTENER = "PeerListener"; const std::string HCE_EVENT_LISTENER = "HCEEventListener"; -void HCEEventCallback(nfc_se_h handle, - nfc_hce_event_type_e event_type, - unsigned char* apdu, - unsigned int apdu_len, - void* /*user_data*/) { +void HCEEventCallback(nfc_se_h handle, nfc_hce_event_type_e event_type, unsigned char* apdu, + unsigned int apdu_len, void* /*user_data*/) { LoggerD("Entered"); NFCAdapter::GetInstance()->SetSEHandle(handle); @@ -69,8 +66,7 @@ void HCEEventCallback(nfc_se_h handle, picojson::value event_data = picojson::value(picojson::object()); picojson::object& event_data_obj = event_data.get(); event_data_obj[JSON_EVENT_TYPE] = picojson::value(NFCUtil::ToStr(event_type)); - event_data_obj[JSON_APDU] = picojson::value( - NFCUtil::FromUCharArray(apdu, apdu_len)); + event_data_obj[JSON_APDU] = picojson::value(NFCUtil::FromUCharArray(apdu, apdu_len)); event_data_obj[JSON_LENGTH] = picojson::value(static_cast(apdu_len)); tools::ReportSuccess(event_data, response_obj); @@ -79,27 +75,26 @@ void HCEEventCallback(nfc_se_h handle, } // anonymous namespace -NFCAdapter::NFCAdapter(): - m_last_tag_handle(nullptr), - m_is_tag_listener_set(false), - m_latest_tag_id(0), - m_is_listener_set(false), - m_is_transaction_ese_listener_set(false), - m_is_transaction_uicc_listener_set(false), - m_is_transaction_hce_listener_set(false), - m_is_peer_listener_set(false), - m_latest_peer_id(0), - m_peer_handle(nullptr), - m_is_ndef_listener_set(false), - m_se_handle(nullptr), - m_is_hce_listener_set(false), - m_is_preferred_app_set(false), - responder_(nullptr) -{ +NFCAdapter::NFCAdapter() + : m_last_tag_handle(nullptr), + m_is_tag_listener_set(false), + m_latest_tag_id(0), + m_is_listener_set(false), + m_is_transaction_ese_listener_set(false), + m_is_transaction_uicc_listener_set(false), + m_is_transaction_hce_listener_set(false), + m_is_peer_listener_set(false), + m_latest_peer_id(0), + m_peer_handle(nullptr), + m_is_ndef_listener_set(false), + m_se_handle(nullptr), + m_is_hce_listener_set(false), + m_is_preferred_app_set(false), + responder_(nullptr) { LoggerD("Entered"); // NFC library initialization int ret = nfc_manager_initialize(); - if(ret != NFC_ERROR_NONE) { + if (ret != NFC_ERROR_NONE) { LoggerE("Could not initialize NFC Manager, error: %d", ret); } } @@ -133,7 +128,7 @@ NFCAdapter::~NFCAdapter() { // NFC library deinitialization int ret = nfc_manager_deinitialize(); - if(ret != NFC_ERROR_NONE) { + if (ret != NFC_ERROR_NONE) { LoggerE("Could not deinitialize NFC Manager, error: %d", ret); } } @@ -185,8 +180,7 @@ static gboolean setPoweredCompleteCB(void* user_data) { return false; } -static void targetDetectedCallback(nfc_discovered_type_e type, - nfc_p2p_target_h target, +static void targetDetectedCallback(nfc_discovered_type_e type, nfc_p2p_target_h target, void* /*user_data*/) { LoggerD("Entered"); picojson::value event = picojson::value(picojson::object()); @@ -195,7 +189,7 @@ static void targetDetectedCallback(nfc_discovered_type_e type, NFCAdapter* adapter = NFCAdapter::GetInstance(); - //unregister previous NDEF listener + // unregister previous NDEF listener if (adapter->IsNDEFListenerSet()) { adapter->UnsetReceiveNDEFListener(adapter->GetPeerId()); } @@ -225,13 +219,13 @@ bool NFCAdapter::GetPowered() { #ifndef APP_CONTROL_SETTINGS_SUPPORT -static void NFCSetActivationCompletedCallback(nfc_error_e error, - void* user_data) { +static void NFCSetActivationCompletedCallback(nfc_error_e error, void* user_data) { LoggerD("Entered"); double* callbackId = static_cast(user_data); if (NFC_ERROR_NONE != error) { - PlatformResult result = NFCUtil::CodeToResult(error, NFCUtil::getNFCErrorMessage(error).c_str()); + PlatformResult result = + NFCUtil::CodeToResult(error, NFCUtil::getNFCErrorMessage(error).c_str()); picojson::value event = CreateEventError(*callbackId, result); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); @@ -257,13 +251,11 @@ static void se_event_callback(nfc_se_event_e se_event, void* /*user_data*/) { switch (se_event) { case NFC_SE_EVENT_SE_TYPE_CHANGED: NFCAdapter::GetInstance()->GetActiveSecureElement(&result); - obj.insert(make_pair(JSON_LISTENER_ID, - picojson::value(ACTIVE_SECURE_ELEMENT_CHANGED))); + obj.insert(make_pair(JSON_LISTENER_ID, picojson::value(ACTIVE_SECURE_ELEMENT_CHANGED))); break; case NFC_SE_EVENT_CARD_EMULATION_CHANGED: NFCAdapter::GetInstance()->GetCardEmulationMode(&result); - obj.insert(make_pair(JSON_LISTENER_ID, - picojson::value(CARD_EMULATION_MODE_CHANGED))); + obj.insert(make_pair(JSON_LISTENER_ID, picojson::value(CARD_EMULATION_MODE_CHANGED))); break; default: LoggerE("Unsupported se_event: %d", se_event); @@ -275,20 +267,18 @@ static void se_event_callback(nfc_se_event_e se_event, void* /*user_data*/) { NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); } -static void transaction_event_callback(nfc_se_type_e type, - unsigned char* _aid, - int aid_size, - unsigned char* param, - int param_size, - void* /*user_data*/) { +static void transaction_event_callback(nfc_se_type_e type, unsigned char* _aid, int aid_size, + unsigned char* param, int param_size, void* /*user_data*/) { LoggerD("Entered"); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); tools::ReportSuccess(response_obj); - picojson::array& aid_array = response_obj.insert(std::make_pair(JSON_AID, - picojson::value(picojson::array()))).first->second.get(); - picojson::array& data_array = response_obj.insert(std::make_pair(JSON_DATA, - picojson::value(picojson::array()))).first->second.get(); + picojson::array& aid_array = + response_obj.insert(std::make_pair(JSON_AID, picojson::value(picojson::array()))) + .first->second.get(); + picojson::array& data_array = + response_obj.insert(std::make_pair(JSON_DATA, picojson::value(picojson::array()))) + .first->second.get(); for (ssize_t i = 0; i < aid_size; i++) { aid_array.push_back(picojson::value(static_cast(_aid[i]))); @@ -299,11 +289,11 @@ static void transaction_event_callback(nfc_se_type_e type, } if (NFC_SE_TYPE_ESE == type) { - response_obj.insert(make_pair(JSON_LISTENER_ID, - picojson::value(TRANSACTION_EVENT_LISTENER_ESE))); + response_obj.insert( + make_pair(JSON_LISTENER_ID, picojson::value(TRANSACTION_EVENT_LISTENER_ESE))); } else { - response_obj.insert(make_pair(JSON_LISTENER_ID, - picojson::value(TRANSACTION_EVENT_LISTENER_UICC))); + response_obj.insert( + make_pair(JSON_LISTENER_ID, picojson::value(TRANSACTION_EVENT_LISTENER_UICC))); } response_obj.insert(make_pair(JSON_TYPE, picojson::value(TRANSACTION))); @@ -313,9 +303,8 @@ static void transaction_event_callback(nfc_se_type_e type, #ifdef APP_CONTROL_SETTINGS_SUPPORT static void PostMessage(double* callbackId) { LoggerE("Posting error message."); - picojson::value event = CreateEventError(*callbackId, - PlatformResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.")); + picojson::value event = + CreateEventError(*callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "SetPowered failed.")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); delete callbackId; callbackId = NULL; @@ -332,7 +321,8 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { if (!g_idle_add(setPoweredCompleteCB, static_cast(callbackId))) { delete callbackId; callbackId = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SetPowered failed.", ("g_idle addition failed")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("g_idle addition failed")); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -344,9 +334,9 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { if (ret != APP_CONTROL_ERROR_NONE) { delete callbackId; callbackId = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.", - ("app_control_create() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("app_control_create() error: %d, message: %s", ret, get_error_message(ret))); } ret = app_control_set_operation(service, "http://tizen.org/appcontrol/operation/setting/nfc"); @@ -354,9 +344,9 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { app_control_destroy(service); delete callbackId; callbackId = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.", - ("app_control_set_operation() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("app_control_set_operation() error: %d, message: %s", ret, get_error_message(ret))); } ret = app_control_add_extra_data(service, "type", "nfc"); @@ -364,48 +354,50 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { app_control_destroy(service); delete callbackId; callbackId = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.", - ("app_control_add_extra_data() error: %d, message: %s", ret, get_error_message(ret))); - } - - ret = app_control_send_launch_request(service, [](app_control_h request, - app_control_h reply, app_control_result_e result, void* user_data) { - double* callbackId = static_cast(user_data); - if (result != APP_CONTROL_RESULT_SUCCEEDED) { - LoggerE("NFC enable app control failed : %d", result); - PostMessage(callbackId); - return; - } - - if (!g_idle_add(setPoweredCompleteCB, static_cast(callbackId))) { - LoggerE("g_idle addition failed"); - PostMessage(callbackId); - return; - } - }, static_cast(callbackId)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("app_control_add_extra_data() error: %d, message: %s", ret, get_error_message(ret))); + } + + ret = app_control_send_launch_request( + service, + [](app_control_h request, app_control_h reply, app_control_result_e result, void* user_data) { + double* callbackId = static_cast(user_data); + if (result != APP_CONTROL_RESULT_SUCCEEDED) { + LoggerE("NFC enable app control failed : %d", result); + PostMessage(callbackId); + return; + } + + if (!g_idle_add(setPoweredCompleteCB, static_cast(callbackId))) { + LoggerE("g_idle addition failed"); + PostMessage(callbackId); + return; + } + }, + static_cast(callbackId)); if (ret != APP_CONTROL_ERROR_NONE) { app_control_destroy(service); delete callbackId; callbackId = NULL; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.", - ("app_control_send_launch_request() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("app_control_send_launch_request() error: %d, message: %s", ret, get_error_message(ret))); } ret = app_control_destroy(service); if (ret != APP_CONTROL_ERROR_NONE) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SetPowered failed.", - ("app_control_destroy() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "SetPowered failed.", + ("app_control_destroy() error: %d, message: %s", ret, get_error_message(ret))); } #else - int ret = nfc_manager_set_activation(powered, - NFCSetActivationCompletedCallback, static_cast(callbackId)); + int ret = nfc_manager_set_activation(powered, NFCSetActivationCompletedCallback, + static_cast(callbackId)); if (NFC_ERROR_NONE != ret) { - LoggerE("setPowered failed %d",ret); + LoggerE("setPowered failed %d", ret); delete callbackId; callbackId = NULL; return NFCUtil::CodeToResult(ret, "setPowered failed."); @@ -447,8 +439,7 @@ PlatformResult NFCAdapter::SetCardEmulationMode(const std::string& mode) { } if (mode.compare(current_mode) == 0) { - LoggerD("Card emulation mode already set to given value (%s)", - mode.c_str()); + LoggerD("Card emulation mode already set to given value (%s)", mode.c_str()); return PlatformResult(ErrorCode::NO_ERROR); } @@ -463,8 +454,7 @@ PlatformResult NFCAdapter::SetCardEmulationMode(const std::string& mode) { default: // Should never go here - in case of invalid mode // platformResult is returned from convertert few lines above - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid card emulation mode given.", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid card emulation mode given.", ("Invalid card emulation mode: %s", mode.c_str())); } @@ -482,8 +472,7 @@ PlatformResult NFCAdapter::GetActiveSecureElement(std::string* type) { int ret = nfc_manager_get_se_type(&se_type); if (NFC_ERROR_NONE != ret) { LoggerE("Failed to get active secure element type: %d", ret); - return NFCUtil::CodeToResult(ret, - "Unable to get active secure element type"); + return NFCUtil::CodeToResult(ret, "Unable to get active secure element type"); } return NFCUtil::ToStringSecureElementType(se_type, type); @@ -519,8 +508,7 @@ PlatformResult NFCAdapter::SetActiveSecureElement(std::string element) { int ret = nfc_manager_set_se_type(new_type); if (NFC_ERROR_NONE != ret) { LoggerE("Failed to set active secure element type: %d", ret); - return NFCUtil::CodeToResult(ret, - "Unable to set active secure element type"); + return NFCUtil::CodeToResult(ret, "Unable to set active secure element type"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -537,8 +525,7 @@ PlatformResult NFCAdapter::SetExclusiveModeForTransaction(bool exmode) { if (NFC_ERROR_NONE != ret) { LoggerE("Failed to set exclusive mode for transaction: %d", ret); - return NFCUtil::CodeToResult(ret, - "Setting exclusive mode for transaction failed."); + return NFCUtil::CodeToResult(ret, "Setting exclusive mode for transaction failed."); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -549,8 +536,7 @@ PlatformResult NFCAdapter::AddCardEmulationModeChangeListener() { int ret = nfc_manager_set_se_event_cb(se_event_callback, nullptr); if (NFC_ERROR_NONE != ret) { LoggerE("AddCardEmulationModeChangeListener failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } m_is_listener_set = true; } @@ -571,14 +557,11 @@ PlatformResult NFCAdapter::RemoveCardEmulationModeChangeListener() { return PlatformResult(ErrorCode::NO_ERROR); } - -PlatformResult NFCAdapter::AddTransactionEventListener( - const picojson::value& args) { +PlatformResult NFCAdapter::AddTransactionEventListener(const picojson::value& args) { LoggerD("Entered"); nfc_se_type_e se_type = NFC_SE_TYPE_DISABLE; - PlatformResult result = NFCUtil::ToSecureElementType( - args.get(JSON_TYPE).get(), &se_type); + PlatformResult result = NFCUtil::ToSecureElementType(args.get(JSON_TYPE).get(), &se_type); if (result.IsError()) { LoggerD("Error: %s", result.message().c_str()); return result; @@ -587,20 +570,17 @@ PlatformResult NFCAdapter::AddTransactionEventListener( int ret = NFC_ERROR_NONE; if (NFC_SE_TYPE_ESE == se_type) { if (!m_is_transaction_ese_listener_set) { - ret = nfc_manager_set_se_transaction_event_cb(se_type, - transaction_event_callback, NULL); + ret = nfc_manager_set_se_transaction_event_cb(se_type, transaction_event_callback, NULL); m_is_transaction_ese_listener_set = true; } } else if (NFC_SE_TYPE_UICC == se_type) { if (!m_is_transaction_uicc_listener_set) { - ret = nfc_manager_set_se_transaction_event_cb(se_type, - transaction_event_callback, NULL); + ret = nfc_manager_set_se_transaction_event_cb(se_type, transaction_event_callback, NULL); m_is_transaction_uicc_listener_set = true; } } else if (NFC_SE_TYPE_HCE == se_type) { if (!m_is_transaction_hce_listener_set) { - ret = nfc_manager_set_se_transaction_event_cb(se_type, - transaction_event_callback, NULL); + ret = nfc_manager_set_se_transaction_event_cb(se_type, transaction_event_callback, NULL); m_is_transaction_hce_listener_set = true; } } @@ -612,13 +592,11 @@ PlatformResult NFCAdapter::AddTransactionEventListener( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::RemoveTransactionEventListener( - const picojson::value& args) { +PlatformResult NFCAdapter::RemoveTransactionEventListener(const picojson::value& args) { LoggerD("Entered"); nfc_se_type_e se_type = NFC_SE_TYPE_DISABLE; - PlatformResult result = - NFCUtil::ToSecureElementType(args.get(JSON_TYPE).get(), &se_type); + PlatformResult result = NFCUtil::ToSecureElementType(args.get(JSON_TYPE).get(), &se_type); if (result.IsError()) { return result; } @@ -644,8 +622,7 @@ PlatformResult NFCAdapter::AddActiveSecureElementChangeListener() { int ret = nfc_manager_set_se_event_cb(se_event_callback, nullptr); if (NFC_ERROR_NONE != ret) { LoggerE("AddActiveSecureElementChangeListener failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } m_is_listener_set = true; } @@ -712,7 +689,7 @@ PlatformResult NFCAdapter::SetPeerListener() { } if (!m_is_peer_listener_set) { - int ret = nfc_manager_set_p2p_target_discovered_cb (targetDetectedCallback, NULL); + int ret = nfc_manager_set_p2p_target_discovered_cb(targetDetectedCallback, NULL); if (NFC_ERROR_NONE != ret) { LoggerE("Failed to set listener: %d", ret); return NFCUtil::CodeToResult(ret, "setPeerListener failed"); @@ -737,8 +714,7 @@ PlatformResult NFCAdapter::UnsetPeerListener() { return PlatformResult(ErrorCode::NO_ERROR); } -static void targetReceivedCallback(nfc_p2p_target_h /*target*/, - nfc_ndef_message_h message, +static void targetReceivedCallback(nfc_p2p_target_h /*target*/, nfc_ndef_message_h message, void* /*data*/) { LoggerD("Entered"); unsigned char* raw_data = NULL; @@ -752,8 +728,9 @@ static void targetReceivedCallback(nfc_p2p_target_h /*target*/, picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); obj.insert(make_pair("listenerId", picojson::value("ReceiveNDEFListener"))); - obj.insert(make_pair("id", picojson::value(static_cast(NFCAdapter::GetInstance()->GetPeerId())))); - obj.insert(make_pair("action",picojson::value("onsuccess"))); + obj.insert(make_pair( + "id", picojson::value(static_cast(NFCAdapter::GetInstance()->GetPeerId())))); + obj.insert(make_pair("action", picojson::value("onsuccess"))); NFCMessageUtils::ReportNdefMessageFromData(raw_data, size, obj); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); @@ -762,7 +739,7 @@ static void targetReceivedCallback(nfc_p2p_target_h /*target*/, PlatformResult NFCAdapter::SetReceiveNDEFListener(int peer_id) { LoggerD("Entered"); - //unregister previous NDEF listener + // unregister previous NDEF listener if (m_is_ndef_listener_set) { int ret = nfc_p2p_unset_data_received_cb(m_peer_handle); if (NFC_ERROR_NONE != ret) { @@ -771,7 +748,7 @@ PlatformResult NFCAdapter::SetReceiveNDEFListener(int peer_id) { m_is_ndef_listener_set = false; } - //check if peer object is still connected + // check if peer object is still connected bool is_connected = false; PlatformResult result = PeerIsConnectedGetter(peer_id, &is_connected); if (result.IsError()) { @@ -796,7 +773,7 @@ PlatformResult NFCAdapter::SetReceiveNDEFListener(int peer_id) { PlatformResult NFCAdapter::UnsetReceiveNDEFListener(int peer_id) { LoggerD("Entered"); if (m_is_ndef_listener_set) { - //check if peer object is still connected + // check if peer object is still connected bool is_connected = false; PlatformResult result = PeerIsConnectedGetter(peer_id, &is_connected); @@ -825,7 +802,6 @@ bool NFCAdapter::IsNDEFListenerSet() { return m_is_ndef_listener_set; } - // NFCTag related functions PlatformResult NFCAdapter::TagTypeGetter(int /*tag_id*/, std::string* type) { LoggerD("Entered"); @@ -833,7 +809,7 @@ PlatformResult NFCAdapter::TagTypeGetter(int /*tag_id*/, std::string* type) { nfc_tag_type_e nfc_type = NFC_UNKNOWN_TARGET; int err = nfc_tag_get_type(m_last_tag_handle, &nfc_type); - if(NFC_ERROR_NONE != err) { + if (NFC_ERROR_NONE != err) { LoggerE("Failed to get tag type: %d", err); return NFCUtil::CodeToResult(err, "Failed to get tag type"); } @@ -843,57 +819,48 @@ PlatformResult NFCAdapter::TagTypeGetter(int /*tag_id*/, std::string* type) { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::TagIsSupportedNDEFGetter(int /*tag_id*/, - bool* is_supported) { +PlatformResult NFCAdapter::TagIsSupportedNDEFGetter(int /*tag_id*/, bool* is_supported) { LoggerD("Entered"); int err = nfc_tag_is_support_ndef(m_last_tag_handle, is_supported); - if(NFC_ERROR_NONE != err) { + if (NFC_ERROR_NONE != err) { LoggerE("Failed to check if NDEF is supported %d", err); - return NFCUtil::CodeToResult(err, - "Failed to check if NDEF is supported"); + return NFCUtil::CodeToResult(err, "Failed to check if NDEF is supported"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::TagNDEFSizeGetter(int /*tag_id*/, - unsigned int* size) { +PlatformResult NFCAdapter::TagNDEFSizeGetter(int /*tag_id*/, unsigned int* size) { LoggerD("Entered"); int err = nfc_tag_get_ndef_size(m_last_tag_handle, size); - if(NFC_ERROR_NONE != err) { + if (NFC_ERROR_NONE != err) { LoggerE("Failed to get tag NDEF size: %d, %s", err); - return NFCUtil::CodeToResult(err, - "Failed to get tag NDEF size"); + return NFCUtil::CodeToResult(err, "Failed to get tag NDEF size"); } return PlatformResult(ErrorCode::NO_ERROR); } -static bool tagPropertiesGetterCb(const char* key, - const unsigned char* value, - int value_size, +static bool tagPropertiesGetterCb(const char* key, const unsigned char* value, int value_size, void* user_data) { LoggerD("Entered"); if (user_data) { UCharVector tag_info = NFCUtil::ToVector(value, value_size); - (static_cast(user_data))->push_back( - std::make_pair(key, tag_info)); + (static_cast(user_data))->push_back(std::make_pair(key, tag_info)); return true; } return false; } -PlatformResult NFCAdapter::TagPropertiesGetter(int /*tag_id*/, - NFCTagPropertiesT* properties) { +PlatformResult NFCAdapter::TagPropertiesGetter(int /*tag_id*/, NFCTagPropertiesT* properties) { LoggerD("Entered"); - int err = nfc_tag_foreach_information(m_last_tag_handle, - tagPropertiesGetterCb, (void*)properties); - if(NFC_ERROR_NONE != err) { + int err = + nfc_tag_foreach_information(m_last_tag_handle, tagPropertiesGetterCb, (void*)properties); + if (NFC_ERROR_NONE != err) { LoggerE("Error occured while getting NFC properties: %d", err); - return NFCUtil::CodeToResult(err, - "Error occured while getting NFC properties"); + return NFCUtil::CodeToResult(err, "Error occured while getting NFC properties"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -904,7 +871,7 @@ PlatformResult NFCAdapter::TagIsConnectedGetter(int tag_id, bool* state) { PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); - if(tag_id != m_latest_tag_id || NULL == m_last_tag_handle) { + if (tag_id != m_latest_tag_id || NULL == m_last_tag_handle) { // internaly stored tag id changed -> new tag has been already connected // internaly stored tag handle NULL -> tag has been disconnected LoggerD("NFCTag () not connected (id differs or invalid handle)"); @@ -914,15 +881,14 @@ PlatformResult NFCAdapter::TagIsConnectedGetter(int tag_id, bool* state) { nfc_tag_h handle = NULL; int ret = nfc_manager_get_connected_tag(&handle); - if(NFC_ERROR_NONE != ret) { - LoggerE("Failed to get connected tag: %s", - NFCUtil::getNFCErrorMessage(ret).c_str()); + if (NFC_ERROR_NONE != ret) { + LoggerE("Failed to get connected tag: %s", NFCUtil::getNFCErrorMessage(ret).c_str()); // exception is thrown here to return undefined in JS layer // instead of false return NFCUtil::CodeToResult(ret, "Failed to get connected tag"); } - if(m_last_tag_handle != handle) { + if (m_last_tag_handle != handle) { LoggerD("Last known handle and current handle differs"); *state = false; } else { @@ -937,10 +903,7 @@ int NFCAdapter::GetNextTagId() { return ++m_latest_tag_id; } - -static void tagEventCallback(nfc_discovered_type_e type, - nfc_tag_h tag, - void* /*data*/) { +static void tagEventCallback(nfc_discovered_type_e type, nfc_tag_h tag, void* /*data*/) { LoggerD("Entered"); picojson::value event = picojson::value(picojson::object()); @@ -954,8 +917,8 @@ static void tagEventCallback(nfc_discovered_type_e type, int result; result = nfc_tag_get_type(tag, &tag_type); - if(NFC_ERROR_NONE != result) { - LoggerE("setTagListener failed %d",result); + if (NFC_ERROR_NONE != result) { + LoggerE("setTagListener failed %d", result); return; } // Fetch new id and set detected tag handle in NFCAdapter @@ -967,28 +930,23 @@ static void tagEventCallback(nfc_discovered_type_e type, obj.insert(make_pair("type", picojson::value(NFCUtil::ToStringNFCTag(tag_type)))); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); - } - // Tag disconnected event - else if (NFC_DISCOVERED_TYPE_DETACHED == type) { + } else if (NFC_DISCOVERED_TYPE_DETACHED == type) { // Tag disconnected event // Set stored tag handle to NULL adapter->SetTagHandle(NULL); obj.insert(make_pair("action", picojson::value("ondetach"))); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); - } - // ERROR - should never happen - else { + } else { // ERROR - should never happen LoggerE("Invalid NFC discovered type: %d (%x)", type, type); } - } -PlatformResult NFCAdapter::SetTagListener() { +PlatformResult NFCAdapter::SetTagListener() { LoggerD("Entered"); if (!m_is_tag_listener_set) { nfc_manager_set_tag_filter(NFC_TAG_FILTER_ALL_ENABLE); - int result = nfc_manager_set_tag_discovered_cb (tagEventCallback, NULL); + int result = nfc_manager_set_tag_discovered_cb(tagEventCallback, NULL); if (NFC_ERROR_NONE != result) { LoggerE("Failed to register tag listener: %d", result); return NFCUtil::CodeToResult(result, "Failed to register tag listener."); @@ -1001,7 +959,7 @@ PlatformResult NFCAdapter::SetTagListener() { void NFCAdapter::UnsetTagListener() { LoggerD("Entered"); - if(m_is_tag_listener_set) { + if (m_is_tag_listener_set) { nfc_manager_unset_tag_discovered_cb(); m_is_tag_listener_set = false; } @@ -1012,12 +970,10 @@ void NFCAdapter::SetTagHandle(nfc_tag_h tag) { m_last_tag_handle = tag; } -static void tagReadNDEFCb(nfc_error_e result, - nfc_ndef_message_h message, - void* data) { +static void tagReadNDEFCb(nfc_error_e result, nfc_ndef_message_h message, void* data) { LoggerD("Entered"); - if(!data) { + if (!data) { // Can not continue if unable to get callbackId LoggerE("NULL callback id given"); return; @@ -1027,11 +983,11 @@ static void tagReadNDEFCb(nfc_error_e result, delete (double*)data; data = NULL; - if(NFC_ERROR_NONE != result) { + if (NFC_ERROR_NONE != result) { LoggerE("Tag read failed: %d, message: %s", result, get_error_message(result)); // create exception and post error message (call error callback) - picojson::value event = CreateEventError(callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to read NDEF message")); + picojson::value event = CreateEventError( + callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to read NDEF message")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); return; } @@ -1040,15 +996,15 @@ static void tagReadNDEFCb(nfc_error_e result, unsigned int size = 0; int ret = nfc_ndef_message_get_rawdata(message, &raw_data, &size); - if(NFC_ERROR_NONE != ret) { + if (NFC_ERROR_NONE != ret) { LoggerE("Failed to get message data: %d, message: %s", ret, get_error_message(ret)); // release data if any allocated free(raw_data); // create exception and post error message (call error callback) - picojson::value event = CreateEventError(callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to retrieve NDEF message data")); + picojson::value event = CreateEventError( + callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to retrieve NDEF message data")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); return; } @@ -1063,8 +1019,7 @@ static void tagReadNDEFCb(nfc_error_e result, free(raw_data); } -PlatformResult NFCAdapter::TagReadNDEF(int tag_id, - const picojson::value& args) { +PlatformResult NFCAdapter::TagReadNDEF(int tag_id, const picojson::value& args) { LoggerD("Entered"); bool is_connected = false; @@ -1076,29 +1031,26 @@ PlatformResult NFCAdapter::TagReadNDEF(int tag_id, double callbackId = args.get(JSON_CALLBACK_ID).get(); LoggerD("Received callback id: %f", callbackId); - if(!is_connected) { + if (!is_connected) { LoggerE("Tag is not connected"); - picojson::value event = CreateEventError(callbackId, - PlatformResult(ErrorCode::UNKNOWN_ERR, - "Tag is no more connected.")); + picojson::value event = CreateEventError( + callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "Tag is no more connected.")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); return PlatformResult(ErrorCode::NO_ERROR); } double* callbackIdPointer = new double(callbackId); - int ret = nfc_tag_read_ndef(m_last_tag_handle, tagReadNDEFCb, - (void*)(callbackIdPointer)); - if(NFC_ERROR_NONE != ret) { + int ret = nfc_tag_read_ndef(m_last_tag_handle, tagReadNDEFCb, (void*)(callbackIdPointer)); + if (NFC_ERROR_NONE != ret) { LoggerE("Failed to read NDEF message from tag: %d", ret); delete callbackIdPointer; callbackIdPointer = NULL; // for permission related error throw exception ... - if(NFC_ERROR_SECURITY_RESTRICTED == ret || - NFC_ERROR_PERMISSION_DENIED == ret) { - return LogAndCreateResult(ErrorCode::SECURITY_ERR, - "Failed to read NDEF - permission denied", - ("nfc_tag_read_ndef() error: %d, message: %s", ret, get_error_message(ret))); + if (NFC_ERROR_SECURITY_RESTRICTED == ret || NFC_ERROR_PERMISSION_DENIED == ret) { + return LogAndCreateResult( + ErrorCode::SECURITY_ERR, "Failed to read NDEF - permission denied", + ("nfc_tag_read_ndef() error: %d, message: %s", ret, get_error_message(ret))); } LoggerE("Preparing error callback to call"); @@ -1113,8 +1065,7 @@ PlatformResult NFCAdapter::TagReadNDEF(int tag_id, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, - const picojson::value& args) { +PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, const picojson::value& args) { LoggerD("Entered"); bool is_connected = false; @@ -1127,17 +1078,16 @@ PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, double callbackId = args.get(JSON_CALLBACK_ID).get(); LoggerD("Received callback id: %f", callbackId); - if(!is_connected) { + if (!is_connected) { LoggerE("Tag is not connected"); - picojson::value event = CreateEventError(callbackId, - PlatformResult(ErrorCode::UNKNOWN_ERR, - "Tag is no more connected.")); + picojson::value event = CreateEventError( + callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "Tag is no more connected.")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); return PlatformResult(ErrorCode::NO_ERROR); } - const picojson::array& records_array = FromJson( - args.get(), "records"); + const picojson::array& records_array = + FromJson(args.get(), "records"); const int size = static_cast(args.get("recordsSize").get()); @@ -1149,18 +1099,16 @@ PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, return result; } - if(message){ + if (message) { int ret = nfc_tag_write_ndef(m_last_tag_handle, message, NULL, NULL); NFCMessageUtils::RemoveMessageHandle(message); - if (NFC_ERROR_NONE != ret){ - + if (NFC_ERROR_NONE != ret) { // for permission related error throw exception - if(NFC_ERROR_SECURITY_RESTRICTED == ret || - NFC_ERROR_PERMISSION_DENIED == ret) { - return LogAndCreateResult(ErrorCode::SECURITY_ERR, - "Failed to read NDEF - permission denied", - ("nfc_tag_write_ndef() error: %d, message: %s", ret, get_error_message(ret))); + if (NFC_ERROR_SECURITY_RESTRICTED == ret || NFC_ERROR_PERMISSION_DENIED == ret) { + return LogAndCreateResult( + ErrorCode::SECURITY_ERR, "Failed to read NDEF - permission denied", + ("nfc_tag_write_ndef() error: %d, message: %s", ret, get_error_message(ret))); } LoggerE("Error occured when sending message: %d", ret); @@ -1170,25 +1118,21 @@ PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, picojson::value event = CreateEventError(callbackId, result); // create and post error message NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); - } - else { + } else { // create and post success message picojson::value event = createEventSuccess(callbackId); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); } } else { LoggerE("Invalid message handle"); - picojson::value event = CreateEventError(callbackId, PlatformResult(ErrorCode::INVALID_VALUES_ERR, - "Message is not valid")); + picojson::value event = CreateEventError( + callbackId, PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Message is not valid")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); } return PlatformResult(ErrorCode::NO_ERROR); } -static void tagTransceiveCb(nfc_error_e err, - unsigned char* buffer, - int buffer_size, - void* data) { +static void tagTransceiveCb(nfc_error_e err, unsigned char* buffer, int buffer_size, void* data) { LoggerD("Entered"); std::unique_ptr buffer_ptr(buffer); buffer = nullptr; @@ -1203,7 +1147,6 @@ static void tagTransceiveCb(nfc_error_e err, data = nullptr; if (NFC_ERROR_NONE != err) { - LoggerE("NFCTag transceive failed: %d", err); // create exception and post error message (call error callback) @@ -1219,14 +1162,12 @@ static void tagTransceiveCb(nfc_error_e err, picojson::value response = createEventSuccess(callback_id); picojson::object& response_obj = response.get(); tools::ReportSuccess(response_obj); - response_obj[JSON_DATA] = - picojson::value(NFCUtil::FromUCharArray(buffer_ptr.get(), buffer_size)); + response_obj[JSON_DATA] = picojson::value(NFCUtil::FromUCharArray(buffer_ptr.get(), buffer_size)); NFCAdapter::GetInstance()->RespondAsync(response.serialize().c_str()); } PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args) { - LoggerD("Entered"); bool is_connected = false; PlatformResult result = TagIsConnectedGetter(tag_id, &is_connected); @@ -1237,22 +1178,22 @@ PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args double callback_id = args.get(JSON_CALLBACK_ID).get(); LoggerD("Received callback id: %f", callback_id); - if(!is_connected) { + if (!is_connected) { LoggerE("Tag is not connected"); - picojson::value event = CreateEventError(callback_id, - PlatformResult(ErrorCode::UNKNOWN_ERR, "Tag is no more connected.")); + picojson::value event = CreateEventError( + callback_id, PlatformResult(ErrorCode::UNKNOWN_ERR, "Tag is no more connected.")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); return PlatformResult(ErrorCode::NO_ERROR); - } + } - const picojson::array& data_array = FromJson( - args.get(), JSON_DATA); + const picojson::array& data_array = + FromJson(args.get(), JSON_DATA); unsigned char* buffer = NFCUtil::DoubleArrayToUCharArray(data_array); double* callback_id_pointer = new double(callback_id); - int ret = nfc_tag_transceive(m_last_tag_handle, buffer, - data_array.size(), tagTransceiveCb, (void*) callback_id_pointer); + int ret = nfc_tag_transceive(m_last_tag_handle, buffer, data_array.size(), tagTransceiveCb, + (void*)callback_id_pointer); if (NFC_ERROR_NONE != ret) { delete callback_id_pointer; @@ -1261,11 +1202,10 @@ PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args buffer = nullptr; // for permission related error throw exception - if(NFC_ERROR_SECURITY_RESTRICTED == ret || - NFC_ERROR_PERMISSION_DENIED == ret) { - return LogAndCreateResult(ErrorCode::SECURITY_ERR, - "Failed to read NDEF - permission denied", - ("nfc_tag_transceive() error: %d, message: %s", ret, get_error_message(ret))); + if (NFC_ERROR_SECURITY_RESTRICTED == ret || NFC_ERROR_PERMISSION_DENIED == ret) { + return LogAndCreateResult( + ErrorCode::SECURITY_ERR, "Failed to read NDEF - permission denied", + ("nfc_tag_transceive() error: %d, message: %s", ret, get_error_message(ret))); } std::string error_message = NFCUtil::getNFCErrorMessage(ret); @@ -1288,8 +1228,7 @@ PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) { LoggerD("Entered"); nfc_ndef_message_h message_handle = NULL; int result = nfc_manager_get_cached_message(&message_handle); - if (NFC_ERROR_INVALID_NDEF_MESSAGE == result || - NFC_ERROR_NO_NDEF_MESSAGE == result) { + if (NFC_ERROR_INVALID_NDEF_MESSAGE == result || NFC_ERROR_NO_NDEF_MESSAGE == result) { LoggerE("Error: %d", result); NFCMessageUtils::RemoveMessageHandle(message_handle); return PlatformResult(ErrorCode::NO_ERROR); @@ -1301,15 +1240,13 @@ PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) { } unsigned char* raw_data = NULL; unsigned int size; - if (NFC_ERROR_NONE != nfc_ndef_message_get_rawdata(message_handle, - &raw_data, &size)) { + if (NFC_ERROR_NONE != nfc_ndef_message_get_rawdata(message_handle, &raw_data, &size)) { LoggerE("Unknown error while getting message."); free(raw_data); NFCMessageUtils::RemoveMessageHandle(message_handle); return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult ret = NFCMessageUtils::ReportNdefMessageFromData(raw_data, - size, out); + PlatformResult ret = NFCMessageUtils::ReportNdefMessageFromData(raw_data, size, out); free(raw_data); if (ret.IsError()) { LoggerE("Error: %d", ret.message().c_str()); @@ -1324,7 +1261,7 @@ static void peerSentCallback(nfc_error_e result, void* user_data) { LoggerD("Entered"); double* callbackId = static_cast(user_data); - if (NFC_ERROR_NONE != result){ + if (NFC_ERROR_NONE != result) { LoggerE("Error: %d", result); std::string error_message = NFCUtil::getNFCErrorMessage(result); @@ -1359,8 +1296,8 @@ PlatformResult NFCAdapter::sendNDEF(int peer_id, const picojson::value& args) { if (!is_connected) { LoggerE("Peer is not connected"); - picojson::value event = CreateEventError(*callbackId, - PlatformResult(ErrorCode::UNKNOWN_ERR, "Peer is no more connected")); + picojson::value event = CreateEventError( + *callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "Peer is no more connected")); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); delete callbackId; callbackId = NULL; @@ -1372,14 +1309,13 @@ PlatformResult NFCAdapter::sendNDEF(int peer_id, const picojson::value& args) { const int size = static_cast(args.get("recordsSize").get()); nfc_ndef_message_h message = NULL; - result = NFCMessageUtils::NDEFMessageToStruct( - records_array, size, &message); + result = NFCMessageUtils::NDEFMessageToStruct(records_array, size, &message); if (message) { - int ret = nfc_p2p_send(m_peer_handle, message, peerSentCallback, - static_cast(callbackId)); + int ret = + nfc_p2p_send(m_peer_handle, message, peerSentCallback, static_cast(callbackId)); NFCMessageUtils::RemoveMessageHandle(message); if (NFC_ERROR_NONE != ret) { - LoggerE("sendNDEF failed %d",ret); + LoggerE("sendNDEF failed %d", ret); delete callbackId; callbackId = NULL; return NFCUtil::CodeToResult(ret, "sendNDEF failed."); @@ -1410,8 +1346,7 @@ PlatformResult NFCAdapter::AddHCEEventListener() { int ret = nfc_manager_set_hce_event_cb(HCEEventCallback, nullptr); if (NFC_ERROR_NONE != ret) { LoggerE("AddHCEEventListener failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } m_is_hce_listener_set = true; } @@ -1427,10 +1362,9 @@ PlatformResult NFCAdapter::RemoveHCEEventListener() { return PlatformResult(ErrorCode::NO_ERROR); } -void NFCAdapter::SendHostAPDUResponse( - const UCharVector& apdu, - const std::function& success_cb, - const std::function& error_cb) { +void NFCAdapter::SendHostAPDUResponse(const UCharVector& apdu, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("Entered"); if (!nfc_manager_is_supported()) { @@ -1438,22 +1372,18 @@ void NFCAdapter::SendHostAPDUResponse( return; } - int ret = nfc_hce_send_apdu_response(m_se_handle, - const_cast(apdu.data()), - static_cast(apdu.size())); + int ret = nfc_hce_send_apdu_response(m_se_handle, const_cast(apdu.data()), + static_cast(apdu.size())); if (NFC_ERROR_NONE == ret) { success_cb(); } else { LoggerE("Error: %d", ret); - error_cb( - NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str())); + error_cb(NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str())); } } -PlatformResult NFCAdapter::IsActivatedHandlerForAID( - const std::string& type, - const std::string& aid, - bool* is_activated_handler) { +PlatformResult NFCAdapter::IsActivatedHandlerForAID(const std::string& type, const std::string& aid, + bool* is_activated_handler) { AssertMsg(is_activated_handler, "Poiner can not be null!"); LoggerD("Entered"); @@ -1464,20 +1394,16 @@ PlatformResult NFCAdapter::IsActivatedHandlerForAID( return result; } - int ret = nfc_se_is_activated_handler_for_aid(se_type, - aid.c_str(), - is_activated_handler); + int ret = nfc_se_is_activated_handler_for_aid(se_type, aid.c_str(), is_activated_handler); if (NFC_ERROR_NONE != ret) { LoggerE("IsActivatedHandlerForAID failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult NFCAdapter::IsActivatedHandlerForCategory( - const std::string& type, - nfc_card_emulation_category_type_e category, + const std::string& type, nfc_card_emulation_category_type_e category, bool* is_activated_handler) { LoggerD("Entered"); AssertMsg(is_activated_handler, "Poiner can not be null!"); @@ -1489,21 +1415,16 @@ PlatformResult NFCAdapter::IsActivatedHandlerForCategory( return result; } - int ret = nfc_se_is_activated_handler_for_category(se_type, - category, - is_activated_handler); + int ret = nfc_se_is_activated_handler_for_category(se_type, category, is_activated_handler); if (NFC_ERROR_NONE != ret) { LoggerE("IsActivatedHandlerForCategory failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::RegisterAID( - const std::string& type, - const std::string& aid, - nfc_card_emulation_category_type_e category) { +PlatformResult NFCAdapter::RegisterAID(const std::string& type, const std::string& aid, + nfc_card_emulation_category_type_e category) { LoggerD("Entered"); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); @@ -1515,16 +1436,13 @@ PlatformResult NFCAdapter::RegisterAID( int ret = nfc_se_register_aid(se_type, category, aid.c_str()); if (NFC_ERROR_NONE != ret) { LoggerE("RegisterAID failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCAdapter::UnregisterAID( - const std::string& type, - const std::string& aid, - nfc_card_emulation_category_type_e category) { +PlatformResult NFCAdapter::UnregisterAID(const std::string& type, const std::string& aid, + nfc_card_emulation_category_type_e category) { LoggerD("Entered"); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); @@ -1536,16 +1454,12 @@ PlatformResult NFCAdapter::UnregisterAID( int ret = nfc_se_unregister_aid(se_type, category, aid.c_str()); if (NFC_ERROR_NONE != ret) { LoggerE("UnregisterAID failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str()); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str()); } return PlatformResult(ErrorCode::NO_ERROR); } -static void SaveRow(nfc_se_type_e se_type, - const char* aid, - bool read_only, - void* user_data) { +static void SaveRow(nfc_se_type_e se_type, const char* aid, bool read_only, void* user_data) { LoggerD("Entered"); AssertMsg(aid, "Poiner can not be null!"); AssertMsg(user_data, "Poiner can not be null!"); @@ -1554,11 +1468,10 @@ static void SaveRow(nfc_se_type_e se_type, aids->push_back(AIDData(std::string(NFCUtil::ToStr(se_type)), aid_str, read_only)); }; -void NFCAdapter::GetAIDsForCategory( - const std::string& type, - nfc_card_emulation_category_type_e category, - const std::function& success_cb, - const std::function& error_cb) { +void NFCAdapter::GetAIDsForCategory(const std::string& type, + nfc_card_emulation_category_type_e category, + const std::function& success_cb, + const std::function& error_cb) { LoggerD("Entered"); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); @@ -1572,8 +1485,7 @@ void NFCAdapter::GetAIDsForCategory( int ret = nfc_se_foreach_registered_aids(se_type, category, SaveRow, &aids); if (NFC_ERROR_NONE != ret) { LoggerE("GetAIDsForCategory failed: %d", ret); - error_cb(NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str())); + error_cb(NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str())); } success_cb(aids); } @@ -1588,9 +1500,7 @@ PlatformResult NFCAdapter::SetPreferredApp() { int ret = nfc_se_set_preferred_handler(); if (ret != NFC_ERROR_NONE) { LoggerE("SetPreferredApp failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str(), - true); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str(), true); } m_is_preferred_app_set = true; @@ -1607,9 +1517,7 @@ PlatformResult NFCAdapter::UnsetPreferredApp() { int ret = nfc_se_unset_preferred_handler(); if (ret != NFC_ERROR_NONE) { LoggerE("SetPreferredApp failed: %d", ret); - return NFCUtil::CodeToResult(ret, - NFCUtil::getNFCErrorMessage(ret).c_str(), - true); + return NFCUtil::CodeToResult(ret, NFCUtil::getNFCErrorMessage(ret).c_str(), true); } m_is_preferred_app_set = false; @@ -1617,5 +1525,5 @@ PlatformResult NFCAdapter::UnsetPreferredApp() { return PlatformResult(ErrorCode::NO_ERROR); } -}// nfc -}// extension +} // nfc +} // extension diff --git a/src/nfc/nfc_adapter.h b/src/nfc/nfc_adapter.h index 40d2e4b..8e7c1b0 100644 --- a/src/nfc/nfc_adapter.h +++ b/src/nfc/nfc_adapter.h @@ -41,7 +41,7 @@ class NFCAdapter { // Interface provides method PostMessage() that returns asynchronous response. class IResponder { - public: + public: virtual void RespondAsync(const char* msg) = 0; }; @@ -59,7 +59,7 @@ class NFCAdapter { common::PlatformResult SetActiveSecureElement(std::string element); // Adapter methods - common::PlatformResult SetExclusiveModeForTransaction(bool exmode); + common::PlatformResult SetExclusiveModeForTransaction(bool exmode); common::PlatformResult AddCardEmulationModeChangeListener(); common::PlatformResult RemoveCardEmulationModeChangeListener(); @@ -103,34 +103,23 @@ class NFCAdapter { nfc_se_h GetSEHandle(); common::PlatformResult AddHCEEventListener(); common::PlatformResult RemoveHCEEventListener(); - void SendHostAPDUResponse( - const UCharVector& apdu, - const std::function& success_cb, - const std::function& error_cb); - common::PlatformResult IsActivatedHandlerForAID(const std::string& type, - const std::string& aid, + void SendHostAPDUResponse(const UCharVector& apdu, const std::function& success_cb, + const std::function& error_cb); + common::PlatformResult IsActivatedHandlerForAID(const std::string& type, const std::string& aid, bool* is_activated_handler); - common::PlatformResult IsActivatedHandlerForCategory( - const std::string& type, - nfc_card_emulation_category_type_e category, - bool* is_activated_handler); - common::PlatformResult RegisterAID( - const std::string& type, - const std::string& aid, - nfc_card_emulation_category_type_e category); - common::PlatformResult UnregisterAID( - const std::string& type, - const std::string& aid, - nfc_card_emulation_category_type_e category); - void GetAIDsForCategory( - const std::string& type, - nfc_card_emulation_category_type_e category, - const std::function& success_cb, - const std::function& error_cb); + common::PlatformResult IsActivatedHandlerForCategory(const std::string& type, + nfc_card_emulation_category_type_e category, + bool* is_activated_handler); + common::PlatformResult RegisterAID(const std::string& type, const std::string& aid, + nfc_card_emulation_category_type_e category); + common::PlatformResult UnregisterAID(const std::string& type, const std::string& aid, + nfc_card_emulation_category_type_e category); + void GetAIDsForCategory(const std::string& type, nfc_card_emulation_category_type_e category, + const std::function& success_cb, + const std::function& error_cb); common::PlatformResult SetPreferredApp(); common::PlatformResult UnsetPreferredApp(); - private: NFCAdapter(); virtual ~NFCAdapter(); @@ -153,7 +142,7 @@ class NFCAdapter { IResponder* responder_; }; -} // nfc -} // extension +} // nfc +} // extension -#endif // NFC_NFC_ADAPTER_H_ +#endif // NFC_NFC_ADAPTER_H_ diff --git a/src/nfc/nfc_extension.cc b/src/nfc/nfc_extension.cc index 4475d8d..4d0d044 100644 --- a/src/nfc/nfc_extension.cc +++ b/src/nfc/nfc_extension.cc @@ -16,8 +16,8 @@ #include "nfc/nfc_extension.h" -#include "nfc/nfc_instance.h" #include "common/logger.h" +#include "nfc/nfc_instance.h" extern const char kSource_nfc_api[]; @@ -30,19 +30,13 @@ NFCExtension::NFCExtension() { SetExtensionName("tizen.nfc"); SetJavaScriptAPI(kSource_nfc_api); - const char* entry_points[] = { - "tizen.NDEFMessage", - "tizen.NDEFRecord", - "tizen.NDEFRecordText", - "tizen.NDEFRecordURI", - "tizen.NDEFRecordMedia", - NULL - }; + const char* entry_points[] = {"tizen.NDEFMessage", "tizen.NDEFRecord", + "tizen.NDEFRecordText", "tizen.NDEFRecordURI", + "tizen.NDEFRecordMedia", NULL}; SetExtraJSEntryPoints(entry_points); } -NFCExtension::~NFCExtension() -{ +NFCExtension::~NFCExtension() { LoggerD("Entered"); } diff --git a/src/nfc/nfc_extension.h b/src/nfc/nfc_extension.h index 15e4867..7eae1e5 100644 --- a/src/nfc/nfc_extension.h +++ b/src/nfc/nfc_extension.h @@ -23,6 +23,7 @@ class NFCExtension : public common::Extension { public: NFCExtension(); virtual ~NFCExtension(); + private: // common::Extension implementation. virtual common::Instance* CreateInstance(); diff --git a/src/nfc/nfc_instance.cc b/src/nfc/nfc_instance.cc index 3809aa3..5218c2c 100644 --- a/src/nfc/nfc_instance.cc +++ b/src/nfc/nfc_instance.cc @@ -18,6 +18,7 @@ #include +#include #include "common/converter.h" #include "common/logger.h" #include "common/picojson.h" @@ -28,7 +29,6 @@ #include "nfc/defs.h" #include "nfc/nfc_message_utils.h" #include "nfc/nfc_util.h" -#include namespace extension { namespace nfc { @@ -44,43 +44,39 @@ const std::string kPrivilegeNfcCommon = "http://tizen.org/privilege/nfc.common"; const std::string kPrivilegeNfcP2P = "http://tizen.org/privilege/nfc.p2p"; const std::string kPrivilegeNfcTag = "http://tizen.org/privilege/nfc.tag"; -} // namespace +} // namespace void NFCInstance::RespondAsync(const char* msg) { LoggerD("Entered"); Instance::PostMessage(this, msg); } -static bool isTagSupported(){ - LoggerD("Entered"); - bool supported = true; - if (system_info_get_platform_bool( - "http://tizen.org/feature/network.nfc.tag", &supported) - != SYSTEM_INFO_ERROR_NONE) { - LoggerD("Can't check Tag is supported or not"); - } - return supported; +static bool isTagSupported() { + LoggerD("Entered"); + bool supported = true; + if (system_info_get_platform_bool("http://tizen.org/feature/network.nfc.tag", &supported) != + SYSTEM_INFO_ERROR_NONE) { + LoggerD("Can't check Tag is supported or not"); + } + return supported; } -static bool isP2PSupported(){ - LoggerD("Entered"); - bool supported = true; - if (system_info_get_platform_bool( - "http://tizen.org/feature/network.nfc.p2p", &supported) - != SYSTEM_INFO_ERROR_NONE) { - LoggerD("Can't check Tag is supported or not"); - } - return supported; +static bool isP2PSupported() { + LoggerD("Entered"); + bool supported = true; + if (system_info_get_platform_bool("http://tizen.org/feature/network.nfc.p2p", &supported) != + SYSTEM_INFO_ERROR_NONE) { + LoggerD("Can't check Tag is supported or not"); + } + return supported; } NFCInstance::NFCInstance() { LoggerD("Entered"); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&NFCInstance::x, this, _1, _2)); -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&NFCInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&NFCInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&NFCInstance::x, this, _1, _2)); REGISTER_SYNC("NFCManager_getDefaultAdapter", GetDefaultAdapter); REGISTER_SYNC("NFCManager_setExclusiveMode", SetExclusiveMode); REGISTER_ASYNC("NFCAdapter_setPowered", SetPowered); @@ -98,26 +94,21 @@ NFCInstance::NFCInstance() { AddCardEmulationModeChangeListener); REGISTER_SYNC("NFCAdapter_removeCardEmulationModeChangeListener", RemoveCardEmulationModeChangeListener); - REGISTER_SYNC("NFCAdapter_addTransactionEventListener", - AddTransactionEventListener); - REGISTER_SYNC("NFCAdapter_removeTransactionEventListener", - RemoveTransactionEventListener); + REGISTER_SYNC("NFCAdapter_addTransactionEventListener", AddTransactionEventListener); + REGISTER_SYNC("NFCAdapter_removeTransactionEventListener", RemoveTransactionEventListener); REGISTER_SYNC("NFCAdapter_addActiveSecureElementChangeListener", AddActiveSecureElementChangeListener); REGISTER_SYNC("NFCAdapter_removeActiveSecureElementChangeListener", RemoveActiveSecureElementChangeListener); REGISTER_SYNC("NFCAdapter_getCachedMessage", GetCachedMessage); - REGISTER_SYNC("NFCAdapter_setExclusiveModeForTransaction", - SetExclusiveModeForTransaction); + REGISTER_SYNC("NFCAdapter_setExclusiveModeForTransaction", SetExclusiveModeForTransaction); // HCE related methods REGISTER_SYNC("NFCAdapter_addHCEEventListener", AddHCEEventListener); REGISTER_SYNC("NFCAdapter_removeHCEEventListener", RemoveHCEEventListener); REGISTER_ASYNC("NFCAdapter_sendHostAPDUResponse", SendHostAPDUResponse); - REGISTER_SYNC("NFCAdapter_isActivatedHandlerForAID", - IsActivatedHandlerForAID); - REGISTER_SYNC("NFCAdapter_isActivatedHandlerForCategory", - IsActivatedHandlerForCategory); + REGISTER_SYNC("NFCAdapter_isActivatedHandlerForAID", IsActivatedHandlerForAID); + REGISTER_SYNC("NFCAdapter_isActivatedHandlerForCategory", IsActivatedHandlerForCategory); REGISTER_SYNC("NFCAdapter_registerAID", RegisterAID); REGISTER_SYNC("NFCAdapter_unregisterAID", UnregisterAID); REGISTER_ASYNC("NFCAdapter_getAIDsForCategory", GetAIDsForCategory); @@ -127,7 +118,7 @@ NFCInstance::NFCInstance() { REGISTER_SYNC("NFCPeer_setReceiveNDEFListener", SetReceiveNDEFListener); REGISTER_SYNC("NFCPeer_unsetReceiveNDEFListener", UnsetReceiveNDEFListener); REGISTER_SYNC("NDEFMessage_toByte", ToByte); - //Message related methods + // Message related methods REGISTER_SYNC("NDEFMessage_constructor", NDEFMessageContructor); REGISTER_SYNC("NDEFRecord_constructor", NDEFRecordContructor); REGISTER_SYNC("NDEFRecordText_constructor", NDEFRecordTextContructor); @@ -143,7 +134,7 @@ NFCInstance::NFCInstance() { REGISTER_ASYNC("NFCTag_readNDEF", ReadNDEF); REGISTER_ASYNC("NFCTag_writeNDEF", WriteNDEF); - REGISTER_ASYNC("NFCTag_transceive", Transceive ); + REGISTER_ASYNC("NFCTag_transceive", Transceive); REGISTER_ASYNC("NFCPeer_sendNDEF", SendNDEF); #undef REGISTER_SYNC #undef REGISTER_ASYNC @@ -153,11 +144,11 @@ NFCInstance::NFCInstance() { NFCAdapter::GetInstance()->SetResponder(this); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) { \ - LoggerE("args doesn't contain attribute '%s'", name); \ - LogAndReportError(TypeMismatchException(name" is required argument"), out); \ - return; \ +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LoggerE("args doesn't contain attribute '%s'", name); \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ } NFCInstance::~NFCInstance() { @@ -165,29 +156,23 @@ NFCInstance::~NFCInstance() { NFCAdapter::GetInstance()->SetResponder(nullptr); } -void NFCInstance::GetDefaultAdapter( - const picojson::value& args, picojson::object& out) { - +void NFCInstance::GetDefaultAdapter(const picojson::value& args, picojson::object& out) { // Default NFC adapter is created at JS level // Here there's only check for NFC support LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); - if(!nfc_manager_is_supported()) { + if (!nfc_manager_is_supported()) { // According to API reference only Security and Unknown // exceptions are allowed here - LogAndReportError( - PlatformResult(ErrorCode::UNKNOWN_ERR, "NFC manager not supported"), - &out); - } - else { + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "NFC manager not supported"), &out); + } else { ReportSuccess(out); } } -void NFCInstance::SetExclusiveMode( - const picojson::value& args, picojson::object& out) { +void NFCInstance::SetExclusiveMode(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); @@ -196,19 +181,21 @@ void NFCInstance::SetExclusiveMode( int ret = nfc_manager_set_system_handler_enable(!exmode); if (NFC_ERROR_NONE != ret) { - PlatformResult result = NFCUtil::CodeToResult(ret, - "Failed to set exclusive mode."); - LogAndReportError(result, &out, ("nfc_manager_set_system_handler_enable() error: %d, message: %s", ret, get_error_message(ret))); + PlatformResult result = NFCUtil::CodeToResult(ret, "Failed to set exclusive mode."); + LogAndReportError(result, &out, + ("nfc_manager_set_system_handler_enable() error: %d, message: %s", ret, + get_error_message(ret))); } else { ReportSuccess(out); } } -//TODO(g.rynkowski): Rewrite to asynchronous approach -void NFCInstance::SetPowered( - const picojson::value& args, picojson::object& out) { +// TODO(g.rynkowski): Rewrite to asynchronous approach +void NFCInstance::SetPowered(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); - LoggerW("DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. Let the user turn NFC on/off " + LoggerW( + "DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. Let " + "the user turn NFC on/off " "through the Settings application instead."); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcAdmin, &out); @@ -221,15 +208,13 @@ void NFCInstance::SetPowered( } } -void NFCInstance::GetPowered( - const picojson::value& args, picojson::object& out) { +void NFCInstance::GetPowered(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); bool ret = NFCAdapter::GetInstance()->GetPowered(); ReportSuccess(picojson::value(ret), out); } -void NFCInstance::CardEmulationModeSetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::CardEmulationModeSetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -243,8 +228,7 @@ void NFCInstance::CardEmulationModeSetter( } } -void NFCInstance::CardEmulationModeGetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::CardEmulationModeGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -257,8 +241,7 @@ void NFCInstance::CardEmulationModeGetter( } } -void NFCInstance::ActiveSecureElementSetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::ActiveSecureElementSetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -272,8 +255,7 @@ void NFCInstance::ActiveSecureElementSetter( } } -void NFCInstance::ActiveSecureElementGetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::ActiveSecureElementGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -286,20 +268,18 @@ void NFCInstance::ActiveSecureElementGetter( } } -void NFCInstance::SetTagListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::SetTagListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); - bool supported = isTagSupported(); - if (supported) { - SLoggerE("Tag is supported"); - } else { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, - "Tag is not supported on this device."), - &out); - return; - } + bool supported = isTagSupported(); + if (supported) { + SLoggerE("Tag is supported"); + } else { + LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, + "Tag is not supported on this device."), + &out); + return; + } PlatformResult result = NFCAdapter::GetInstance()->SetTagListener(); if (result.IsSuccess()) { ReportSuccess(out); @@ -308,8 +288,7 @@ void NFCInstance::SetTagListener( } } -void NFCInstance::PeerIsConnectedGetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::PeerIsConnectedGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "id", out); @@ -322,21 +301,18 @@ void NFCInstance::PeerIsConnectedGetter( } else { LogAndReportError(result, &out); } - } -void NFCInstance::SetPeerListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::SetPeerListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); bool supported = isP2PSupported(); if (supported) { SLoggerE("P2P is supported"); } else { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, - "P2P is not supported on this device."), - &out); + LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, + "P2P is not supported on this device."), + &out); return; } PlatformResult result = NFCAdapter::GetInstance()->SetPeerListener(); @@ -347,38 +323,34 @@ void NFCInstance::SetPeerListener( } } -void NFCInstance::UnsetTagListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::UnsetTagListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); bool supported = isTagSupported(); if (supported) { SLoggerE("Tag is supported"); } else { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, - "Tag is not supported on this device."), - &out); + LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, + "Tag is not supported on this device."), + &out); return; } NFCAdapter::GetInstance()->UnsetTagListener(); ReportSuccess(out); } -void NFCInstance::UnsetPeerListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::UnsetPeerListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); - bool supported = isP2PSupported(); - if (supported) { - SLoggerE("P2P is supported"); - } else { - LogAndReportError( - common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, - "P2P is not supported on this device."), - &out); - return; - } + bool supported = isP2PSupported(); + if (supported) { + SLoggerE("P2P is supported"); + } else { + LogAndReportError(common::PlatformResult(common::ErrorCode::NOT_SUPPORTED_ERR, + "P2P is not supported on this device."), + &out); + return; + } PlatformResult result = NFCAdapter::GetInstance()->UnsetPeerListener(); if (result.IsSuccess()) { ReportSuccess(out); @@ -387,8 +359,8 @@ void NFCInstance::UnsetPeerListener( } } -void NFCInstance::AddCardEmulationModeChangeListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::AddCardEmulationModeChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -400,8 +372,8 @@ void NFCInstance::AddCardEmulationModeChangeListener( } } -void NFCInstance::RemoveCardEmulationModeChangeListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::RemoveCardEmulationModeChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -413,8 +385,7 @@ void NFCInstance::RemoveCardEmulationModeChangeListener( } } -void NFCInstance::AddTransactionEventListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::AddTransactionEventListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -426,8 +397,8 @@ void NFCInstance::AddTransactionEventListener( } } -void NFCInstance::RemoveTransactionEventListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::RemoveTransactionEventListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -439,8 +410,8 @@ void NFCInstance::RemoveTransactionEventListener( } } -void NFCInstance::AddActiveSecureElementChangeListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::AddActiveSecureElementChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -452,8 +423,8 @@ void NFCInstance::AddActiveSecureElementChangeListener( } } -void NFCInstance::RemoveActiveSecureElementChangeListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::RemoveActiveSecureElementChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -465,8 +436,7 @@ void NFCInstance::RemoveActiveSecureElementChangeListener( } } -void NFCInstance::GetCachedMessage( - const picojson::value& args, picojson::object& out) { +void NFCInstance::GetCachedMessage(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); @@ -481,16 +451,16 @@ void NFCInstance::GetCachedMessage( } } -void NFCInstance::SetExclusiveModeForTransaction( - const picojson::value& args, picojson::object& out) { +void NFCInstance::SetExclusiveModeForTransaction(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, "transactionMode", out); bool transaction_mode = args.get("transactionMode").get(); - PlatformResult result = NFCAdapter::GetInstance()->SetExclusiveModeForTransaction( - transaction_mode); + PlatformResult result = + NFCAdapter::GetInstance()->SetExclusiveModeForTransaction(transaction_mode); if (result.IsSuccess()) { ReportSuccess(out); } else { @@ -498,9 +468,8 @@ void NFCInstance::SetExclusiveModeForTransaction( } } -//TODO(g.rynkowski): Rewrite to asynchronous approach -void NFCInstance::ReadNDEF( - const picojson::value& args, picojson::object& out) { +// TODO(g.rynkowski): Rewrite to asynchronous approach +void NFCInstance::ReadNDEF(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); @@ -517,9 +486,8 @@ void NFCInstance::ReadNDEF( } } -//TODO(g.rynkowski): Rewrite to asynchronous approach -void NFCInstance::WriteNDEF( - const picojson::value& args, picojson::object& out) { +// TODO(g.rynkowski): Rewrite to asynchronous approach +void NFCInstance::WriteNDEF(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); @@ -536,9 +504,8 @@ void NFCInstance::WriteNDEF( } } -//TODO(g.rynkowski): Rewrite to asynchronous approach -void NFCInstance::Transceive( - const picojson::value& args, picojson::object& out) { +// TODO(g.rynkowski): Rewrite to asynchronous approach +void NFCInstance::Transceive(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); @@ -554,8 +521,7 @@ void NFCInstance::Transceive( } } -void NFCInstance::SetReceiveNDEFListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::SetReceiveNDEFListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); @@ -570,8 +536,7 @@ void NFCInstance::SetReceiveNDEFListener( } } -void NFCInstance::UnsetReceiveNDEFListener( - const picojson::value& args, picojson::object& out) { +void NFCInstance::UnsetReceiveNDEFListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); @@ -586,9 +551,8 @@ void NFCInstance::UnsetReceiveNDEFListener( } } -//TODO(g.rynkowski): Rewrite to asynchronous approach -void NFCInstance::SendNDEF( - const picojson::value& args, picojson::object& out) { +// TODO(g.rynkowski): Rewrite to asynchronous approach +void NFCInstance::SendNDEF(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); @@ -606,8 +570,7 @@ void NFCInstance::SendNDEF( } } -void NFCInstance::ToByte( - const picojson::value& args, picojson::object& out) { +void NFCInstance::ToByte(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); picojson::value result = picojson::value(picojson::object()); @@ -621,7 +584,7 @@ void NFCInstance::ToByte( } } -//Message related methods +// Message related methods void NFCInstance::NDEFMessageContructor(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); picojson::value result = picojson::value(picojson::object()); @@ -690,8 +653,7 @@ void NFCInstance::NDEFRecordMediaContructor(const picojson::value& args, picojso } // NFCTag attributes getters -void NFCInstance::TagTypeGetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::TagTypeGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "id", out); @@ -725,8 +687,7 @@ void NFCInstance::TagTypeGetter( } } -void NFCInstance::TagIsSupportedNDEFGetter( - const picojson::value& args, picojson::object& out) { +void NFCInstance::TagIsSupportedNDEFGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); int tag_id = (int)args.get("id").get(); @@ -758,9 +719,7 @@ void NFCInstance::TagIsSupportedNDEFGetter( } } -void NFCInstance::TagNDEFSizeGetter( - const picojson::value& args, picojson::object& out) { - +void NFCInstance::TagNDEFSizeGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); int tag_id = (int)args.get("id").get(); @@ -793,9 +752,7 @@ void NFCInstance::TagNDEFSizeGetter( } } -void NFCInstance::TagPropertiesGetter( - const picojson::value& args, picojson::object& out) { - +void NFCInstance::TagPropertiesGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); int tag_id = (int)args.get("id").get(); @@ -824,16 +781,15 @@ void NFCInstance::TagPropertiesGetter( if (result.IsSuccess()) { picojson::value properties = picojson::value(picojson::array()); picojson::array& properties_array = properties.get(); - for (auto it = prop.begin() ; it != prop.end(); it++) { + for (auto it = prop.begin(); it != prop.end(); it++) { picojson::value val = picojson::value(picojson::object()); picojson::object& obj = val.get(); picojson::value value_vector = picojson::value(picojson::array()); picojson::array& value_vector_obj = value_vector.get(); - for (size_t i = 0 ; i < it->second.size(); i++) { - value_vector_obj.push_back(picojson::value( - std::to_string(it->second[i]))); + for (size_t i = 0; i < it->second.size(); i++) { + value_vector_obj.push_back(picojson::value(std::to_string(it->second[i]))); } obj[it->first] = value_vector; @@ -843,12 +799,9 @@ void NFCInstance::TagPropertiesGetter( } else { LogAndReportError(result, &out); } - } -void NFCInstance::TagIsConnectedGetter( - const picojson::value& args, picojson::object& out) { - +void NFCInstance::TagIsConnectedGetter(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_EXIST(args, "id", out); @@ -865,8 +818,7 @@ void NFCInstance::TagIsConnectedGetter( } } -void NFCInstance::AddHCEEventListener(const picojson::value& args, - picojson::object& out) { +void NFCInstance::AddHCEEventListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -878,8 +830,7 @@ void NFCInstance::AddHCEEventListener(const picojson::value& args, } } -void NFCInstance::RemoveHCEEventListener(const picojson::value& args, - picojson::object& out) { +void NFCInstance::RemoveHCEEventListener(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -891,14 +842,13 @@ void NFCInstance::RemoveHCEEventListener(const picojson::value& args, } } -void NFCInstance::SendHostAPDUResponse(const picojson::value& args, - picojson::object& out) { +void NFCInstance::SendHostAPDUResponse(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_APDU, out); - const picojson::array& apdu_array = FromJson( - args.get(), JSON_APDU); + const picojson::array& apdu_array = + FromJson(args.get(), JSON_APDU); const UCharVector& apdu = NFCUtil::DoubleArrayToUCharVector(apdu_array); const double& callback_id = args.get(JSON_CALLBACK_ID).get(); @@ -920,13 +870,11 @@ void NFCInstance::SendHostAPDUResponse(const picojson::value& args, Instance::PostMessage(this, response.serialize().c_str()); }; - common::TaskQueue::GetInstance().Async( - std::bind(&NFCAdapter::SendHostAPDUResponse, NFCAdapter::GetInstance(), - apdu, success_cb, error_cb)); + common::TaskQueue::GetInstance().Async(std::bind( + &NFCAdapter::SendHostAPDUResponse, NFCAdapter::GetInstance(), apdu, success_cb, error_cb)); } -void NFCInstance::IsActivatedHandlerForAID(const picojson::value& args, - picojson::object& out) { +void NFCInstance::IsActivatedHandlerForAID(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -937,9 +885,7 @@ void NFCInstance::IsActivatedHandlerForAID(const picojson::value& args, bool is_activated_handler = false; PlatformResult result = NFCAdapter::GetInstance()->IsActivatedHandlerForAID( - args.get(JSON_TYPE).get(), - aid, - &is_activated_handler); + args.get(JSON_TYPE).get(), aid, &is_activated_handler); if (result.IsSuccess()) { ReportSuccess(picojson::value(is_activated_handler), out); } else { @@ -959,11 +905,8 @@ void NFCInstance::IsActivatedHandlerForCategory(const picojson::value& args, NFCUtil::StringToCategory(args.get(JSON_CATEGORY).get()); bool is_activated_handler = false; - PlatformResult result = - NFCAdapter::GetInstance()->IsActivatedHandlerForCategory( - args.get(JSON_TYPE).get(), - category, - &is_activated_handler); + PlatformResult result = NFCAdapter::GetInstance()->IsActivatedHandlerForCategory( + args.get(JSON_TYPE).get(), category, &is_activated_handler); if (result.IsSuccess()) { ReportSuccess(picojson::value(is_activated_handler), out); } else { @@ -971,8 +914,7 @@ void NFCInstance::IsActivatedHandlerForCategory(const picojson::value& args, } } -void NFCInstance::RegisterAID(const picojson::value& args, - picojson::object& out) { +void NFCInstance::RegisterAID(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -984,9 +926,7 @@ void NFCInstance::RegisterAID(const picojson::value& args, NFCUtil::StringToCategory(args.get(JSON_CATEGORY).get()); PlatformResult result = NFCAdapter::GetInstance()->RegisterAID( - args.get(JSON_TYPE).get(), - args.get(JSON_AID).get(), - category); + args.get(JSON_TYPE).get(), args.get(JSON_AID).get(), category); if (result.IsSuccess()) { ReportSuccess(out); } else { @@ -994,8 +934,7 @@ void NFCInstance::RegisterAID(const picojson::value& args, } } -void NFCInstance::UnregisterAID(const picojson::value& args, - picojson::object& out) { +void NFCInstance::UnregisterAID(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -1006,11 +945,8 @@ void NFCInstance::UnregisterAID(const picojson::value& args, nfc_card_emulation_category_type_e category = NFCUtil::StringToCategory(args.get(JSON_CATEGORY).get()); - PlatformResult result = - NFCAdapter::GetInstance()->UnregisterAID( - args.get(JSON_TYPE).get(), - args.get(JSON_AID).get(), - category); + PlatformResult result = NFCAdapter::GetInstance()->UnregisterAID( + args.get(JSON_TYPE).get(), args.get(JSON_AID).get(), category); if (result.IsSuccess()) { ReportSuccess(out); } else { @@ -1018,8 +954,7 @@ void NFCInstance::UnregisterAID(const picojson::value& args, } } -void NFCInstance::GetAIDsForCategory(const picojson::value& args, - picojson::object& out) { +void NFCInstance::GetAIDsForCategory(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); @@ -1053,9 +988,9 @@ void NFCInstance::GetAIDsForCategory(const picojson::value& args, Instance::PostMessage(this, response.serialize().c_str()); }; - common::TaskQueue::GetInstance().Async( - std::bind(&NFCAdapter::GetAIDsForCategory, NFCAdapter::GetInstance(), - type, required_category, success_cb, error_cb)); + common::TaskQueue::GetInstance().Async(std::bind(&NFCAdapter::GetAIDsForCategory, + NFCAdapter::GetInstance(), type, + required_category, success_cb, error_cb)); } void NFCInstance::SetPreferredApp(const picojson::value& args, picojson::object& out) { @@ -1082,5 +1017,5 @@ void NFCInstance::UnsetPreferredApp(const picojson::value& args, picojson::objec } } -} // namespace nfc -} // namespace extension +} // namespace nfc +} // namespace extension diff --git a/src/nfc/nfc_instance.h b/src/nfc/nfc_instance.h index 197e8ca..73fd71e 100644 --- a/src/nfc/nfc_instance.h +++ b/src/nfc/nfc_instance.h @@ -23,8 +23,7 @@ namespace extension { namespace nfc { -class NFCInstance: public common::ParsedInstance, NFCAdapter::IResponder -{ +class NFCInstance : public common::ParsedInstance, NFCAdapter::IResponder { public: NFCInstance(); virtual ~NFCInstance(); @@ -89,7 +88,7 @@ class NFCInstance: public common::ParsedInstance, NFCAdapter::IResponder void UnsetPreferredApp(const picojson::value& args, picojson::object& out); }; -} // namespace nfc -} // namespace extension +} // namespace nfc +} // namespace extension -#endif // NFC_NFC_INSTANCE_H_ +#endif // NFC_NFC_INSTANCE_H_ diff --git a/src/nfc/nfc_message_utils.cc b/src/nfc/nfc_message_utils.cc index c5fc48a..cc1d076 100644 --- a/src/nfc/nfc_message_utils.cc +++ b/src/nfc/nfc_message_utils.cc @@ -38,7 +38,7 @@ const int RECORD_TYPE_URI = 0x55; const int TNF_MIN = 0; const int TNF_MAX = 6; -enum nfcTNF{ +enum nfcTNF { NFC_RECORD_TNF_EMPTY = 0, NFC_RECORD_TNF_WELL_KNOWN = 1, NFC_RECORD_TNF_MIME_MEDIA = 2, @@ -50,8 +50,7 @@ enum nfcTNF{ } /* -------------------------------COMMON FUNCTIONS------------------------------------ */ -void NFCMessageUtils::RemoveMessageHandle(nfc_ndef_message_h message_handle) -{ +void NFCMessageUtils::RemoveMessageHandle(nfc_ndef_message_h message_handle) { LoggerD("Entered"); if (message_handle) { int result = nfc_ndef_message_destroy(message_handle); @@ -63,8 +62,7 @@ void NFCMessageUtils::RemoveMessageHandle(nfc_ndef_message_h message_handle) } } -static void removeRecordHandle(nfc_ndef_record_h record_handle) -{ +static void removeRecordHandle(nfc_ndef_record_h record_handle) { LoggerD("Entered"); if (record_handle) { int result = nfc_ndef_record_destroy(record_handle); @@ -76,22 +74,18 @@ static void removeRecordHandle(nfc_ndef_record_h record_handle) } } -static PlatformResult getTnfFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - short *tnf) -{ +static PlatformResult getTnfFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, + short* tnf) { LoggerD("Entered"); nfc_record_tnf_e record_tnf; int result = nfc_ndef_record_get_tnf(handle, &record_tnf); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get record's tnf: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); - //once record handle must be released - from inherited classes constructors - //once record handle cannot be released - from base class constructor + LoggerE("Can't get record's tnf: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); + // once record handle must be released - from inherited classes constructors + // once record handle cannot be released - from base class constructor if (NULL == message_handle) { removeRecordHandle(handle); - } - else { + } else { NFCMessageUtils::RemoveMessageHandle(message_handle); } return NFCUtil::CodeToResult(result, "Can't get record's tnf"); @@ -103,23 +97,19 @@ static PlatformResult getTnfFromHandle(nfc_ndef_record_h handle, } static PlatformResult getTypeNameFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - UCharVector *type) -{ + nfc_ndef_message_h message_handle, UCharVector* type) { LoggerD("Entered"); unsigned char* type_name; int type_size, result; result = nfc_ndef_record_get_type(handle, &type_name, &type_size); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get record's type: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); - //once record handle must be released - from inherited classes constructors - //once record handle cannot be released - from base class constructor + LoggerE("Can't get record's type: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); + // once record handle must be released - from inherited classes constructors + // once record handle cannot be released - from base class constructor if (NULL == message_handle) { removeRecordHandle(handle); - } - else { + } else { NFCMessageUtils::RemoveMessageHandle(message_handle); } return NFCUtil::CodeToResult(result, "Can't get record's type"); @@ -128,24 +118,20 @@ static PlatformResult getTypeNameFromHandle(nfc_ndef_record_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -static PlatformResult getIdFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - UCharVector *id) -{ +static PlatformResult getIdFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, + UCharVector* id) { LoggerD("Entered"); unsigned char* tmp_id; int id_size, result; result = nfc_ndef_record_get_id(handle, &tmp_id, &id_size); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get record's id: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); - //once record handle must be released - from inherited classes constructors - //once record handle cannot be released - from base class constructor + LoggerE("Can't get record's id: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); + // once record handle must be released - from inherited classes constructors + // once record handle cannot be released - from base class constructor if (NULL == message_handle) { removeRecordHandle(handle); - } - else { + } else { NFCMessageUtils::RemoveMessageHandle(message_handle); } return NFCUtil::CodeToResult(result, "Can't get record's id"); @@ -156,9 +142,8 @@ static PlatformResult getIdFromHandle(nfc_ndef_record_h handle, } static PlatformResult getPayloadFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - UCharVector *payload) -{ + nfc_ndef_message_h message_handle, + UCharVector* payload) { LoggerD("Entered"); unsigned char* tmp_payload; unsigned int payload_size; @@ -168,12 +153,11 @@ static PlatformResult getPayloadFromHandle(nfc_ndef_record_h handle, if (NFC_ERROR_NONE != result) { LoggerE("Can't get record's payload: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); - //once record handle must be released - from inherited classes constructors - //once record handle cannot be released - from base class constructor + // once record handle must be released - from inherited classes constructors + // once record handle cannot be released - from base class constructor if (NULL == message_handle) { removeRecordHandle(handle); - } - else { + } else { NFCMessageUtils::RemoveMessageHandle(message_handle); } return NFCUtil::CodeToResult(result, "Can't get record's payload"); @@ -183,19 +167,16 @@ static PlatformResult getPayloadFromHandle(nfc_ndef_record_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -static nfc_encode_type_e convertToNfcEncodeUTF(const std::string& encode_string) -{ +static nfc_encode_type_e convertToNfcEncodeUTF(const std::string& encode_string) { LoggerD("Entered"); if (NFC_TEXT_UTF16 == encode_string) { return NFC_ENCODE_UTF_16; - } - else { + } else { return NFC_ENCODE_UTF_8; } } -static std::string convertEncodingToString(nfc_encode_type_e encoding) -{ +static std::string convertEncodingToString(nfc_encode_type_e encoding) { LoggerD("Entered"); if (encoding == NFC_ENCODE_UTF_16) { return NFC_TEXT_UTF16; @@ -205,8 +186,8 @@ static std::string convertEncodingToString(nfc_encode_type_e encoding) } /* -------------------------------MESSAGE FUNCTIONS------------------------------------ */ -PlatformResult NFCMessageUtils::ToNdefRecords(const nfc_ndef_message_h message, picojson::array& array) -{ +PlatformResult NFCMessageUtils::ToNdefRecords(const nfc_ndef_message_h message, + picojson::array& array) { LoggerD("Entered"); if (NULL != message) { int count; @@ -284,8 +265,7 @@ PlatformResult NFCMessageUtils::ToNdefRecords(const nfc_ndef_message_h message, } PlatformResult NFCMessageUtils::ReportNdefMessageFromData(unsigned char* data, unsigned long size, - picojson::object& out) -{ + picojson::object& out) { LoggerD("Entered"); nfc_ndef_message_h message = NULL; @@ -311,7 +291,8 @@ PlatformResult NFCMessageUtils::ReportNdefMessageFromData(unsigned char* data, u return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCMessageUtils::ReportNDEFMessage(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::ReportNDEFMessage(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const picojson::array& raw_data = FromJson(args.get(), "rawData"); @@ -327,8 +308,7 @@ PlatformResult NFCMessageUtils::ReportNDEFMessage(const picojson::value& args, p } static PlatformResult NdefRecordGetHandle(picojson::value& record, - nfc_ndef_record_h *record_handle) -{ + nfc_ndef_record_h* record_handle) { LoggerD("Entered"); if (!record.is() || !record.contains("tnf") || !record.contains("type") || !record.contains("id") || !record.contains("payload")) { @@ -337,38 +317,32 @@ static PlatformResult NdefRecordGetHandle(picojson::value& record, const picojson::object& record_obj = record.get(); short tnf_from_json = static_cast(record.get("tnf").get()); nfc_record_tnf_e tnf = static_cast(tnf_from_json); - const picojson::array& type_data = - FromJson(record_obj, "type"); + const picojson::array& type_data = FromJson(record_obj, "type"); auto type_size = type_data.size(); std::unique_ptr type(new unsigned char[type_size]); for (size_t i = 0; i < type_size; i++) { type[i] = static_cast(type_data[i].get()); } - const picojson::array& id_data = - FromJson(record_obj, "id"); + const picojson::array& id_data = FromJson(record_obj, "id"); auto id_size = id_data.size(); std::unique_ptr id(new unsigned char[id_size]); for (size_t i = 0; i < id_size; i++) { id[i] = static_cast(id_data[i].get()); } - const picojson::array& payload_data = - FromJson(record_obj, "payload"); + const picojson::array& payload_data = FromJson(record_obj, "payload"); auto payload_size = payload_data.size(); std::unique_ptr payload(new unsigned char[payload_size]); for (size_t i = 0; i < payload_size; i++) { payload[i] = static_cast(payload_data[i].get()); } if ((tnf_from_json < TNF_MIN) || (tnf_from_json > TNF_MAX)) { - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "Type mismatch", - ("Not supported TNF")); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Type mismatch", ("Not supported TNF")); } const int BYTE_ARRAY_MAX = 255; nfc_ndef_record_h ndef_record_handle = NULL; - int result = nfc_ndef_record_create(&ndef_record_handle, - tnf, type.get(), type_size > BYTE_ARRAY_MAX ? BYTE_ARRAY_MAX : type_size, - id.get(), id_size > BYTE_ARRAY_MAX ? BYTE_ARRAY_MAX : id_size, - payload.get(), payload_size); + int result = nfc_ndef_record_create( + &ndef_record_handle, tnf, type.get(), type_size > BYTE_ARRAY_MAX ? BYTE_ARRAY_MAX : type_size, + id.get(), id_size > BYTE_ARRAY_MAX ? BYTE_ARRAY_MAX : id_size, payload.get(), payload_size); if (NFC_ERROR_NONE != result) { removeRecordHandle(ndef_record_handle); LoggerE("Can't create Ndef Record: %d, %s", result, @@ -380,9 +354,7 @@ static PlatformResult NdefRecordGetHandle(picojson::value& record, } PlatformResult NFCMessageUtils::NDEFMessageToStruct(const picojson::array& records_array, - const int size, - nfc_ndef_message_h *message) -{ + const int size, nfc_ndef_message_h* message) { LoggerD("Entered"); if (!size) { LoggerE("No records in message"); @@ -422,14 +394,15 @@ PlatformResult NFCMessageUtils::NDEFMessageToStruct(const picojson::array& recor return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); - //input + // input const picojson::array& records_array = FromJson(args.get(), "records"); const int size = static_cast(args.get("recordsSize").get()); - //output + // output picojson::value byte_array = picojson::value(picojson::array()); picojson::array& byte_array_obj = byte_array.get(); @@ -461,7 +434,7 @@ PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, p return NFCUtil::CodeToResult(result, "Can't get serial bytes of NDEF message"); } - for (size_t i = 0 ; i < raw_data_size; i++) { + for (size_t i = 0; i < raw_data_size; i++) { byte_array_obj.push_back(picojson::value(std::to_string(raw_data[i]))); } if (raw_data) { @@ -472,37 +445,35 @@ PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, p } /* -------------------------------RECORD FUNCTIONS------------------------------------ */ -static void ConstructRecordJson(short _tnf, const UCharVector& _type_name, - const UCharVector& _id, const UCharVector& _payload, picojson::object& out) -{ +static void ConstructRecordJson(short _tnf, const UCharVector& _type_name, const UCharVector& _id, + const UCharVector& _payload, picojson::object& out) { LoggerD("Entered"); out.insert(std::make_pair("tnf", picojson::value(std::to_string(_tnf)))); picojson::value type_array = picojson::value(picojson::array()); picojson::array& type_array_obj = type_array.get(); - for (size_t i = 0 ; i < _type_name.size(); i++) { + for (size_t i = 0; i < _type_name.size(); i++) { type_array_obj.push_back(picojson::value(std::to_string(_type_name[i]))); } out.insert(std::make_pair("type", picojson::value(type_array))); picojson::value id_array = picojson::value(picojson::array()); picojson::array& id_array_obj = id_array.get(); - for (size_t i = 0 ; i < _id.size(); i++) { + for (size_t i = 0; i < _id.size(); i++) { id_array_obj.push_back(picojson::value(std::to_string(_id[i]))); } out.insert(std::make_pair("id", picojson::value(id_array))); picojson::value payload_array = picojson::value(picojson::array()); picojson::array& payload_array_obj = payload_array.get(); - for (size_t i = 0 ; i < _payload.size(); i++) { + for (size_t i = 0; i < _payload.size(); i++) { payload_array_obj.push_back(picojson::value(std::to_string(_payload[i]))); } out.insert(std::make_pair("payload", picojson::value(payload_array))); } PlatformResult NFCMessageUtils::ConstructNdefRecordFromRecordHandle(nfc_ndef_record_h record_handle, - picojson::object& out) -{ + picojson::object& out) { LoggerD("Entered"); short _tnf; @@ -530,20 +501,19 @@ PlatformResult NFCMessageUtils::ConstructNdefRecordFromRecordHandle(nfc_ndef_rec return ret; } - //constructing json + // constructing json ConstructRecordJson(_tnf, _type_name, _id, _payload, out); return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult NFCMessageUtils::ReportNdefRecordFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out) -{ + const int index, + picojson::object& out) { LoggerD("Entered"); nfc_ndef_record_h record_handle = NULL; int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get NdefRecord: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get NdefRecord: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get NdefRecord"); } @@ -551,7 +521,8 @@ PlatformResult NFCMessageUtils::ReportNdefRecordFromMessage(nfc_ndef_message_h m return ConstructNdefRecordFromRecordHandle(record_handle, out); } -PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const picojson::array& raw_data = FromJson(args.get(), "rawData"); @@ -574,8 +545,7 @@ PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, pi int count; result = nfc_ndef_message_get_record_count(message_handle, &count); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get record count: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get record count: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get record count"); } @@ -589,21 +559,17 @@ PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, pi return ret; } - return PlatformResult(ErrorCode::NO_ERROR); } /* -------------------------------RECORD TEXT FUNCTIONS------------------------------------ */ -static PlatformResult getTextFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - std::string *text) -{ +static PlatformResult getTextFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, + std::string* text) { LoggerD("Entered"); char* tmp_text = NULL; int result = nfc_ndef_record_get_text(handle, &tmp_text); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get record's text: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get record's text: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); NFCMessageUtils::RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get record's text"); } @@ -616,9 +582,8 @@ static PlatformResult getTextFromHandle(nfc_ndef_record_h handle, } static PlatformResult getLanguageCodeFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - std::string *language) -{ + nfc_ndef_message_h message_handle, + std::string* language) { LoggerD("Entered"); char* language_code = NULL; int result = nfc_ndef_record_get_langcode(handle, &language_code); @@ -637,9 +602,8 @@ static PlatformResult getLanguageCodeFromHandle(nfc_ndef_record_h handle, } static PlatformResult getEncodingFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - nfc_encode_type_e *encoding_type) -{ + nfc_ndef_message_h message_handle, + nfc_encode_type_e* encoding_type) { LoggerD("Entered"); nfc_encode_type_e encoding; int result = nfc_ndef_record_get_encode_type(handle, &encoding); @@ -654,19 +618,19 @@ static PlatformResult getEncodingFromHandle(nfc_ndef_record_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, const std::string& language_code, - const std::string& encoding_str, picojson::object& out) -{ +static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, + const std::string& language_code, + const std::string& encoding_str, + picojson::object& out) { LoggerD("Entered"); nfc_encode_type_e encoding = convertToNfcEncodeUTF(encoding_str); nfc_ndef_record_h handle = NULL; - int result = nfc_ndef_record_create_text(&handle, text.c_str(), - language_code.c_str(), encoding); + int result = nfc_ndef_record_create_text(&handle, text.c_str(), language_code.c_str(), encoding); if (NFC_ERROR_NONE != result) { LoggerE("Unknown error while getting text record: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); - return NFCUtil::CodeToResult(result,"Can't create text record"); + return NFCUtil::CodeToResult(result, "Can't create text record"); } short _tnf; @@ -694,7 +658,7 @@ static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, cons return ret; } - //constructing json + // constructing json ConstructRecordJson(_tnf, _type_name, _id, _payload, out); removeRecordHandle(handle); @@ -702,20 +666,18 @@ static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, cons } PlatformResult NFCMessageUtils::ReportNdefRecordTextFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out) -{ + const int index, + picojson::object& out) { LoggerD("Entered"); nfc_ndef_record_h record_handle = NULL; - //This function just return the pointer of record. + // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get Ndef Record: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get Ndef Record: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get Ndef Record"); } - nfc_encode_type_e encoding; PlatformResult ret = getEncodingFromHandle(record_handle, message_handle, &encoding); if (ret.IsError()) { @@ -750,7 +712,8 @@ PlatformResult NFCMessageUtils::ReportNdefRecordTextFromMessage(nfc_ndef_message return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCMessageUtils::ReportNDEFRecordText(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::ReportNDEFRecordText(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const std::string& text = args.get("text").get(); const std::string& language_code = args.get("languageCode").get(); @@ -760,16 +723,13 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordText(const picojson::value& args } /* -------------------------------RECORD URI FUNCTIONS------------------------------------ */ -static PlatformResult getURIFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - std::string* uri_handle) -{ +static PlatformResult getURIFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, + std::string* uri_handle) { LoggerD("Entered"); char* uri = NULL; int result = nfc_ndef_record_get_uri(handle, &uri); if (NFC_ERROR_NONE != result || !uri) { - LoggerE("Can't get record's uri: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get record's uri: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); NFCMessageUtils::RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get record's uri"); } @@ -781,13 +741,12 @@ static PlatformResult getURIFromHandle(nfc_ndef_record_h handle, return PlatformResult(ErrorCode::NO_ERROR); } -static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojson::object& out) -{ +static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojson::object& out) { LoggerD("Entered"); nfc_ndef_record_h handle = NULL; int result = nfc_ndef_record_create_uri(&handle, uri.c_str()); - if(NFC_ERROR_NONE != result) { + if (NFC_ERROR_NONE != result) { LoggerE("Unknown error while creating NdefRecordURI: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); return NFCUtil::CodeToResult(result, "Unknown error while creating NdefRecordURI"); @@ -818,7 +777,7 @@ static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojso return ret; } - //constructing json + // constructing json ConstructRecordJson(_tnf, _type_name, _id, _payload, out); removeRecordHandle(handle); @@ -826,15 +785,14 @@ static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojso } PlatformResult NFCMessageUtils::ReportNdefRecordURIFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out) -{ + const int index, + picojson::object& out) { LoggerD("Entered"); nfc_ndef_record_h record_handle = NULL; - //This function just return the pointer of record. + // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get Ndef Record: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get Ndef Record: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get Ndef Record"); } @@ -854,7 +812,8 @@ PlatformResult NFCMessageUtils::ReportNdefRecordURIFromMessage(nfc_ndef_message_ return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCMessageUtils::ReportNDEFRecordURI(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::ReportNDEFRecordURI(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const std::string& uri = args.get("uri").get(); @@ -863,9 +822,7 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordURI(const picojson::value& args, /* -------------------------------RECORD MEDIA FUNCTIONS------------------------------------ */ static PlatformResult getMimeTypeFromHandle(nfc_ndef_record_h handle, - nfc_ndef_message_h message_handle, - std::string *mime) -{ + nfc_ndef_message_h message_handle, std::string* mime) { LoggerD("Entered"); char* mime_type = NULL; int result = nfc_ndef_record_get_mime_type(handle, &mime_type); @@ -884,15 +841,14 @@ static PlatformResult getMimeTypeFromHandle(nfc_ndef_record_h handle, } PlatformResult NFCMessageUtils::ReportNdefRecordMediaFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out) -{ + const int index, + picojson::object& out) { LoggerD("Entered"); nfc_ndef_record_h record_handle = NULL; - //This function just return the pointer of record. + // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); if (NFC_ERROR_NONE != result) { - LoggerE("Can't get Ndef Record: %d, %s", result, - NFCUtil::getNFCErrorMessage(result).c_str()); + LoggerE("Can't get Ndef Record: %d, %s", result, NFCUtil::getNFCErrorMessage(result).c_str()); RemoveMessageHandle(message_handle); return NFCUtil::CodeToResult(result, "Can't get Ndef Record"); } @@ -928,18 +884,18 @@ PlatformResult NFCMessageUtils::ReportNdefRecordMediaFromMessage(nfc_ndef_messag return ret; } - //constructing json + // constructing json ConstructRecordJson(_tnf, _type_name, _id, _payload, out); out.insert(std::make_pair("mimeType", picojson::value(mime_type))); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCMessageUtils::ReportNDEFRecordMedia(const picojson::value& args, picojson::object& out){ +PlatformResult NFCMessageUtils::ReportNDEFRecordMedia(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); const std::string& mime_type = args.get("mimeType").get(); - const picojson::array& raw_data = - FromJson(args.get(), "data"); + const picojson::array& raw_data = FromJson(args.get(), "data"); const int size = static_cast(args.get("dataSize").get()); std::unique_ptr data(new unsigned char[size]); @@ -954,16 +910,13 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordMedia(const picojson::value& arg UCharVector _id; UCharVector _payload; - int result = nfc_ndef_record_create_mime(&handle, mime_type.c_str(), data.get(), - size); + int result = nfc_ndef_record_create_mime(&handle, mime_type.c_str(), data.get(), size); if (NFC_ERROR_NONE != result) { - LoggerE("Unknown error while getting mimeType: %s - %d: %s", - mime_type.c_str(), result, + LoggerE("Unknown error while getting mimeType: %s - %d: %s", mime_type.c_str(), result, NFCUtil::getNFCErrorMessage(result).c_str()); - //Do not throw just return default values - //NFCUtil::throwNFCException(result, "Unknown error while getting mimeType"); + // Do not throw just return default values + // NFCUtil::throwNFCException(result, "Unknown error while getting mimeType"); } else { - PlatformResult ret = getTnfFromHandle(handle, NULL, &_tnf); if (ret.IsError()) { LoggerE("Error: %s", ret.message().c_str()); @@ -986,12 +939,12 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordMedia(const picojson::value& arg } } - //constructing json + // constructing json ConstructRecordJson(_tnf, _type_name, _id, _payload, out); removeRecordHandle(handle); return PlatformResult(ErrorCode::NO_ERROR); } -} // NFC -} // DeviceApi +} // NFC +} // DeviceApi diff --git a/src/nfc/nfc_message_utils.h b/src/nfc/nfc_message_utils.h index 7bd5eb4..e519469 100644 --- a/src/nfc/nfc_message_utils.h +++ b/src/nfc/nfc_message_utils.h @@ -30,31 +30,39 @@ namespace nfc { typedef std::vector UCharVector; -class NFCMessageUtils -{ +class NFCMessageUtils { public: - static common::PlatformResult ToNdefRecords(const nfc_ndef_message_h message, picojson::array& array); + static common::PlatformResult ToNdefRecords(const nfc_ndef_message_h message, + picojson::array& array); static common::PlatformResult ReportNdefMessageFromData(unsigned char* data, unsigned long size, - picojson::object& out); - static common::PlatformResult ReportNDEFMessage(const picojson::value& args, picojson::object& out); + picojson::object& out); + static common::PlatformResult ReportNDEFMessage(const picojson::value& args, + picojson::object& out); static common::PlatformResult NDEFMessageToStruct(const picojson::array& records_array, - const int size, - nfc_ndef_message_h *message); - static common::PlatformResult NDEFMessageToByte(const picojson::value& args, picojson::object& out); - static common::PlatformResult ConstructNdefRecordFromRecordHandle(nfc_ndef_record_h record_handle, + const int size, nfc_ndef_message_h* message); + static common::PlatformResult NDEFMessageToByte(const picojson::value& args, picojson::object& out); + static common::PlatformResult ConstructNdefRecordFromRecordHandle(nfc_ndef_record_h record_handle, + picojson::object& out); static common::PlatformResult ReportNdefRecordFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out); - static common::PlatformResult ReportNDEFRecord(const picojson::value& args, picojson::object& out); + const int index, picojson::object& out); + static common::PlatformResult ReportNDEFRecord(const picojson::value& args, + picojson::object& out); static common::PlatformResult ReportNdefRecordTextFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out); - static common::PlatformResult ReportNDEFRecordText(const picojson::value& args, picojson::object& out); + const int index, + picojson::object& out); + static common::PlatformResult ReportNDEFRecordText(const picojson::value& args, + picojson::object& out); static common::PlatformResult ReportNdefRecordURIFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out); - static common::PlatformResult ReportNDEFRecordURI(const picojson::value& args, picojson::object& out); + const int index, + picojson::object& out); + static common::PlatformResult ReportNDEFRecordURI(const picojson::value& args, + picojson::object& out); static common::PlatformResult ReportNdefRecordMediaFromMessage(nfc_ndef_message_h message_handle, - const int index, picojson::object& out); - static common::PlatformResult ReportNDEFRecordMedia(const picojson::value& args, picojson::object& out); + const int index, + picojson::object& out); + static common::PlatformResult ReportNDEFRecordMedia(const picojson::value& args, + picojson::object& out); static void RemoveMessageHandle(nfc_ndef_message_h message_handle); }; diff --git a/src/nfc/nfc_util.cc b/src/nfc/nfc_util.cc index a9fc84c..3d3327c 100644 --- a/src/nfc/nfc_util.cc +++ b/src/nfc/nfc_util.cc @@ -26,18 +26,16 @@ using namespace common; namespace extension { namespace nfc { -UCharVector NFCUtil::ToVector(const unsigned char* ch, const int size) -{ +UCharVector NFCUtil::ToVector(const unsigned char* ch, const int size) { LoggerD("Entered"); UCharVector vec(ch, ch + size / sizeof(char)); return vec; } -PlatformResult NFCUtil::CodeToResult(const int errorCode, - const std::string& message, +PlatformResult NFCUtil::CodeToResult(const int errorCode, const std::string& message, const bool newAPIVersion) { LoggerD("Entered"); - switch(errorCode) { + switch (errorCode) { case NFC_ERROR_INVALID_PARAMETER: case NFC_ERROR_INVALID_NDEF_MESSAGE: case NFC_ERROR_INVALID_RECORD_TYPE: @@ -65,10 +63,9 @@ PlatformResult NFCUtil::CodeToResult(const int errorCode, } } -std::string NFCUtil::getNFCErrorString(const int error_code) -{ - LoggerD("Error code : %d",error_code); - switch(error_code) { +std::string NFCUtil::getNFCErrorString(const int error_code) { + LoggerD("Error code : %d", error_code); + switch (error_code) { case NFC_ERROR_ALREADY_ACTIVATED: case NFC_ERROR_ALREADY_DEACTIVATED: return ""; @@ -94,7 +91,7 @@ std::string NFCUtil::getNFCErrorString(const int error_code) const std::string NFCUtil::getNFCErrorMessage(const int error_code) { LoggerD("Error code : %d", error_code); - switch(error_code) { + switch (error_code) { case NFC_ERROR_ALREADY_ACTIVATED: case NFC_ERROR_ALREADY_DEACTIVATED: return ""; @@ -133,8 +130,7 @@ const std::string NFCUtil::getNFCErrorMessage(const int error_code) { } } -std::string NFCUtil::ToStringNFCTag(nfc_tag_type_e tag_type) -{ +std::string NFCUtil::ToStringNFCTag(nfc_tag_type_e tag_type) { LoggerD("Entered"); switch (tag_type) { case NFC_GENERIC_PICC: @@ -173,69 +169,50 @@ std::string NFCUtil::ToStringNFCTag(nfc_tag_type_e tag_type) } } -PlatformResult NFCUtil::ToNfcTagString(const std::string& type_string, nfc_tag_type_e* tag_type) -{ +PlatformResult NFCUtil::ToNfcTagString(const std::string& type_string, nfc_tag_type_e* tag_type) { LoggerD("Entered"); if (GENERIC_TARGET == type_string) { *tag_type = NFC_GENERIC_PICC; - } - else if (ISO14443_A == type_string) { + } else if (ISO14443_A == type_string) { *tag_type = NFC_ISO14443_A_PICC; - } - else if (ISO14443_4A == type_string) { + } else if (ISO14443_4A == type_string) { *tag_type = NFC_ISO14443_4A_PICC; - } - else if (ISO14443_3A == type_string) { + } else if (ISO14443_3A == type_string) { *tag_type = NFC_ISO14443_3A_PICC; - } - else if (MIFARE_MINI == type_string) { + } else if (MIFARE_MINI == type_string) { *tag_type = NFC_MIFARE_MINI_PICC; - } - else if (MIFARE_1K == type_string) { + } else if (MIFARE_1K == type_string) { *tag_type = NFC_MIFARE_1K_PICC; - } - else if (MIFARE_4K == type_string) { + } else if (MIFARE_4K == type_string) { *tag_type = NFC_MIFARE_4K_PICC; - } - else if (MIFARE_ULTRA == type_string) { + } else if (MIFARE_ULTRA == type_string) { *tag_type = NFC_MIFARE_ULTRA_PICC; - } - else if (MIFARE_DESFIRE == type_string) { + } else if (MIFARE_DESFIRE == type_string) { *tag_type = NFC_MIFARE_DESFIRE_PICC; - } - else if (ISO14443_B == type_string) { + } else if (ISO14443_B == type_string) { *tag_type = NFC_ISO14443_B_PICC; - } - else if (ISO14443_4B == type_string) { + } else if (ISO14443_4B == type_string) { *tag_type = NFC_ISO14443_4B_PICC; - } - else if (ISO14443_BPRIME == type_string) { + } else if (ISO14443_BPRIME == type_string) { *tag_type = NFC_ISO14443_BPRIME_PICC; - } - else if (FELICA == type_string) { + } else if (FELICA == type_string) { *tag_type = NFC_FELICA_PICC; - } - else if (JEWEL == type_string) { + } else if (JEWEL == type_string) { *tag_type = NFC_JEWEL_PICC; - } - else if (ISO15693 == type_string) { + } else if (ISO15693 == type_string) { *tag_type = NFC_ISO15693_PICC; - } - else if (UNKNOWN_TARGET == type_string) { + } else if (UNKNOWN_TARGET == type_string) { *tag_type = NFC_UNKNOWN_TARGET; - } - else { + } else { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "No Match Tag Type"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCUtil::ToStringCardEmulationMode( - const nfc_se_card_emulation_mode_type_e card_mode, std::string* mode) -{ +PlatformResult NFCUtil::ToStringCardEmulationMode(const nfc_se_card_emulation_mode_type_e card_mode, + std::string* mode) { LoggerD("Entered"); - switch (card_mode) - { + switch (card_mode) { case NFC_SE_CARD_EMULATION_MODE_OFF: *mode = OFF; break; @@ -243,31 +220,27 @@ PlatformResult NFCUtil::ToStringCardEmulationMode( *mode = ALWAYS_ON; break; default: - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "No Match Card Emulation mode", + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "No Match Card Emulation mode", ("No Match Card Emulation mode: %x", card_mode)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCUtil::ToCardEmulationMode( - const std::string& mode_string, - nfc_se_card_emulation_mode_type_e* mode) { +PlatformResult NFCUtil::ToCardEmulationMode(const std::string& mode_string, + nfc_se_card_emulation_mode_type_e* mode) { LoggerD("Entered"); if (mode_string == ALWAYS_ON) { *mode = NFC_SE_CARD_EMULATION_MODE_ON; } else if (mode_string == OFF) { *mode = NFC_SE_CARD_EMULATION_MODE_OFF; } else { - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "No Match Card Emulation mode", + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "No Match Card Emulation mode", ("No Match Card Emulation mode: %s", mode_string.c_str())); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCUtil::ToStringSecureElementType(const nfc_se_type_e se_type, - std::string* type) { +PlatformResult NFCUtil::ToStringSecureElementType(const nfc_se_type_e se_type, std::string* type) { LoggerD("Entered"); switch (se_type) { case NFC_SE_TYPE_ESE: @@ -280,15 +253,13 @@ PlatformResult NFCUtil::ToStringSecureElementType(const nfc_se_type_e se_type, *type = DATA_NFC_SE_TYPE_HCE; break; default: - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "No Match Secure Element Type", + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "No Match Secure Element Type", ("No Match Secure Element Type: %x", se_type)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NFCUtil::ToSecureElementType(const std::string& type_string, - nfc_se_type_e* type) { +PlatformResult NFCUtil::ToSecureElementType(const std::string& type_string, nfc_se_type_e* type) { LoggerD("Entered"); if (type_string == DATA_NFC_SE_TYPE_ESE) { *type = NFC_SE_TYPE_ESE; @@ -297,15 +268,13 @@ PlatformResult NFCUtil::ToSecureElementType(const std::string& type_string, } else if (type_string == DATA_NFC_SE_TYPE_HCE) { *type = NFC_SE_TYPE_HCE; } else { - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "No Match Secure Element Type", + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "No Match Secure Element Type", ("No Match Secure Element Type: %s", type_string.c_str())); } return PlatformResult(ErrorCode::NO_ERROR); } -void NFCUtil::setDefaultFilterValues(std::vector& filter) -{ +void NFCUtil::setDefaultFilterValues(std::vector& filter) { LoggerD("Entered"); filter.push_back(NFC_GENERIC_PICC); filter.push_back(NFC_ISO14443_A_PICC); @@ -363,17 +332,15 @@ const char* NFCUtil::ToStr(nfc_se_type_e se_type) { // Convertion CardEmulationCategoryType(characters sequence) to enum. nfc_card_emulation_category_type_e NFCUtil::StringToCategory(const std::string& category_type) { LoggerD("Entered"); - if (category_type == "PAYMENT") - return NFC_CARD_EMULATION_CATEGORY_PAYMENT; - if (category_type == "OTHER") - return NFC_CARD_EMULATION_CATEGORY_OTHER; + if (category_type == "PAYMENT") return NFC_CARD_EMULATION_CATEGORY_PAYMENT; + if (category_type == "OTHER") return NFC_CARD_EMULATION_CATEGORY_OTHER; AssertMsg(false, "That category type is incorrect."); } unsigned char* NFCUtil::DoubleArrayToUCharArray(const picojson::array& array_in) { LoggerD("Entered"); unsigned char* result_array = new unsigned char[array_in.size()]; - for(std::size_t i = 0; i < array_in.size(); ++i) { + for (std::size_t i = 0; i < array_in.size(); ++i) { result_array[i] = static_cast(array_in.at(i).get()); } return result_array; @@ -384,12 +351,11 @@ UCharVector NFCUtil::DoubleArrayToUCharVector(const picojson::array& array_in) { return ToVector(NFCUtil::DoubleArrayToUCharArray(array_in), array_in.size()); } -picojson::array NFCUtil::FromUCharArray(unsigned char* array, - unsigned int apdu_len) { +picojson::array NFCUtil::FromUCharArray(unsigned char* array, unsigned int apdu_len) { LoggerD("Entered"); picojson::array apdu_array; apdu_array.reserve(apdu_len); - for(unsigned int i = 0; i < apdu_len; ++i) + for (unsigned int i = 0; i < apdu_len; ++i) apdu_array.push_back(picojson::value(static_cast(array[i]))); return apdu_array; } diff --git a/src/nfc/nfc_util.h b/src/nfc/nfc_util.h index 6879eb1..a08b2ad 100644 --- a/src/nfc/nfc_util.h +++ b/src/nfc/nfc_util.h @@ -39,10 +39,10 @@ const std::string MIFARE_ULTRA = "MIFARE_ULTRA"; const std::string MIFARE_DESFIRE = "MIFARE_DESFIRE"; const std::string ISO14443_B = "ISO14443_B"; const std::string ISO14443_4B = "ISO14443_4B"; -const std::string ISO14443_BPRIME = "ISO14443_BPRIME"; -const std::string FELICA = "FELICA"; -const std::string JEWEL = "JEWEL"; -const std::string ISO15693 = "ISO15693"; +const std::string ISO14443_BPRIME = "ISO14443_BPRIME"; +const std::string FELICA = "FELICA"; +const std::string JEWEL = "JEWEL"; +const std::string ISO15693 = "ISO15693"; const std::string UNKNOWN_TARGET = "UNKNOWN_TARGET"; const std::string ALWAYS_ON = "ALWAYS_ON"; @@ -57,12 +57,10 @@ const std::string NOT_SUPPORTED_ERROR_NAME_STR = "NotSupportedError"; typedef std::vector UCharVector; -class NFCUtil -{ +class NFCUtil { public: static UCharVector ToVector(const unsigned char* ch, const int size); - static common::PlatformResult CodeToResult(const int errorCode, - const std::string& message, + static common::PlatformResult CodeToResult(const int errorCode, const std::string& message, const bool newAPIVersion = false); static std::string getNFCErrorString(const int error_code); static const std::string getNFCErrorMessage(const int error_code); @@ -70,12 +68,13 @@ class NFCUtil static common::PlatformResult ToNfcTagString(const std::string& type_string, nfc_tag_type_e* tag_type); static common::PlatformResult ToStringCardEmulationMode( - const nfc_se_card_emulation_mode_type_e card_mode, std::string *mode); - static common::PlatformResult ToCardEmulationMode( - const std::string& mode_string, - nfc_se_card_emulation_mode_type_e* mode); - static common::PlatformResult ToStringSecureElementType(const nfc_se_type_e se_type, std::string *type); - static common::PlatformResult ToSecureElementType(const std::string& type_string, nfc_se_type_e *type); + const nfc_se_card_emulation_mode_type_e card_mode, std::string* mode); + static common::PlatformResult ToCardEmulationMode(const std::string& mode_string, + nfc_se_card_emulation_mode_type_e* mode); + static common::PlatformResult ToStringSecureElementType(const nfc_se_type_e se_type, + std::string* type); + static common::PlatformResult ToSecureElementType(const std::string& type_string, + nfc_se_type_e* type); static void setDefaultFilterValues(std::vector& filter); static const char* ToStr(nfc_hce_event_type_e event_type); static const char* ToStr(nfc_se_type_e se_type); @@ -85,7 +84,7 @@ class NFCUtil static picojson::array FromUCharArray(unsigned char* array, unsigned int apdu_len); }; -} // nfc -} // extension +} // nfc +} // extension -#endif // __TIZEN_NFC_NFCUTIL_H_ +#endif // __TIZEN_NFC_NFCUTIL_H_ diff --git a/src/notification/common_notification.cc b/src/notification/common_notification.cc index a62df7a..eafe781 100644 --- a/src/notification/common_notification.cc +++ b/src/notification/common_notification.cc @@ -16,51 +16,42 @@ #include "notification/common_notification.h" -#include #include +#include #include "common/converter.h" +#include "common/filesystem/filesystem_provider.h" #include "common/logger.h" #include "common/scope_exit.h" -#include "common/filesystem/filesystem_provider.h" namespace extension { namespace notification { using namespace common; -const InformationEnumMap CommonNotification::info_map_ = { - {0, NOTIFICATION_TEXT_TYPE_INFO_1}, - {1, NOTIFICATION_TEXT_TYPE_INFO_2}, - {2, NOTIFICATION_TEXT_TYPE_INFO_3}}; +const InformationEnumMap CommonNotification::info_map_ = {{0, NOTIFICATION_TEXT_TYPE_INFO_1}, + {1, NOTIFICATION_TEXT_TYPE_INFO_2}, + {2, NOTIFICATION_TEXT_TYPE_INFO_3}}; const InformationEnumMap CommonNotification::info_sub_map_ = { {0, NOTIFICATION_TEXT_TYPE_INFO_SUB_1}, {1, NOTIFICATION_TEXT_TYPE_INFO_SUB_2}, {2, NOTIFICATION_TEXT_TYPE_INFO_SUB_3}}; -const ImageEnumMap CommonNotification::thumbnails_map_ = { - {0, NOTIFICATION_IMAGE_TYPE_LIST_1}, - {1, NOTIFICATION_IMAGE_TYPE_LIST_2}, - {2, NOTIFICATION_IMAGE_TYPE_LIST_3}, - {3, NOTIFICATION_IMAGE_TYPE_LIST_4}}; +const ImageEnumMap CommonNotification::thumbnails_map_ = {{0, NOTIFICATION_IMAGE_TYPE_LIST_1}, + {1, NOTIFICATION_IMAGE_TYPE_LIST_2}, + {2, NOTIFICATION_IMAGE_TYPE_LIST_3}, + {3, NOTIFICATION_IMAGE_TYPE_LIST_4}}; const InformationEnumMap CommonNotification::buttons_texts_map_ = { - {0, NOTIFICATION_TEXT_TYPE_BUTTON_1}, - {1, NOTIFICATION_TEXT_TYPE_BUTTON_2}, - {2, NOTIFICATION_TEXT_TYPE_BUTTON_3}, - {3, NOTIFICATION_TEXT_TYPE_BUTTON_4}, - {4, NOTIFICATION_TEXT_TYPE_BUTTON_5}, - {5, NOTIFICATION_TEXT_TYPE_BUTTON_6}}; + {0, NOTIFICATION_TEXT_TYPE_BUTTON_1}, {1, NOTIFICATION_TEXT_TYPE_BUTTON_2}, + {2, NOTIFICATION_TEXT_TYPE_BUTTON_3}, {3, NOTIFICATION_TEXT_TYPE_BUTTON_4}, + {4, NOTIFICATION_TEXT_TYPE_BUTTON_5}, {5, NOTIFICATION_TEXT_TYPE_BUTTON_6}}; const ImageEnumMap CommonNotification::buttons_icon_paths_map_ = { - {0, NOTIFICATION_IMAGE_TYPE_BUTTON_1}, - {1, NOTIFICATION_IMAGE_TYPE_BUTTON_2}, - {2, NOTIFICATION_IMAGE_TYPE_BUTTON_3}, - {3, NOTIFICATION_IMAGE_TYPE_BUTTON_4}, - {4, NOTIFICATION_IMAGE_TYPE_BUTTON_5}, - {5, NOTIFICATION_IMAGE_TYPE_BUTTON_6}}; - + {0, NOTIFICATION_IMAGE_TYPE_BUTTON_1}, {1, NOTIFICATION_IMAGE_TYPE_BUTTON_2}, + {2, NOTIFICATION_IMAGE_TYPE_BUTTON_3}, {3, NOTIFICATION_IMAGE_TYPE_BUTTON_4}, + {4, NOTIFICATION_IMAGE_TYPE_BUTTON_5}, {5, NOTIFICATION_IMAGE_TYPE_BUTTON_6}}; CommonNotification::CommonNotification() { } @@ -86,16 +77,13 @@ bool CommonNotification::IsColorFormatNumeric(const std::string& color) { PlatformResult CommonNotification::SetLayout(notification_h noti_handle, const std::string& noti_type) { - LoggerD("Enter"); notification_ly_type_e noti_layout = NOTIFICATION_LY_NONE; if ("SIMPLE" == noti_type) { long number; - PlatformResult status = - GetNumber(noti_handle, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, &number); - if (status.IsError()) - { + PlatformResult status = GetNumber(noti_handle, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, &number); + if (status.IsError()) { LoggerE("Failed: GetNumber"); return status; } @@ -113,17 +101,14 @@ PlatformResult CommonNotification::SetLayout(notification_h noti_handle, } int ret = notification_set_layout(noti_handle, noti_layout); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification layout error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification layout error", ("Set notification layout error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -static bool ServiceExtraDataCb(app_control_h service, - const char* key, - void* user_data) { +static bool ServiceExtraDataCb(app_control_h service, const char* key, void* user_data) { LoggerD("Enter"); if (nullptr == user_data || nullptr == key) { LoggerE("User data or key not exist"); @@ -134,7 +119,9 @@ static bool ServiceExtraDataCb(app_control_h service, int length = 0; char** value = nullptr; - SCOPE_EXIT { free(value); }; + SCOPE_EXIT { + free(value); + }; int ret = app_control_get_extra_data_array(service, key, &value, &length); if (APP_CONTROL_ERROR_NONE != ret) { @@ -166,18 +153,15 @@ PlatformResult CommonNotification::Create(notification_type_e noti_type, LoggerD("Enter"); *noti_handle = notification_create(noti_type); if (!*noti_handle) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Cannot make new notification object"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot make new notification object"); } if (NOTIFICATION_TYPE_ONGOING == noti_type) { - int ret = notification_set_display_applist( - *noti_handle, - NOTIFICATION_DISPLAY_APP_NOTIFICATION_TRAY | - NOTIFICATION_DISPLAY_APP_INDICATOR); + int ret = + notification_set_display_applist(*noti_handle, NOTIFICATION_DISPLAY_APP_NOTIFICATION_TRAY | + NOTIFICATION_DISPLAY_APP_INDICATOR); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Cannot set notification display applist", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot set notification display applist", ("Cannot make new notification object: %d", ret)); } } @@ -185,10 +169,9 @@ PlatformResult CommonNotification::Create(notification_type_e noti_type, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::StatusTypeFromPlatform( - notification_type_e noti_type, - notification_ly_type_e noti_layout, - std::string* type) { +PlatformResult CommonNotification::StatusTypeFromPlatform(notification_type_e noti_type, + notification_ly_type_e noti_layout, + std::string* type) { LoggerD("Enter"); if (NOTIFICATION_TYPE_NOTI == noti_type) { if (NOTIFICATION_LY_NOTI_EVENT_SINGLE == noti_layout || @@ -204,42 +187,37 @@ PlatformResult CommonNotification::StatusTypeFromPlatform( *type = "PROGRESS"; } } else { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Notification type not found"); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Notification type not found"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::StatusTypeToPlatform( - const std::string& type, - notification_type_e* noti_type) { +PlatformResult CommonNotification::StatusTypeToPlatform(const std::string& type, + notification_type_e* noti_type) { LoggerD("Enter"); if ("SIMPLE" == type || "THUMBNAIL" == type) { *noti_type = NOTIFICATION_TYPE_NOTI; } else if ("ONGOING" == type || "PROGRESS" == type) { *noti_type = NOTIFICATION_TYPE_ONGOING; } else { - return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, - "Invalide notification type", + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalide notification type", ("Invalide noti type: %s", type.c_str())); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetImage( - notification_h noti_handle, - notification_image_type_e image_type, - std::string* image_path) { +PlatformResult CommonNotification::GetImage(notification_h noti_handle, + notification_image_type_e image_type, + std::string* image_path) { LoggerD("Enter"); char* path = nullptr; *image_path = ""; if (NOTIFICATION_ERROR_NONE != notification_get_image(noti_handle, image_type, &path)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification image error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification image error", ("Get notification image error, image_type: %d", image_type)); } if (path) { @@ -249,17 +227,15 @@ PlatformResult CommonNotification::GetImage( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::SetImage( - notification_h noti_handle, - notification_image_type_e image_type, - const std::string& image_path) { +PlatformResult CommonNotification::SetImage(notification_h noti_handle, + notification_image_type_e image_type, + const std::string& image_path) { LoggerD("Enter"); int ret = notification_set_image(noti_handle, image_type, image_path.c_str()); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification image error", - ("Set notification image error, image_type: %d, error: %d", - image_type, ret)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Set notification image error", + ("Set notification image error, image_type: %d, error: %d", image_type, ret)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -274,13 +250,11 @@ PlatformResult CommonNotification::GetText(notification_h noti_handle, *noti_text = ""; if (NOTIFICATION_ERROR_NONE != notification_get_text(noti_handle, text_type, &text)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification text error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification text error", ("Get notification text error, text_type: %d", text_type)); } - if (text) - *noti_text = text; + if (text) *noti_text = text; return PlatformResult(ErrorCode::NO_ERROR); } @@ -289,24 +263,19 @@ PlatformResult CommonNotification::SetText(notification_h noti_handle, notification_text_type_e text_type, const std::string& noti_text) { LoggerD("Enter"); - int ret = notification_set_text(noti_handle, - text_type, - noti_text.c_str(), - nullptr, + int ret = notification_set_text(noti_handle, text_type, noti_text.c_str(), nullptr, NOTIFICATION_VARIABLE_TYPE_NONE); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification text error", - ("Set notification text error, text_type: %d, error: %d", - text_type, ret)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Set notification text error", + ("Set notification text error, text_type: %d, error: %d", text_type, ret)); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult CommonNotification::GetNumber(notification_h noti_handle, - notification_text_type_e text_type, - long* number) { + notification_text_type_e text_type, long* number) { LoggerD("Enter"); std::string text; PlatformResult status = GetText(noti_handle, text_type, &text); @@ -320,8 +289,7 @@ PlatformResult CommonNotification::GetNumber(notification_h noti_handle, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetLedColor(notification_h noti_handle, - std::string* led_color) { +PlatformResult CommonNotification::GetLedColor(notification_h noti_handle, std::string* led_color) { LoggerD("Enter"); unsigned int color = 0; notification_led_op_e type = NOTIFICATION_LED_OP_ON; @@ -343,8 +311,7 @@ PlatformResult CommonNotification::GetLedColor(notification_h noti_handle, led_color->insert(1, "0"); } - std::transform( - led_color->begin(), led_color->end(), led_color->begin(), ::tolower); + std::transform(led_color->begin(), led_color->end(), led_color->begin(), ::tolower); } LoggerD("color:%s", (*led_color).c_str()); @@ -359,15 +326,13 @@ PlatformResult CommonNotification::GetLedPeriod(notification_h noti_handle, int on_time = 0; int off_time = 0; - if (NOTIFICATION_ERROR_NONE != notification_get_led_time_period(noti_handle, &on_time, &off_time)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification led on/off period error"); + if (NOTIFICATION_ERROR_NONE != + notification_get_led_time_period(noti_handle, &on_time, &off_time)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification led on/off period error"); } - if (on_period) - *on_period = on_time; - if (off_period) - *off_period = off_time; + if (on_period) *on_period = on_time; + if (off_period) *off_period = off_time; return PlatformResult(ErrorCode::NO_ERROR); } @@ -381,8 +346,7 @@ PlatformResult CommonNotification::GetSoundPath(notification_h noti_handle, notification_sound_type_e type = NOTIFICATION_SOUND_TYPE_NONE; if (NOTIFICATION_ERROR_NONE != notification_get_sound(noti_handle, &type, &path)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification sound error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification sound error"); } LoggerD("Sound type = %d", type); @@ -399,11 +363,10 @@ PlatformResult CommonNotification::GetSoundPath(notification_h noti_handle, PlatformResult CommonNotification::SetSoundPath(notification_h noti_handle, const std::string& sound_path) { LoggerD("Enter"); - int ret = notification_set_sound( - noti_handle, NOTIFICATION_SOUND_TYPE_USER_DATA, sound_path.c_str()); + int ret = + notification_set_sound(noti_handle, NOTIFICATION_SOUND_TYPE_USER_DATA, sound_path.c_str()); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification sound error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification sound error", ("Set notification sound error: %d", ret)); } @@ -412,14 +375,12 @@ PlatformResult CommonNotification::SetSoundPath(notification_h noti_handle, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetVibration(notification_h noti_handle, - bool* vibration) { +PlatformResult CommonNotification::GetVibration(notification_h noti_handle, bool* vibration) { LoggerD("Enter"); notification_vibration_type_e vib_type = NOTIFICATION_VIBRATION_TYPE_NONE; if (NOTIFICATION_ERROR_NONE != notification_get_vibration(noti_handle, &vib_type, nullptr)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification vibration error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification vibration error"); } if (NOTIFICATION_VIBRATION_TYPE_DEFAULT == vib_type || @@ -432,9 +393,8 @@ PlatformResult CommonNotification::GetVibration(notification_h noti_handle, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetApplicationControl( - app_control_h app_handle, - picojson::object* out_ptr) { +PlatformResult CommonNotification::GetApplicationControl(app_control_h app_handle, + picojson::object* out_ptr) { LoggerD("Enter"); picojson::object& out = *out_ptr; @@ -451,8 +411,7 @@ PlatformResult CommonNotification::GetApplicationControl( int ret = app_control_get_operation(app_handle, &operation); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get application control operation error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get application control operation error", ("Get application control operation error: %d", ret)); } if (operation) { @@ -461,8 +420,7 @@ PlatformResult CommonNotification::GetApplicationControl( } if (APP_CONTROL_ERROR_NONE != app_control_get_uri(app_handle, &uri)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get application control uri error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get application control uri error"); } if (uri) { out["uri"] = picojson::value(uri); @@ -470,8 +428,7 @@ PlatformResult CommonNotification::GetApplicationControl( } if (APP_CONTROL_ERROR_NONE != app_control_get_mime(app_handle, &mime)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get application control mime error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get application control mime error"); } if (mime) { out["mime"] = picojson::value(mime); @@ -479,8 +436,7 @@ PlatformResult CommonNotification::GetApplicationControl( } if (APP_CONTROL_ERROR_NONE != app_control_get_category(app_handle, &category)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get application control category error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get application control category error"); } if (category) { out["category"] = picojson::value(category); @@ -488,23 +444,20 @@ PlatformResult CommonNotification::GetApplicationControl( } picojson::array app_control_data = picojson::array(); - if (APP_CONTROL_ERROR_NONE != app_control_foreach_extra_data( - app_handle, ServiceExtraDataCb, (void*)&app_control_data)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get application control data error"); + if (APP_CONTROL_ERROR_NONE != + app_control_foreach_extra_data(app_handle, ServiceExtraDataCb, (void*)&app_control_data)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get application control data error"); } out["data"] = picojson::value(app_control_data); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::SetApplicationControl( - app_control_h app_handle, - const picojson::object& app_ctrl) { +PlatformResult CommonNotification::SetApplicationControl(app_control_h app_handle, + const picojson::object& app_ctrl) { LoggerD("Enter"); picojson::value val(app_ctrl); - const std::string& operation = - FromJson(app_ctrl, "operation"); + const std::string& operation = FromJson(app_ctrl, "operation"); int ret; if (operation.length()) { @@ -513,8 +466,7 @@ PlatformResult CommonNotification::SetApplicationControl( ret = app_control_set_operation(app_handle, APP_CONTROL_OPERATION_DEFAULT); } if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set application control operation error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set application control operation error", ("Set application control operation error: %d", ret)); } @@ -522,8 +474,7 @@ PlatformResult CommonNotification::SetApplicationControl( const std::string& uri = FromJson(app_ctrl, "uri"); ret = app_control_set_uri(app_handle, uri.c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set application control uri error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set application control uri error", ("Set application control uri error: %d", ret)); } } @@ -532,19 +483,16 @@ PlatformResult CommonNotification::SetApplicationControl( const std::string& mime = FromJson(app_ctrl, "mime"); ret = app_control_set_mime(app_handle, mime.c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set application control mime error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set application control mime error", ("Set application control mime error: %d", ret)); } } if (val.contains("category") && !IsNull(app_ctrl, "category")) { - const std::string& category = - FromJson(app_ctrl, "category"); + const std::string& category = FromJson(app_ctrl, "category"); ret = app_control_set_category(app_handle, category.c_str()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set application control category error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set application control category error", ("Set application control category error: %d", ret)); } } @@ -560,21 +508,19 @@ PlatformResult CommonNotification::SetApplicationControl( for (auto item : items) { const picojson::object& obj = JsonCast(item); const std::string key = FromJson(obj, "key"); - const picojson::array values = - FromJson(obj, "value"); - const char** arrayValue = - (const char**)calloc(sizeof(char*), values.size()); - SCOPE_EXIT { free(arrayValue); }; + const picojson::array values = FromJson(obj, "value"); + const char** arrayValue = (const char**)calloc(sizeof(char*), values.size()); + SCOPE_EXIT { + free(arrayValue); + }; idx = 0; for (auto& item : values) { arrayValue[idx] = JsonCast(item).c_str(); ++idx; } - ret = app_control_add_extra_data_array( - app_handle, key.c_str(), arrayValue, values.size()); + ret = app_control_add_extra_data_array(app_handle, key.c_str(), arrayValue, values.size()); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set application control extra data error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set application control extra data error", ("Set application control extra data error: %d", ret)); } } @@ -582,11 +528,12 @@ PlatformResult CommonNotification::SetApplicationControl( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetApplicationId(app_control_h app_handle, - std::string* app_id) { +PlatformResult CommonNotification::GetApplicationId(app_control_h app_handle, std::string* app_id) { LoggerD("Enter"); char* app_id_str = nullptr; - SCOPE_EXIT { free(app_id_str); }; + SCOPE_EXIT { + free(app_id_str); + }; *app_id = ""; @@ -617,28 +564,24 @@ PlatformResult CommonNotification::SetApplicationId(app_control_h app_handle, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetProgressValue( - notification_h noti_handle, - const std::string& progress_type, - double* progress_value) { +PlatformResult CommonNotification::GetProgressValue(notification_h noti_handle, + const std::string& progress_type, + double* progress_value) { LoggerD("Enter"); double tmp_progress_value = 0.0; if (kProgressTypeByte == progress_type) { if (NOTIFICATION_ERROR_NONE != notification_get_size(noti_handle, &tmp_progress_value)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification size error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification size error"); } } else if (kProgressTypePercentage == progress_type) { if (NOTIFICATION_ERROR_NONE != notification_get_progress(noti_handle, &tmp_progress_value)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification progress error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification progress error"); } // native api uses range 0-1, but webapi expects 0-100, so we need to multiply result with 100 tmp_progress_value *= 100; } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown notification progress type", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown notification progress type", ("Unknown notification progress type: %s ", progress_type.c_str())); } @@ -648,11 +591,9 @@ PlatformResult CommonNotification::GetProgressValue( return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::SetProgressValue( - notification_h noti_handle, - const std::string& progress_type, - double progress_value, - bool is_update) { +PlatformResult CommonNotification::SetProgressValue(notification_h noti_handle, + const std::string& progress_type, + double progress_value, bool is_update) { LoggerD("Enter"); int ret; @@ -660,52 +601,44 @@ PlatformResult CommonNotification::SetProgressValue( ret = notification_set_size(noti_handle, progress_value); if (is_update) { - ret = notification_update_size(noti_handle, NOTIFICATION_PRIV_ID_NONE, - progress_value); + ret = notification_update_size(noti_handle, NOTIFICATION_PRIV_ID_NONE, progress_value); } } else if (kProgressTypePercentage == progress_type) { // native api uses range 0-1, but webapi expects 0-100, so we need to divide by 100 - ret = notification_set_progress(noti_handle, progress_value/100); + ret = notification_set_progress(noti_handle, progress_value / 100); if (is_update) { - ret = notification_update_progress(noti_handle, NOTIFICATION_PRIV_ID_NONE, - progress_value); + ret = notification_update_progress(noti_handle, NOTIFICATION_PRIV_ID_NONE, progress_value); } } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown notification progress type", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown notification progress type", ("Unknown notification progress type: %s ", progress_type.c_str())); } if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification progress/size error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification progress/size error", ("Set notification progress/size error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetPostedTime(notification_h noti_handle, - time_t* posted_time) { +PlatformResult CommonNotification::GetPostedTime(notification_h noti_handle, time_t* posted_time) { LoggerD("Enter"); *posted_time = 0; if (NOTIFICATION_ERROR_NONE != notification_get_insert_time(noti_handle, posted_time)) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification posted time error"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification posted time error"); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::GetNotiHandle(int id, - notification_h* noti_handle) { +PlatformResult CommonNotification::GetNotiHandle(int id, notification_h* noti_handle) { LoggerD("Enter"); *noti_handle = notification_load(nullptr, id); if (nullptr == *noti_handle) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Not found or removed notification id"); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Not found or removed notification id"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -714,26 +647,21 @@ PlatformResult CommonNotification::GetNotiHandle(int id, PlatformResult CommonNotification::GetAppControl(notification_h noti_handle, app_control_h* app_control) { LoggerD("Enter"); - int ret = - notification_get_launch_option(noti_handle, - NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, - static_cast(app_control)); + int ret = notification_get_launch_option(noti_handle, NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, + static_cast(app_control)); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Notification get launch option error", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Notification get launch option error", ("Notification get launch option error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::CreateAppControl( - app_control_h* app_control) { +PlatformResult CommonNotification::CreateAppControl(app_control_h* app_control) { LoggerD("Enter"); int ret = app_control_create(app_control); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Application create error", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Application create error", ("Application create error: %d", ret)); } @@ -743,36 +671,31 @@ PlatformResult CommonNotification::CreateAppControl( PlatformResult CommonNotification::SetAppControl(notification_h noti_handle, app_control_h app_control) { LoggerD("Enter"); - int ret = - notification_set_launch_option(noti_handle, - NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, - static_cast(app_control)); + int ret = notification_set_launch_option(noti_handle, NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, + static_cast(app_control)); if (APP_CONTROL_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Notification set launch option error", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Notification set launch option error", ("Notification set launch option error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::UpdateNotificationAfterPost( - notification_h noti_handle, int id, picojson::object* out_ptr) { +PlatformResult CommonNotification::UpdateNotificationAfterPost(notification_h noti_handle, int id, + picojson::object* out_ptr) { time_t posted_time; PlatformResult status = GetPostedTime(noti_handle, &posted_time); CHECK_ERROR(status); picojson::object& out = *out_ptr; - out["postedTime"] = - picojson::value(static_cast(posted_time) * 1000.0); + out["postedTime"] = picojson::value(static_cast(posted_time) * 1000.0); out["id"] = picojson::value(std::to_string(id)); out["type"] = picojson::value("STATUS"); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::PostNotification(const picojson::object& args, - bool is_update, +PlatformResult CommonNotification::PostNotification(const picojson::object& args, bool is_update, picojson::object* out_ptr, GetHandleFromJsonFun getHandle) { LoggerD("Enter"); @@ -794,16 +717,14 @@ PlatformResult CommonNotification::PostNotification(const picojson::object& args if (is_update) { ret = notification_update(noti_handle); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Update notification error", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Update notification error", ("Update notification error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } else { ret = notification_insert(noti_handle, &id); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Cannot insert notification", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot insert notification", ("Cannot insert notification: %d", ret)); } } @@ -811,7 +732,6 @@ PlatformResult CommonNotification::PostNotification(const picojson::object& args return UpdateNotificationAfterPost(noti_handle, id, out_ptr); } - PlatformResult CommonNotification::AddCommonMembersToJson(int id, notification_h noti_handle, picojson::object* out_ptr) { LoggerD("Enter"); @@ -823,8 +743,7 @@ PlatformResult CommonNotification::AddCommonMembersToJson(int id, notification_h time_t posted_time = 0; PlatformResult ret = GetPostedTime(noti_handle, &posted_time); CHECK_ERROR(ret); - out["postedTime"] = - picojson::value(static_cast(posted_time) * 1000.0); + out["postedTime"] = picojson::value(static_cast(posted_time) * 1000.0); std::string value_str; ret = GetText(noti_handle, NOTIFICATION_TEXT_TYPE_TITLE, &value_str); @@ -841,23 +760,22 @@ PlatformResult CommonNotification::AddCommonMembersToJson(int id, notification_h } PlatformResult CommonNotification::AddTypeToJson(notification_h noti_handle, const std::string& key, - picojson::object* out_ptr, std::string* noti_type_str) { + picojson::object* out_ptr, + std::string* noti_type_str) { LoggerD("Enter"); picojson::object& out = *out_ptr; // Notification type notification_type_e noti_type = NOTIFICATION_TYPE_NONE; int ret = notification_get_type(noti_handle, ¬i_type); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Notification get type error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Notification get type error", ("Notification get type error: %d", ret)); } notification_ly_type_e noti_layout = NOTIFICATION_LY_NONE; ret = notification_get_layout(noti_handle, ¬i_layout); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Notification get layout error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Notification get layout error", ("Notification get layout error: %d", ret)); } @@ -895,7 +813,8 @@ PlatformResult CommonNotification::AddProgressTypeAndValueToJson(notification_h return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::AddEventsNumberToJson(notification_h noti_handle, const std::string& key, +PlatformResult CommonNotification::AddEventsNumberToJson(notification_h noti_handle, + const std::string& key, picojson::object* out_ptr) { LoggerD("Enter"); picojson::object& out = *out_ptr; @@ -918,9 +837,8 @@ PlatformResult CommonNotification::AddDetailInfosToJson(notification_h noti_hand picojson::array& detail_info_array = result_json.get(); if (info_map_.size() != info_sub_map_.size()) { - return LogAndCreateResult( - ErrorCode::VALIDATION_ERR, - "Different notification information types element size"); + return LogAndCreateResult(ErrorCode::VALIDATION_ERR, + "Different notification information types element size"); } picojson::value detail_info = picojson::value(picojson::object()); @@ -935,12 +853,10 @@ PlatformResult CommonNotification::AddDetailInfosToJson(notification_h noti_hand if (text.length()) { detail_info_obj["mainText"] = picojson::value(text); - status = AddTextToJson(noti_handle, info_sub_map_.at(idx), - "subText", &detail_info_obj); + status = AddTextToJson(noti_handle, info_sub_map_.at(idx), "subText", &detail_info_obj); CHECK_ERROR(status); detail_info_array.push_back(detail_info); } - } out["detailInfo"] = result_json; @@ -992,8 +908,7 @@ PlatformResult CommonNotification::AddLedOnOffPeriodToJson(notification_h noti_h return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::AddPathsArrayToJson(notification_h noti_handle, - ImageEnumMap map, +PlatformResult CommonNotification::AddPathsArrayToJson(notification_h noti_handle, ImageEnumMap map, const std::string& key, picojson::object* out_ptr) { LoggerD("Enter"); @@ -1009,8 +924,7 @@ PlatformResult CommonNotification::AddPathsArrayToJson(notification_h noti_handl CHECK_ERROR(status); if (path.length()) { - result_array.push_back( - picojson::value(FilesystemProvider::Create().GetVirtualPath(path))); + result_array.push_back(picojson::value(FilesystemProvider::Create().GetVirtualPath(path))); } } @@ -1113,14 +1027,12 @@ PlatformResult CommonNotification::AddAppControlInfoToJson(notification_h noti_h } PlatformResult CommonNotification::InitNotiFromJson(const picojson::object& noti_obj, - const std::string& type_key, - bool is_update, + const std::string& type_key, bool is_update, notification_h* noti_handle) { LoggerD("Enter"); notification_h tmp_noti = nullptr; - const std::string& status_type = - FromJson(noti_obj, type_key.c_str()); + const std::string& status_type = FromJson(noti_obj, type_key.c_str()); notification_type_e noti_type = NOTIFICATION_TYPE_NONE; PlatformResult status = StatusTypeToPlatform(status_type, ¬i_type); @@ -1135,8 +1047,8 @@ PlatformResult CommonNotification::InitNotiFromJson(const picojson::object& noti status = Create(noti_type, &tmp_noti); CHECK_ERROR(status); } - std::unique_ptr::type, int(*)(notification_h)> - tmp_noti_ptr(tmp_noti, ¬ification_free); // automatically release the memory + std::unique_ptr::type, int (*)(notification_h)> tmp_noti_ptr( + tmp_noti, ¬ification_free); // automatically release the memory status = SetLayout(tmp_noti, status_type); CHECK_ERROR(status); @@ -1145,14 +1057,12 @@ PlatformResult CommonNotification::InitNotiFromJson(const picojson::object& noti return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult CommonNotification::SetCommonMembersFromJson(const picojson::value& noti_value, notification_h noti_handle) { LoggerD("Enter"); const picojson::object& noti_obj = noti_value.get(); - PlatformResult status = SetText(noti_handle, - NOTIFICATION_TEXT_TYPE_TITLE, - FromJson(noti_obj, "title")); + PlatformResult status = + SetText(noti_handle, NOTIFICATION_TEXT_TYPE_TITLE, FromJson(noti_obj, "title")); CHECK_ERROR(status); SetTextFromJson(noti_value, NOTIFICATION_TEXT_TYPE_CONTENT, "content", noti_handle); @@ -1182,20 +1092,17 @@ PlatformResult CommonNotification::SetLedColorFromJson(const picojson::value& no const picojson::object& noti_obj = noti_value.get(); if (noti_value.contains("ledColor") && !IsNull(noti_obj, "ledColor")) { std::string color_str = FromJson(noti_obj, "ledColor"); - std::transform( - color_str.begin(), color_str.end(), color_str.begin(), ::tolower); + std::transform(color_str.begin(), color_str.end(), color_str.begin(), ::tolower); if (!IsColorFormatNumeric(color_str)) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Led color is not numeric value", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Led color is not numeric value", ("Led color is not numeric value: %s", color_str.c_str())); } std::stringstream stream; unsigned int color = 0; notification_led_op_e type = NOTIFICATION_LED_OP_ON; - std::string color_code = - color_str.substr(1, color_str.length()).insert(0, "ff"); + std::string color_code = color_str.substr(1, color_str.length()).insert(0, "ff"); stream << std::hex << color_code; stream >> color; @@ -1207,8 +1114,7 @@ PlatformResult CommonNotification::SetLedColorFromJson(const picojson::value& no int ret = notification_set_led(noti_handle, type, static_cast(color)); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification led color eror", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification led color eror", ("Set notification led color eror: %d", ret)); } } @@ -1220,8 +1126,7 @@ PlatformResult CommonNotification::SetLedOnPeriodFromJson(const picojson::value& notification_h noti_handle) { LoggerD("Enter"); const picojson::object& noti_obj = noti_value.get(); - unsigned long on_period = static_cast( - FromJson(noti_obj, "ledOnPeriod")); + unsigned long on_period = static_cast(FromJson(noti_obj, "ledOnPeriod")); unsigned long off_period = 0; PlatformResult status = GetLedPeriod(noti_handle, nullptr, &off_period); @@ -1229,8 +1134,7 @@ PlatformResult CommonNotification::SetLedOnPeriodFromJson(const picojson::value& int ret = notification_set_led_time_period(noti_handle, on_period, off_period); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification led on period error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification led on period error", ("Set notification led on period error: %d", ret)); } @@ -1241,33 +1145,29 @@ PlatformResult CommonNotification::SetLedOffPeriodFromJson(const picojson::value notification_h noti_handle) { LoggerD("Enter"); const picojson::object& noti_obj = noti_value.get(); - unsigned long off_period = static_cast( - FromJson(noti_obj, "ledOffPeriod")); + unsigned long off_period = static_cast(FromJson(noti_obj, "ledOffPeriod")); unsigned long on_period = 0; PlatformResult status = GetLedPeriod(noti_handle, &on_period, nullptr); CHECK_ERROR(status); int ret = notification_set_led_time_period(noti_handle, on_period, off_period); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification led off period error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification led off period error", ("Set notification led off period error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult CommonNotification::SetProgressTypeAndValueFromJson(const picojson::value& noti_value, - bool is_update, - notification_h noti_handle) { +PlatformResult CommonNotification::SetProgressTypeAndValueFromJson( + const picojson::value& noti_value, bool is_update, notification_h noti_handle) { LoggerD("Enter"); const picojson::object& noti_obj = noti_value.get(); // progressType // native code does not support progress_type value, we are using NOTIFICATION_IMAGE_TYPE_LIST_5 // to store this field on native level - const std::string& progress_type = - FromJson(noti_obj, "progressType"); + const std::string& progress_type = FromJson(noti_obj, "progressType"); PlatformResult status = SetImage(noti_handle, NOTIFICATION_IMAGE_TYPE_LIST_5, progress_type); CHECK_ERROR(status); @@ -1297,14 +1197,12 @@ PlatformResult CommonNotification::SetAppControlInfoFromJson(const picojson::val CHECK_ERROR(status); if (noti_value.contains("appControl") && !IsNull(noti_obj, "appControl")) { - status = SetApplicationControl( - app_control, FromJson(noti_obj, "appControl")); + status = SetApplicationControl(app_control, FromJson(noti_obj, "appControl")); CHECK_ERROR(status); } if (noti_value.contains("appId") && !IsNull(noti_obj, "appId")) { - status = SetApplicationId(app_control, - FromJson(noti_obj, "appId")); + status = SetApplicationId(app_control, FromJson(noti_obj, "appId")); CHECK_ERROR(status); } @@ -1322,8 +1220,8 @@ PlatformResult CommonNotification::SetEventsNumberFromJson(const picojson::value if (noti_value.contains(key) && !IsNull(noti_obj, key.c_str())) { long number = (long)FromJson(noti_obj, key.c_str()); - PlatformResult status = SetText(noti_handle, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, - std::to_string(number)); + PlatformResult status = + SetText(noti_handle, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, std::to_string(number)); CHECK_ERROR(status); } return PlatformResult(ErrorCode::NO_ERROR); @@ -1346,9 +1244,7 @@ PlatformResult CommonNotification::SetDetailInfosFromJson(const picojson::value& const picojson::object& obj = JsonCast(item); PlatformResult status = - SetText(noti_handle, - info_map_.at(idx), - FromJson(obj, "mainText")); + SetText(noti_handle, info_map_.at(idx), FromJson(obj, "mainText")); CHECK_ERROR(status); SetTextFromJson(picojson::value(obj), info_sub_map_.at(idx), "subText", noti_handle); @@ -1378,8 +1274,7 @@ PlatformResult CommonNotification::SetVibrationFromJson(const picojson::value& n int ret = notification_set_vibration(noti_handle, vib_type, nullptr); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Set notification vibration error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set notification vibration error", ("Set notification vibration error: %d", ret)); } } @@ -1404,8 +1299,7 @@ PlatformResult CommonNotification::SetSoundPathFromJson(const picojson::value& n } PlatformResult CommonNotification::SetPathsArrayFromJson(const picojson::value& noti_value, - ImageEnumMap map, - const std::string& key, + ImageEnumMap map, const std::string& key, notification_h noti_handle) { LoggerD("Enter"); const picojson::object& noti_obj = noti_value.get(); @@ -1464,7 +1358,8 @@ PlatformResult CommonNotification::SetTextFromJson(const picojson::value& noti_v const picojson::object& noti_obj = noti_value.get(); if (noti_value.contains(key) && !IsNull(noti_obj, key.c_str())) { - PlatformResult status = SetText(noti_handle, type, FromJson(noti_obj, key.c_str())); + PlatformResult status = + SetText(noti_handle, type, FromJson(noti_obj, key.c_str())); CHECK_ERROR(status); } return PlatformResult(ErrorCode::NO_ERROR); diff --git a/src/notification/common_notification.h b/src/notification/common_notification.h index 47c7079..a5c813d 100644 --- a/src/notification/common_notification.h +++ b/src/notification/common_notification.h @@ -17,8 +17,8 @@ #ifndef NOTIFICATION_COMMON_NOTIFICATION_H_ #define NOTIFICATION_COMMON_NOTIFICATION_H_ -#include #include +#include #include #include "common/picojson.h" @@ -30,9 +30,9 @@ namespace extension { namespace notification { #define CHECK_ERROR(ret) \ - if (ret.IsError()) { \ - return ret; \ - } + if (ret.IsError()) { \ + return ret; \ + } const std::string kProgressTypePercentage = "PERCENTAGE"; const std::string kProgressTypeByte = "BYTE"; @@ -40,17 +40,15 @@ const std::string kProgressTypeByte = "BYTE"; typedef std::map InformationEnumMap; typedef std::map ImageEnumMap; -XW_EXPORT typedef std::function< - common::PlatformResult(const picojson::value& noti_val, - bool is_update, - notification_h *noti_handle)> GetHandleFromJsonFun; +XW_EXPORT typedef std::function + GetHandleFromJsonFun; class CommonNotification { public: XW_EXPORT static common::PlatformResult GetAppControl(notification_h noti_handle, app_control_h* app_control); - static common::PlatformResult GetNotiHandle(int id, - notification_h* noti_handle); + static common::PlatformResult GetNotiHandle(int id, notification_h* noti_handle); XW_EXPORT static common::PlatformResult SetAppControl(notification_h noti_handle, app_control_h app_control); @@ -60,15 +58,12 @@ class CommonNotification { static const InformationEnumMap buttons_texts_map_; static const ImageEnumMap buttons_icon_paths_map_; - static common::PlatformResult StatusTypeFromPlatform( - notification_type_e noti_type, - notification_ly_type_e noti_layout, - std::string* type); - static common::PlatformResult StatusTypeToPlatform( - const std::string& type, - notification_type_e* noti_type); - static common::PlatformResult Create(notification_type_e noti_type, - notification_h* noti_handle); + static common::PlatformResult StatusTypeFromPlatform(notification_type_e noti_type, + notification_ly_type_e noti_layout, + std::string* type); + static common::PlatformResult StatusTypeToPlatform(const std::string& type, + notification_type_e* noti_type); + static common::PlatformResult Create(notification_type_e noti_type, notification_h* noti_handle); static common::PlatformResult GetImage(notification_h noti_handle, notification_image_type_e image_type, std::string* image_path); @@ -76,48 +71,34 @@ class CommonNotification { notification_image_type_e image_type, const std::string& image_path); static common::PlatformResult GetText(notification_h noti_handle, - notification_text_type_e text_type, - std::string* noti_text); + notification_text_type_e text_type, std::string* noti_text); static common::PlatformResult SetText(notification_h noti_handle, notification_text_type_e text_type, const std::string& noti_text); static common::PlatformResult GetNumber(notification_h noti_handle, - notification_text_type_e text_type, - long* number); - static common::PlatformResult GetLedColor(notification_h noti_handle, - std::string* led_color); - static common::PlatformResult GetLedPeriod(notification_h noti_handle, - unsigned long* on_period, + notification_text_type_e text_type, long* number); + static common::PlatformResult GetLedColor(notification_h noti_handle, std::string* led_color); + static common::PlatformResult GetLedPeriod(notification_h noti_handle, unsigned long* on_period, unsigned long* off_period); - static common::PlatformResult GetSoundPath(notification_h noti_handle, - std::string* sound_path); + static common::PlatformResult GetSoundPath(notification_h noti_handle, std::string* sound_path); static common::PlatformResult SetSoundPath(notification_h noti_handle, const std::string& sound_path); - static common::PlatformResult GetVibration(notification_h noti_handle, - bool* vibration); - static common::PlatformResult GetApplicationControl( - app_control_h app_handle, - picojson::object* out_ptr); - static common::PlatformResult SetApplicationControl( - app_control_h app_handle, - const picojson::object& app_ctrl); - static common::PlatformResult GetApplicationId(app_control_h app_handle, - std::string* app_id); + static common::PlatformResult GetVibration(notification_h noti_handle, bool* vibration); + static common::PlatformResult GetApplicationControl(app_control_h app_handle, + picojson::object* out_ptr); + static common::PlatformResult SetApplicationControl(app_control_h app_handle, + const picojson::object& app_ctrl); + static common::PlatformResult GetApplicationId(app_control_h app_handle, std::string* app_id); static common::PlatformResult SetApplicationId(app_control_h app_handle, const std::string& app_id); - static common::PlatformResult GetProgressValue( - notification_h noti_handle, - const std::string& progess_type, - double* progress_value); - static common::PlatformResult SetProgressValue( - notification_h noti_handle, - const std::string& progress_type, - double progress_value, - bool is_update); - static common::PlatformResult GetPostedTime(notification_h noti_handle, - time_t* posted_time); - static common::PlatformResult SetLayout(notification_h noti_handle, - const std::string& noti_type); + static common::PlatformResult GetProgressValue(notification_h noti_handle, + const std::string& progess_type, + double* progress_value); + static common::PlatformResult SetProgressValue(notification_h noti_handle, + const std::string& progress_type, + double progress_value, bool is_update); + static common::PlatformResult GetPostedTime(notification_h noti_handle, time_t* posted_time); + static common::PlatformResult SetLayout(notification_h noti_handle, const std::string& noti_type); static common::PlatformResult CreateAppControl(app_control_h* app_control); static bool IsColorFormatNumeric(const std::string& color); @@ -128,18 +109,22 @@ class CommonNotification { static common::PlatformResult AddCommonMembersToJson(int id, notification_h noti_handle, picojson::object* out_ptr); static common::PlatformResult AddTypeToJson(notification_h noti_handle, const std::string& key, - picojson::object* out_ptr, std::string* noti_type_str); + picojson::object* out_ptr, + std::string* noti_type_str); static common::PlatformResult AddProgressTypeAndValueToJson(notification_h noti_handle, const std::string& noti_type_str, picojson::object* out_ptr); - static common::PlatformResult AddEventsNumberToJson(notification_h noti_handle, const std::string& key, + static common::PlatformResult AddEventsNumberToJson(notification_h noti_handle, + const std::string& key, picojson::object* out_ptr); static common::PlatformResult AddDetailInfosToJson(notification_h noti_handle, picojson::object* out_ptr); - static common::PlatformResult AddPathToJson(notification_h noti_handle, notification_image_type_e type, - const std::string& key, picojson::object* out_ptr); - static common::PlatformResult AddTextToJson(notification_h noti_handle, notification_text_type_e type, + static common::PlatformResult AddPathToJson(notification_h noti_handle, + notification_image_type_e type, const std::string& key, picojson::object* out_ptr); + static common::PlatformResult AddTextToJson(notification_h noti_handle, + notification_text_type_e type, const std::string& key, + picojson::object* out_ptr); static common::PlatformResult AddIconPathToJson(notification_h noti_handle, picojson::object* out_ptr); static common::PlatformResult AddSubIconPathToJson(notification_h noti_handle, @@ -157,26 +142,22 @@ class CommonNotification { static common::PlatformResult AddAppControlInfoToJson(notification_h noti_handle, app_control_h app_handle, picojson::object* out_ptr); - static common::PlatformResult AddPathsArrayToJson(notification_h noti_handle, - ImageEnumMap map, + static common::PlatformResult AddPathsArrayToJson(notification_h noti_handle, ImageEnumMap map, const std::string& key, picojson::object* out_ptr); static common::PlatformResult AddTextsArrayToJson(notification_h noti_handle, - InformationEnumMap map, - const std::string& key, + InformationEnumMap map, const std::string& key, picojson::object* out_ptr); // FromJson section static common::PlatformResult InitNotiFromJson(const picojson::object& args, - const std::string& type_key, - bool is_update, + const std::string& type_key, bool is_update, notification_h* noti_handle); static common::PlatformResult SetCommonMembersFromJson(const picojson::value& noti_val, notification_h noti_handle); static common::PlatformResult SetPathFromJson(const picojson::value& noti_value, notification_image_type_e type, - const std::string& key, - notification_h noti_handle); + const std::string& key, notification_h noti_handle); static common::PlatformResult SetLedColorFromJson(const picojson::value& noti_value, notification_h noti_handle); static common::PlatformResult SetLedOnPeriodFromJson(const picojson::value& noti_value, @@ -198,8 +179,7 @@ class CommonNotification { static common::PlatformResult SetSoundPathFromJson(const picojson::value& noti_value, notification_h noti_handle); static common::PlatformResult SetPathsArrayFromJson(const picojson::value& noti_value, - ImageEnumMap map, - const std::string& key, + ImageEnumMap map, const std::string& key, notification_h noti_handle); static common::PlatformResult SetTextsArrayFromJson(const picojson::value& noti_value, InformationEnumMap map, @@ -207,13 +187,12 @@ class CommonNotification { notification_h noti_handle); static common::PlatformResult SetTextFromJson(const picojson::value& noti_value, notification_text_type_e type, - const std::string& key, - notification_h noti_handle); + const std::string& key, notification_h noti_handle); - static common::PlatformResult PostNotification(const picojson::object& args, - bool is_update, + static common::PlatformResult PostNotification(const picojson::object& args, bool is_update, picojson::object* out_ptr, GetHandleFromJsonFun getHandle); + protected: CommonNotification(); virtual ~CommonNotification(); diff --git a/src/notification/notification_extension.cc b/src/notification/notification_extension.cc index f283928..2a9495c 100644 --- a/src/notification/notification_extension.cc +++ b/src/notification/notification_extension.cc @@ -20,7 +20,9 @@ // This will be generated from notification_api.js extern const char kSource_notification_api[]; -common::Extension* CreateExtension() { return new NotificationExtension; } +common::Extension* CreateExtension() { + return new NotificationExtension; +} NotificationExtension::NotificationExtension() { SetExtensionName("tizen.notification"); @@ -31,7 +33,8 @@ NotificationExtension::NotificationExtension() { SetExtraJSEntryPoints(entry_points); } -NotificationExtension::~NotificationExtension() {} +NotificationExtension::~NotificationExtension() { +} common::Instance* NotificationExtension::CreateInstance() { return new extension::notification::NotificationInstance; diff --git a/src/notification/notification_instance.cc b/src/notification/notification_instance.cc index 9c334d6..0c64b26 100644 --- a/src/notification/notification_instance.cc +++ b/src/notification/notification_instance.cc @@ -46,12 +46,11 @@ NotificationInstance::NotificationInstance() { REGISTER_SYNC("NotificationManager_getAll", NotificationManagerGetAll); REGISTER_SYNC("NotificationManager_post", NotificationManagerPost); REGISTER_SYNC("NotificationManager_removeAll", NotificationManagerRemoveAll); - REGISTER_SYNC("NotificationManager_playLEDCustomEffect", - NotificationManagerPlayLEDCustomEffect); - REGISTER_SYNC("NotificationManager_stopLEDCustomEffect", - NotificationManagerStopLEDCustomEffect); + REGISTER_SYNC("NotificationManager_playLEDCustomEffect", NotificationManagerPlayLEDCustomEffect); + REGISTER_SYNC("NotificationManager_stopLEDCustomEffect", NotificationManagerStopLEDCustomEffect); REGISTER_SYNC("NotificationManager_saveNotificationAsTemplate", NotificationManagerSaveTemplate); - REGISTER_SYNC("NotificationManager_createNotificationFromTemplate", NotificationManagerCreateFromTemplate); + REGISTER_SYNC("NotificationManager_createNotificationFromTemplate", + NotificationManagerCreateFromTemplate); #undef REGISTER_SYNC manager_ = NotificationManager::GetInstance(); @@ -61,10 +60,10 @@ NotificationInstance::~NotificationInstance() { LoggerD("Enter"); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) { \ +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ LogAndReportError(TypeMismatchException(name " is required argument"), out); \ - return; \ + return; \ } void NotificationInstance::NotificationManagerPost(const picojson::value& args, @@ -75,7 +74,7 @@ void NotificationInstance::NotificationManagerPost(const picojson::value& args, picojson::value val{picojson::object{}}; using namespace std::placeholders; - std::function impl {}; + std::function impl{}; if (args.contains("newImpl") && args.get("newImpl").get()) { LoggerD("New implementation"); impl = std::bind(&NotificationManager::PostUserNoti, manager_, _1, _2); @@ -93,14 +92,13 @@ void NotificationInstance::NotificationManagerPost(const picojson::value& args, } } -void NotificationInstance::NotificationManagerUpdate( - const picojson::value& args, - picojson::object& out) { +void NotificationInstance::NotificationManagerUpdate(const picojson::value& args, + picojson::object& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); LoggerD("Enter"); using namespace std::placeholders; - std::function impl {}; + std::function impl{}; if (args.contains("newImpl") && args.get("newImpl").get()) { LoggerD("New implementation"); impl = std::bind(&NotificationManager::UpdateUserNoti, manager_, _1); @@ -118,9 +116,8 @@ void NotificationInstance::NotificationManagerUpdate( } } -void NotificationInstance::NotificationManagerRemove( - const picojson::value& args, - picojson::object& out) { +void NotificationInstance::NotificationManagerRemove(const picojson::value& args, + picojson::object& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); LoggerD("Enter"); @@ -133,9 +130,8 @@ void NotificationInstance::NotificationManagerRemove( } } -void NotificationInstance::NotificationManagerRemoveAll( - const picojson::value& args, - picojson::object& out) { +void NotificationInstance::NotificationManagerRemoveAll(const picojson::value& args, + picojson::object& out) { CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); LoggerD("Enter"); @@ -153,9 +149,9 @@ void NotificationInstance::NotificationManagerGet(const picojson::value& args, LoggerD("Enter"); picojson::value val{picojson::object{}}; - PlatformResult status = manager_->Get( - args.get(), val.get(), - args.contains("newImpl") && args.get("newImpl").get()); + PlatformResult status = + manager_->Get(args.get(), val.get(), + args.contains("newImpl") && args.get("newImpl").get()); if (status.IsSuccess()) { ReportSuccess(val, out); @@ -164,15 +160,13 @@ void NotificationInstance::NotificationManagerGet(const picojson::value& args, } } -void NotificationInstance::NotificationManagerGetAll( - const picojson::value& args, - picojson::object& out) { +void NotificationInstance::NotificationManagerGetAll(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); picojson::value val{picojson::array{}}; PlatformResult status = manager_->GetAll( - val.get(), - args.contains("newImpl") && args.get("newImpl").get()); + val.get(), args.contains("newImpl") && args.get("newImpl").get()); if (status.IsSuccess()) { ReportSuccess(val, out); @@ -181,9 +175,8 @@ void NotificationInstance::NotificationManagerGetAll( } } -void NotificationInstance::NotificationManagerPlayLEDCustomEffect( - const picojson::value& args, picojson::object& out) { - +void NotificationInstance::NotificationManagerPlayLEDCustomEffect(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); @@ -196,9 +189,8 @@ void NotificationInstance::NotificationManagerPlayLEDCustomEffect( } } -void NotificationInstance::NotificationManagerStopLEDCustomEffect( - const picojson::value& /*args*/, picojson::object& out) { - +void NotificationInstance::NotificationManagerStopLEDCustomEffect(const picojson::value& /*args*/, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); @@ -225,7 +217,6 @@ void NotificationInstance::NotificationManagerSaveTemplate(const picojson::value } } - void NotificationInstance::NotificationManagerCreateFromTemplate(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); diff --git a/src/notification/notification_instance.h b/src/notification/notification_instance.h index 4eef4f8..fa0715f 100644 --- a/src/notification/notification_instance.h +++ b/src/notification/notification_instance.h @@ -31,27 +31,17 @@ class NotificationInstance : public common::ParsedInstance { private: NotificationManager* manager_; - void NotificationManagerPost(const picojson::value& args, - picojson::object& out); - void NotificationManagerUpdate(const picojson::value& args, - picojson::object& out); - void NotificationManagerRemove(const picojson::value& args, - picojson::object& out); - void NotificationManagerRemoveAll(const picojson::value& args, - picojson::object& out); - void NotificationManagerGet(const picojson::value& args, - picojson::object& out); - void NotificationManagerGetAll(const picojson::value& args, - picojson::object& out); - - void NotificationManagerPlayLEDCustomEffect(const picojson::value& args, - picojson::object& out); - void NotificationManagerStopLEDCustomEffect(const picojson::value& args, - picojson::object& out); - void NotificationManagerSaveTemplate(const picojson::value& args, - picojson::object& out); - void NotificationManagerCreateFromTemplate(const picojson::value& args, - picojson::object& out); + void NotificationManagerPost(const picojson::value& args, picojson::object& out); + void NotificationManagerUpdate(const picojson::value& args, picojson::object& out); + void NotificationManagerRemove(const picojson::value& args, picojson::object& out); + void NotificationManagerRemoveAll(const picojson::value& args, picojson::object& out); + void NotificationManagerGet(const picojson::value& args, picojson::object& out); + void NotificationManagerGetAll(const picojson::value& args, picojson::object& out); + + void NotificationManagerPlayLEDCustomEffect(const picojson::value& args, picojson::object& out); + void NotificationManagerStopLEDCustomEffect(const picojson::value& args, picojson::object& out); + void NotificationManagerSaveTemplate(const picojson::value& args, picojson::object& out); + void NotificationManagerCreateFromTemplate(const picojson::value& args, picojson::object& out); }; } // namespace notification diff --git a/src/notification/notification_manager.cc b/src/notification/notification_manager.cc index d457437..bc7b9e8 100644 --- a/src/notification/notification_manager.cc +++ b/src/notification/notification_manager.cc @@ -19,19 +19,19 @@ #include #include +#include #include #include #include #include -#include #include "common/converter.h" #include "common/logger.h" #include "common/scope_exit.h" +#include "notification/common_notification.h" #include "notification/status_notification.h" #include "notification/user_notification.h" -#include "notification/common_notification.h" namespace extension { namespace notification { @@ -52,14 +52,13 @@ NotificationManager* NotificationManager::GetInstance() { return &instance; } -PlatformResult NotificationManager::Post(const picojson::object& args, - picojson::object& out) { +PlatformResult NotificationManager::Post(const picojson::object& args, picojson::object& out) { LoggerD("Enter"); return StatusNotification::PostStatusNotification(args, false, &out); } PlatformResult NotificationManager::PostUserNoti(const picojson::object& args, - picojson::object& out) { + picojson::object& out) { LoggerD("Enter"); return UserNotification::PostUserNotification(args, false, &out); } @@ -74,16 +73,14 @@ PlatformResult NotificationManager::UpdateUserNoti(const picojson::object& args) return UserNotification::PostUserNotification(args, true, nullptr); } - PlatformResult NotificationManager::Remove(const picojson::object& args) { LoggerD("Enter"); int id = std::stoi(FromJson(args, "id")); int ret = notification_delete_by_priv_id(nullptr, NOTIFICATION_TYPE_NONE, id); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "Cannot remove notification error", - ("Cannot remove notification error: %d", ret)); + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Cannot remove notification error", + ("Cannot remove notification error: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -93,23 +90,21 @@ PlatformResult NotificationManager::RemoveAll() { LoggerD("Enter"); int ret = notification_delete_all(NOTIFICATION_TYPE_NOTI); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Notification noti remove all failed", - ("Notification remove all failed: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Notification noti remove all failed", + ("Notification remove all failed: %d", ret)); } ret = notification_delete_all(NOTIFICATION_TYPE_ONGOING); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Notification ongoing remove all failed", - ("Notification remove all failed: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Notification ongoing remove all failed", + ("Notification remove all failed: %d", ret)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NotificationManager::Get(const picojson::object& args, - picojson::object& out, bool is_new_impl) { +PlatformResult NotificationManager::Get(const picojson::object& args, picojson::object& out, + bool is_new_impl) { LoggerD("Enter"); int id; try { @@ -130,15 +125,13 @@ PlatformResult NotificationManager::Get(const picojson::object& args, }; PlatformResult status = StatusNotification::GetNotiHandle(id, ¬i_handle); - if (status.IsError()) - { + if (status.IsError()) { LoggerE("Failed: GetNotiHandle"); return status; } status = StatusNotification::GetAppControl(noti_handle, &app_control); - if (status.IsError()) - { + if (status.IsError()) { LoggerE("Failed: GetAppControl"); return status; } @@ -148,8 +141,7 @@ PlatformResult NotificationManager::Get(const picojson::object& args, } else { status = UserNotification::ToJson(id, noti_handle, app_control, &out); } - if (status.IsError()) - { + if (status.IsError()) { LoggerE("Failed: ToJson"); return status; } @@ -166,8 +158,7 @@ PlatformResult NotificationManager::GetAll(picojson::array& out, bool is_new_imp if (APP_ERROR_NONE == app_get_id(&package)) { LoggerD("Package id: %s", package); } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Could not get package id"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get package id"); } const std::string package_str = package; free(package); @@ -175,12 +166,13 @@ PlatformResult NotificationManager::GetAll(picojson::array& out, bool is_new_imp int ret = notification_get_detail_list(package_str.c_str(), NOTIFICATION_GROUP_ID_NONE, NOTIFICATION_PRIV_ID_NONE, -1, ¬i_list); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Get notification list error", - ("Get notification list error: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get notification list error", + ("Get notification list error: %d", ret)); } - SCOPE_EXIT { notification_free_list(noti_list); }; + SCOPE_EXIT { + notification_free_list(noti_list); + }; noti_list_iter = notification_list_get_head(noti_list); @@ -190,35 +182,29 @@ PlatformResult NotificationManager::GetAll(picojson::array& out, bool is_new_imp int noti_priv = -1; ret = notification_get_id(noti, nullptr, ¬i_priv); if (NOTIFICATION_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Cannot get notification id error", - ("Cannot get notification id, error: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot get notification id error", + ("Cannot get notification id, error: %d", ret)); } app_control_h app_control = nullptr; - PlatformResult status = - StatusNotification::GetAppControl(noti, &app_control); + PlatformResult status = StatusNotification::GetAppControl(noti, &app_control); SCOPE_EXIT { - if (app_control) { - app_control_destroy(app_control); - } + if (app_control) { + app_control_destroy(app_control); + } }; - if (status.IsError()) - return status; + if (status.IsError()) return status; picojson::object noti_item = picojson::object(); if (!is_new_impl) { - status = - StatusNotification::ToJson(noti_priv, noti, app_control, ¬i_item); + status = StatusNotification::ToJson(noti_priv, noti, app_control, ¬i_item); } else { - status = - UserNotification::ToJson(noti_priv, noti, app_control, ¬i_item); + status = UserNotification::ToJson(noti_priv, noti, app_control, ¬i_item); } - if (status.IsError()) - return status; + if (status.IsError()) return status; out.push_back(picojson::value(noti_item)); } @@ -229,8 +215,7 @@ PlatformResult NotificationManager::GetAll(picojson::array& out, bool is_new_imp return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult NotificationManager::PlayLEDCustomEffect( - const picojson::object& args) { +PlatformResult NotificationManager::PlayLEDCustomEffect(const picojson::object& args) { LoggerD("Enter"); int timeOn = FromJson(args, "timeOn"); @@ -251,7 +236,7 @@ PlatformResult NotificationManager::PlayLEDCustomEffect( ret = device_led_play_custom(timeOn, timeOff, color, platformFlags); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot play LED custom effect", - ("Cannot play LED custom effect: ",ret)); + ("Cannot play LED custom effect: ", ret)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -263,7 +248,7 @@ PlatformResult NotificationManager::StopLEDCustomEffect() { int ret = device_led_stop_custom(); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot stop LED custom effect", - ("Cannot stop LED custom effect: ",ret)); + ("Cannot stop LED custom effect: ", ret)); } return PlatformResult(ErrorCode::NO_ERROR); @@ -281,8 +266,7 @@ common::PlatformResult NotificationManager::SaveTemplate(const picojson::object& PlatformResult status = PlatformResult(ErrorCode::NO_ERROR); const auto& new_impl_it = args.find("newImpl"); const auto& noti_val_it = args.find("notification"); - if (args.end() != new_impl_it && args.end() != noti_val_it - && new_impl_it->second.get()) { + if (args.end() != new_impl_it && args.end() != noti_val_it && new_impl_it->second.get()) { status = UserNotification::GetNotiHandleFromJson(noti_val_it->second, false, ¬i_handle); } else { status = StatusNotification::GetNotiHandleFromJson(noti_val_it->second, false, ¬i_handle); @@ -300,8 +284,7 @@ common::PlatformResult NotificationManager::SaveTemplate(const picojson::object& "Maximum number of templates exceeded", ("Maximum number of templates exceeded, error: %d", ret)); } else { - return LogAndCreateResult(ErrorCode::ABORT_ERR, - "Saving template failed", + return LogAndCreateResult(ErrorCode::ABORT_ERR, "Saving template failed", ("Saving template failed, error: %d", ret)); } } @@ -309,7 +292,6 @@ common::PlatformResult NotificationManager::SaveTemplate(const picojson::object& return PlatformResult(ErrorCode::NO_ERROR); } - common::PlatformResult NotificationManager::CreateFromTemplate(const picojson::object& args, picojson::object& out) { LoggerD("Enter"); @@ -318,8 +300,7 @@ common::PlatformResult NotificationManager::CreateFromTemplate(const picojson::o notification_h noti_handle = nullptr; noti_handle = notification_create_from_template(name.c_str()); if (!noti_handle) { - return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, - "The template with given name not found", + return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "The template with given name not found", ("The template with given name not found, handle is nullptr")); } @@ -327,10 +308,9 @@ common::PlatformResult NotificationManager::CreateFromTemplate(const picojson::o notification_free(noti_handle); }; - //This method is designed to return only UserNotification objects + // This method is designed to return only UserNotification objects PlatformResult status = UserNotification::ToJson(0, noti_handle, nullptr, &out); - if (status.IsError()) - { + if (status.IsError()) { LoggerE("Failed: ToJson"); return status; } diff --git a/src/notification/notification_manager.h b/src/notification/notification_manager.h index 6ba779d..883ee57 100644 --- a/src/notification/notification_manager.h +++ b/src/notification/notification_manager.h @@ -29,16 +29,14 @@ class NotificationManager { public: static NotificationManager* GetInstance(); - common::PlatformResult Post(const picojson::object& args, - picojson::object& out); - common::PlatformResult PostUserNoti(const picojson::object& args, - picojson::object& out); + common::PlatformResult Post(const picojson::object& args, picojson::object& out); + common::PlatformResult PostUserNoti(const picojson::object& args, picojson::object& out); common::PlatformResult Update(const picojson::object& args); common::PlatformResult UpdateUserNoti(const picojson::object& args); common::PlatformResult Remove(const picojson::object& args); common::PlatformResult RemoveAll(); - common::PlatformResult Get(const picojson::object& args, - picojson::object& out, bool is_new_impl = false); + common::PlatformResult Get(const picojson::object& args, picojson::object& out, + bool is_new_impl = false); common::PlatformResult GetAll(picojson::array& out, bool is_new_impl = false); common::PlatformResult PlayLEDCustomEffect(const picojson::object& args); @@ -46,8 +44,7 @@ class NotificationManager { // TODO needed also below functions for new design? common::PlatformResult SaveTemplate(const picojson::object& args); - common::PlatformResult CreateFromTemplate(const picojson::object& args, - picojson::object& out); + common::PlatformResult CreateFromTemplate(const picojson::object& args, picojson::object& out); private: NotificationManager(); diff --git a/src/notification/status_notification.cc b/src/notification/status_notification.cc index 303c225..cf4eea1 100644 --- a/src/notification/status_notification.cc +++ b/src/notification/status_notification.cc @@ -17,9 +17,9 @@ #include "notification/status_notification.h" #include "common/converter.h" +#include "common/filesystem/filesystem_provider.h" #include "common/logger.h" #include "common/scope_exit.h" -#include "common/filesystem/filesystem_provider.h" namespace extension { namespace notification { @@ -32,10 +32,8 @@ StatusNotification::StatusNotification() { StatusNotification::~StatusNotification() { } -PlatformResult StatusNotification::ToJson(int id, - notification_h noti_handle, - app_control_h app_handle, - picojson::object* out_ptr) { +PlatformResult StatusNotification::ToJson(int id, notification_h noti_handle, + app_control_h app_handle, picojson::object* out_ptr) { LoggerD("Enter"); picojson::object& out = *out_ptr; @@ -47,13 +45,11 @@ PlatformResult StatusNotification::ToJson(int id, CHECK_ERROR(status); // iconPath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON, - "iconPath", out_ptr); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON, "iconPath", out_ptr); CHECK_ERROR(status); // subIconPath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, - "subIconPath", out_ptr); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, "subIconPath", out_ptr); CHECK_ERROR(status); // eventsNumber @@ -73,8 +69,8 @@ PlatformResult StatusNotification::ToJson(int id, CHECK_ERROR(status); // backgroundImagePath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_BACKGROUND, - "backgroundImagePath", out_ptr); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_BACKGROUND, "backgroundImagePath", + out_ptr); CHECK_ERROR(status); // thumbnails @@ -102,7 +98,7 @@ PlatformResult StatusNotification::ToJson(int id, PlatformResult StatusNotification::GetNotiHandleFromJson(const picojson::value& noti_val, bool is_update, - notification_h *noti_handle) { + notification_h* noti_handle) { LoggerD("Enter"); picojson::object noti_obj = noti_val.get(); @@ -110,8 +106,8 @@ PlatformResult StatusNotification::GetNotiHandleFromJson(const picojson::value& // statusType, id PlatformResult status = InitNotiFromJson(noti_obj, "statusType", is_update, &tmp_noti); CHECK_ERROR(status); - std::unique_ptr::type, int(*)(notification_h)> - tmp_noti_ptr(tmp_noti, ¬ification_free); // automatically release the memory + std::unique_ptr::type, int (*)(notification_h)> tmp_noti_ptr( + tmp_noti, ¬ification_free); // automatically release the memory // title, content status = SetCommonMembersFromJson(noti_val, tmp_noti); @@ -146,8 +142,8 @@ PlatformResult StatusNotification::GetNotiHandleFromJson(const picojson::value& CHECK_ERROR(status); // backgroundImagePath - status = SetPathFromJson(noti_val, NOTIFICATION_IMAGE_TYPE_BACKGROUND, - "backgroundImagePath", tmp_noti); + status = SetPathFromJson(noti_val, NOTIFICATION_IMAGE_TYPE_BACKGROUND, "backgroundImagePath", + tmp_noti); CHECK_ERROR(status); // thumbnails diff --git a/src/notification/status_notification.h b/src/notification/status_notification.h index 5e767e7..2c50675 100644 --- a/src/notification/status_notification.h +++ b/src/notification/status_notification.h @@ -17,8 +17,8 @@ #ifndef NOTIFICATION_STATUS_NOTIFICATION_H_ #define NOTIFICATION_STATUS_NOTIFICATION_H_ -#include #include +#include #include "common/picojson.h" #include "common/platform_result.h" @@ -32,16 +32,15 @@ namespace notification { class StatusNotification : public CommonNotification { public: - XW_EXPORT static common::PlatformResult ToJson(int id, - notification_h noti_handle, + XW_EXPORT static common::PlatformResult ToJson(int id, notification_h noti_handle, app_control_h app_handle, picojson::object* out_ptr); XW_EXPORT static common::PlatformResult GetNotiHandleFromJson(const picojson::value& noti_val, bool is_update, - notification_h *noti_handle); - static common::PlatformResult PostStatusNotification(const picojson::object& args, - bool is_update, + notification_h* noti_handle); + static common::PlatformResult PostStatusNotification(const picojson::object& args, bool is_update, picojson::object* out_ptr); + private: StatusNotification(); virtual ~StatusNotification(); diff --git a/src/notification/user_notification.cc b/src/notification/user_notification.cc index 1c498e1..1a73a2f 100644 --- a/src/notification/user_notification.cc +++ b/src/notification/user_notification.cc @@ -31,10 +31,8 @@ UserNotification::UserNotification() { UserNotification::~UserNotification() { } -PlatformResult UserNotification::ToJson(int id, - notification_h noti_handle, - app_control_h app_handle, - picojson::object* out_ptr) { +PlatformResult UserNotification::ToJson(int id, notification_h noti_handle, + app_control_h app_handle, picojson::object* out_ptr) { LoggerD("Enter"); PlatformResult ret = AddCommonMembersToJson(id, noti_handle, out_ptr); CHECK_ERROR(ret); @@ -66,15 +64,15 @@ PlatformResult UserNotification::ToJson(int id, PlatformResult UserNotification::GetNotiHandleFromJson(const picojson::value& noti_val, bool is_update, - notification_h *noti_handle) { + notification_h* noti_handle) { LoggerD("Enter"); picojson::object noti_obj = noti_val.get(); notification_h tmp_noti = nullptr; PlatformResult status = InitNotiFromJson(noti_obj, "userType", is_update, &tmp_noti); CHECK_ERROR(status); - std::unique_ptr::type, int(*)(notification_h)> - tmp_noti_ptr(tmp_noti, ¬ification_free); // automatically release the memory + std::unique_ptr::type, int (*)(notification_h)> tmp_noti_ptr( + tmp_noti, ¬ification_free); // automatically release the memory status = SetCommonMembersFromJson(noti_val, tmp_noti); CHECK_ERROR(status); @@ -102,8 +100,7 @@ PlatformResult UserNotification::GetNotiHandleFromJson(const picojson::value& no return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult UserNotification::PostUserNotification(const picojson::object& args, - bool is_update, +PlatformResult UserNotification::PostUserNotification(const picojson::object& args, bool is_update, picojson::object* out_ptr) { LoggerD("Enter"); return PostNotification(args, is_update, out_ptr, GetNotiHandleFromJson); @@ -118,8 +115,8 @@ PlatformResult UserNotification::AddTextContentsToJson(notification_h noti_handl picojson::object& text_contents_obj = text_contents.get(); // progressType, progressValue - PlatformResult status = AddProgressTypeAndValueToJson(noti_handle, noti_type_str, - &text_contents_obj); + PlatformResult status = + AddProgressTypeAndValueToJson(noti_handle, noti_type_str, &text_contents_obj); CHECK_ERROR(status); // eventsNumber @@ -151,13 +148,13 @@ PlatformResult UserNotification::AddImagesToJson(notification_h noti_handle, picojson::object& images_contents_obj = images_contents.get(); // iconPath - PlatformResult status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON, - "iconPath", &images_contents_obj); + PlatformResult status = + AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON, "iconPath", &images_contents_obj); CHECK_ERROR(status); // subIconPath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, - "subIconPath", &images_contents_obj); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, "subIconPath", + &images_contents_obj); CHECK_ERROR(status); // indicatorIconPath @@ -166,8 +163,8 @@ PlatformResult UserNotification::AddImagesToJson(notification_h noti_handle, CHECK_ERROR(status); // lockScreenIconPath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, - "lockScreenIconPath", &images_contents_obj); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, "lockScreenIconPath", + &images_contents_obj); CHECK_ERROR(status); // buttonIconPaths @@ -176,8 +173,8 @@ PlatformResult UserNotification::AddImagesToJson(notification_h noti_handle, CHECK_ERROR(status); // backgroundImagePath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_BACKGROUND, - "backgroundImagePath", &images_contents_obj); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_BACKGROUND, "backgroundImagePath", + &images_contents_obj); CHECK_ERROR(status); (*out_ptr)["images"] = images_contents; @@ -197,12 +194,13 @@ PlatformResult UserNotification::AddThumbnailsToJson(notification_h noti_handle, CHECK_ERROR(status); // thumbnailIconPath - status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_THUMBNAIL, - "thumbnailIconPath", &thumbnails_contents_obj); + status = AddPathToJson(noti_handle, NOTIFICATION_IMAGE_TYPE_THUMBNAIL, "thumbnailIconPath", + &thumbnails_contents_obj); CHECK_ERROR(status); // thumbnails - status = AddPathsArrayToJson(noti_handle, thumbnails_map_, "thumbnails", &thumbnails_contents_obj); + status = + AddPathsArrayToJson(noti_handle, thumbnails_map_, "thumbnails", &thumbnails_contents_obj); CHECK_ERROR(status); (*out_ptr)["thumbnails"] = thumbnails_contents; @@ -221,11 +219,11 @@ PlatformResult UserNotification::AddActionsToJson(notification_h noti_handle, PlatformResult status = AddSoundPathToJson(noti_handle, &actions_contents_obj); CHECK_ERROR(status); - //vibration + // vibration status = AddVibrationToJson(noti_handle, &actions_contents_obj); CHECK_ERROR(status); - //appControl, appId + // appControl, appId status = AddAppControlInfoToJson(noti_handle, app_handle, &actions_contents_obj); CHECK_ERROR(status); @@ -246,13 +244,14 @@ PlatformResult UserNotification::AddGroupContentsToJson(notification_h noti_hand CHECK_ERROR(status); // groupContent - status = AddTextToJson(noti_handle, NOTIFICATION_TEXT_TYPE_GROUP_CONTENT, - "groupContent", &group_contents_obj); + status = AddTextToJson(noti_handle, NOTIFICATION_TEXT_TYPE_GROUP_CONTENT, "groupContent", + &group_contents_obj); CHECK_ERROR(status); // groupContentForOff - status = AddTextToJson(noti_handle, NOTIFICATION_TEXT_TYPE_GROUP_CONTENT_FOR_DISPLAY_OPTION_IS_OFF, - "groupContentForOff", &group_contents_obj); + status = + AddTextToJson(noti_handle, NOTIFICATION_TEXT_TYPE_GROUP_CONTENT_FOR_DISPLAY_OPTION_IS_OFF, + "groupContentForOff", &group_contents_obj); CHECK_ERROR(status); (*out_ptr)["groupContents"] = group_contents; @@ -288,8 +287,8 @@ PlatformResult UserNotification::SetTextContentsFromJson(const picojson::value& const picojson::value& text_contents_value = noti_value.get("textContents"); // progressType, progressValue - PlatformResult status = SetProgressTypeAndValueFromJson(text_contents_value, is_update, - noti_handle); + PlatformResult status = + SetProgressTypeAndValueFromJson(text_contents_value, is_update, noti_handle); CHECK_ERROR(status); // eventsNumber @@ -301,8 +300,8 @@ PlatformResult UserNotification::SetTextContentsFromJson(const picojson::value& CHECK_ERROR(status); // buttonsTexts - status = SetTextsArrayFromJson(text_contents_value, buttons_texts_map_, - "buttonsTexts", noti_handle); + status = + SetTextsArrayFromJson(text_contents_value, buttons_texts_map_, "buttonsTexts", noti_handle); CHECK_ERROR(status); // contentForOff @@ -317,19 +316,18 @@ PlatformResult UserNotification::SetTextContentsFromJson(const picojson::value& PlatformResult UserNotification::SetImagesFromJson(const picojson::value& noti_value, notification_h noti_handle) { LoggerD("Enter"); - if (noti_value.contains("images") && - noti_value.get("images").is()) { + if (noti_value.contains("images") && noti_value.get("images").is()) { LoggerD("nullable member images is present - parsing it"); const picojson::value& images_value = noti_value.get("images"); // iconPath - PlatformResult status = SetPathFromJson(images_value, NOTIFICATION_IMAGE_TYPE_ICON, - "iconPath", noti_handle); + PlatformResult status = + SetPathFromJson(images_value, NOTIFICATION_IMAGE_TYPE_ICON, "iconPath", noti_handle); CHECK_ERROR(status); // subIconPath - status = SetPathFromJson(images_value, NOTIFICATION_IMAGE_TYPE_ICON_SUB, - "subIconPath", noti_handle); + status = + SetPathFromJson(images_value, NOTIFICATION_IMAGE_TYPE_ICON_SUB, "subIconPath", noti_handle); CHECK_ERROR(status); // indicatorIconPath @@ -343,8 +341,8 @@ PlatformResult UserNotification::SetImagesFromJson(const picojson::value& noti_v CHECK_ERROR(status); // buttonIconPaths - status = SetPathsArrayFromJson(images_value, buttons_icon_paths_map_, - "buttonIconPaths", noti_handle); + status = SetPathsArrayFromJson(images_value, buttons_icon_paths_map_, "buttonIconPaths", + noti_handle); CHECK_ERROR(status); // backgroundImagePath @@ -364,9 +362,9 @@ PlatformResult UserNotification::SetThumbnailsFromJson(const picojson::value& no const picojson::value& thumbnails_value = noti_value.get("thumbnails"); // lockScreenThumbnailIconPath - PlatformResult status = SetPathFromJson(thumbnails_value, - NOTIFICATION_IMAGE_TYPE_THUMBNAIL_FOR_LOCK, - "lockScreenThumbnailIconPath", noti_handle); + PlatformResult status = + SetPathFromJson(thumbnails_value, NOTIFICATION_IMAGE_TYPE_THUMBNAIL_FOR_LOCK, + "lockScreenThumbnailIconPath", noti_handle); CHECK_ERROR(status); // thumbnailIconPath @@ -414,8 +412,8 @@ PlatformResult UserNotification::SetGroupContentsFromJson(const picojson::value& const picojson::value& group_contents_value = noti_value.get("groupContents"); // groupTitle - PlatformResult status = SetTextFromJson(group_contents_value, NOTIFICATION_TEXT_TYPE_GROUP_TITLE, - "groupTitle", noti_handle); + PlatformResult status = SetTextFromJson( + group_contents_value, NOTIFICATION_TEXT_TYPE_GROUP_TITLE, "groupTitle", noti_handle); CHECK_ERROR(status); // groupContent diff --git a/src/notification/user_notification.h b/src/notification/user_notification.h index 3ed1dfd..86f1c9c 100644 --- a/src/notification/user_notification.h +++ b/src/notification/user_notification.h @@ -24,15 +24,13 @@ namespace notification { class UserNotification : public CommonNotification { public: - XW_EXPORT static common::PlatformResult ToJson(int id, - notification_h noti_handle, + XW_EXPORT static common::PlatformResult ToJson(int id, notification_h noti_handle, app_control_h app_handle, picojson::object* out_ptr); XW_EXPORT static common::PlatformResult GetNotiHandleFromJson(const picojson::value& noti_val, bool is_update, - notification_h *noti_handle); - static common::PlatformResult PostUserNotification(const picojson::object& args, - bool is_update, + notification_h* noti_handle); + static common::PlatformResult PostUserNotification(const picojson::object& args, bool is_update, picojson::object* out_ptr); static common::PlatformResult AddTextContentsToJson(notification_h noti_handle, @@ -51,8 +49,7 @@ class UserNotification : public CommonNotification { picojson::object* out_ptr); static common::PlatformResult SetTextContentsFromJson(const picojson::value& noti_val, - bool is_update, - notification_h noti_handle); + bool is_update, notification_h noti_handle); static common::PlatformResult SetImagesFromJson(const picojson::value& noti_val, notification_h noti_handle); static common::PlatformResult SetThumbnailsFromJson(const picojson::value& noti_val, @@ -63,6 +60,7 @@ class UserNotification : public CommonNotification { notification_h noti_handle); static common::PlatformResult SetLedsFromJson(const picojson::value& noti_val, notification_h noti_handle); + private: UserNotification(); virtual ~UserNotification(); diff --git a/src/package/package_extension.cc b/src/package/package_extension.cc index 578b404..ecdd434 100644 --- a/src/package/package_extension.cc +++ b/src/package/package_extension.cc @@ -16,8 +16,8 @@ #include "package/package_extension.h" -#include "package/package_instance.h" #include "common/logger.h" +#include "package/package_instance.h" // This will be generated from package_api.js extern const char kSource_package_api[]; diff --git a/src/package/package_info_provider.cc b/src/package/package_info_provider.cc index 5490631..f89fc09 100644 --- a/src/package/package_info_provider.cc +++ b/src/package/package_info_provider.cc @@ -16,13 +16,13 @@ #include "package/package_info_provider.h" +#include +#include +#include #include #include -#include #include -#include -#include -#include +#include #include @@ -41,31 +41,28 @@ using common::PlatformResult; using common::tools::ReportError; using common::tools::ReportSuccess; -#define REPORT_ERROR(out, exception) \ +#define REPORT_ERROR(out, exception) \ out["status"] = picojson::value("error"); \ out["error"] = exception.ToJSON(); -static int PackageInfoGetListCb( - const pkgmgrinfo_pkginfo_h info, void *user_data) { +static int PackageInfoGetListCb(const pkgmgrinfo_pkginfo_h info, void* user_data) { LoggerD("Enter"); picojson::array* array_data = static_cast(user_data); - if ( !array_data ) { + if (!array_data) { LoggerE("user_data is NULL"); return PMINFO_R_ERROR; } picojson::object object_info; - if ( PackageInfoProvider::ConvertToPackageToObject( - info, object_info) ) { + if (PackageInfoProvider::ConvertToPackageToObject(info, object_info)) { array_data->push_back(picojson::value(object_info)); } return PMINFO_R_OK; } -void PackageInfoProvider::GetPackagesInfo( - picojson::object& out) { +void PackageInfoProvider::GetPackagesInfo(picojson::object& out) { LoggerD("Enter"); clock_t start_time, end_time; @@ -73,8 +70,7 @@ void PackageInfoProvider::GetPackagesInfo( picojson::array array_data; - if ( pkgmgrinfo_pkginfo_get_usr_list(PackageInfoGetListCb, &array_data, getuid()) - != PMINFO_R_OK ) { + if (pkgmgrinfo_pkginfo_get_usr_list(PackageInfoGetListCb, &array_data, getuid()) != PMINFO_R_OK) { LoggerE("Failed to get package information"); REPORT_ERROR(out, UnknownException("Any other platform error occurs")); return; @@ -82,7 +78,7 @@ void PackageInfoProvider::GetPackagesInfo( end_time = clock(); LoggerD(">>>>>>>>>>>>>>> GetPackagesInfo Time : %f s\n", - (static_cast(end_time-start_time)) / CLOCKS_PER_SEC); + (static_cast(end_time - start_time)) / CLOCKS_PER_SEC); LoggerD("status: success"); out["status"] = picojson::value("success"); @@ -93,7 +89,7 @@ void PackageInfoProvider::GetPackageInfo(picojson::object& out) { LoggerD("Enter"); char* package_id = NULL; - if ( GetCurrentPackageId(&package_id) ) { + if (GetCurrentPackageId(&package_id)) { GetPackageInfo(package_id, out); free(package_id); } else { @@ -102,30 +98,27 @@ void PackageInfoProvider::GetPackageInfo(picojson::object& out) { } } -void PackageInfoProvider::GetPackageInfo( - const char* package_id, picojson::object& out) { +void PackageInfoProvider::GetPackageInfo(const char* package_id, picojson::object& out) { LoggerD("Enter"); - if ( strlen(package_id) <= 0 ) { + if (strlen(package_id) <= 0) { LoggerE("Wrong Package ID"); REPORT_ERROR(out, NotFoundException("The package with the specified ID is not found")); return; } pkgmgrinfo_pkginfo_h info; - if ( pkgmgrinfo_pkginfo_get_usr_pkginfo(package_id, getuid(), &info) - != PMINFO_R_OK ) { + if (pkgmgrinfo_pkginfo_get_usr_pkginfo(package_id, getuid(), &info) != PMINFO_R_OK) { LoggerE("Failed to get pkginfo"); REPORT_ERROR(out, NotFoundException("The package with the specified ID is not found")); return; } picojson::object object_info; - if ( !ConvertToPackageToObject(info, object_info) ) { + if (!ConvertToPackageToObject(info, object_info)) { LoggerE("Failed to convert pkginfo to object"); - REPORT_ERROR(out, UnknownException( - "The package information cannot be retrieved " \ - "because of a platform error")); + REPORT_ERROR(out, UnknownException("The package information cannot be retrieved " + "because of a platform error")); return; } @@ -134,15 +127,12 @@ void PackageInfoProvider::GetPackageInfo( out["result"] = picojson::value(object_info); } -static bool PackageAppInfoCb( - package_info_app_component_type_e comp_type, - const char *app_id, - void *user_data) { +static bool PackageAppInfoCb(package_info_app_component_type_e comp_type, const char* app_id, + void* user_data) { LoggerD("Enter"); - picojson::array* array_data = - static_cast(user_data); - if ( !array_data ) { + picojson::array* array_data = static_cast(user_data); + if (!array_data) { LoggerE("user_data is NULL"); return false; } @@ -151,13 +141,13 @@ static bool PackageAppInfoCb( return true; } -bool PackageInfoProvider:: ConvertToPackageToObject( - const pkgmgrinfo_pkginfo_h info, picojson::object& out) { +bool PackageInfoProvider::ConvertToPackageToObject(const pkgmgrinfo_pkginfo_h info, + picojson::object& out) { int ret = 0; char* id = NULL; ret = pkgmgrinfo_pkginfo_get_pkgid(info, &id); - if ( (ret != PMINFO_R_OK) || (id == NULL) ) { + if ((ret != PMINFO_R_OK) || (id == NULL)) { LoggerE("Failed to get package id: %d (%s)", ret, get_error_message(ret)); return false; } @@ -165,7 +155,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( char* name = NULL; ret = pkgmgrinfo_pkginfo_get_label(info, &name); - if ( (ret != PMINFO_R_OK) || (name == NULL) ) { + if ((ret != PMINFO_R_OK) || (name == NULL)) { LoggerE("[%s] Failed to get package name: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -173,7 +163,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( char* iconPath = NULL; ret = pkgmgrinfo_pkginfo_get_icon(info, &iconPath); - if ( (ret != PMINFO_R_OK) || (iconPath == NULL) ) { + if ((ret != PMINFO_R_OK) || (iconPath == NULL)) { LoggerE("[%s] Failed to get package iconPath: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -181,7 +171,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( char* version = NULL; ret = pkgmgrinfo_pkginfo_get_version(info, &version); - if ( (ret != PMINFO_R_OK) || (version == NULL) ) { + if ((ret != PMINFO_R_OK) || (version == NULL)) { LoggerE("[%s] Failed to get package version: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -189,7 +179,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( int lastModified = 0; ret = pkgmgrinfo_pkginfo_get_installed_time(info, &lastModified); - if ( (ret != PMINFO_R_OK) ) { + if ((ret != PMINFO_R_OK)) { LoggerE("[%s] Failed to get package lastModified: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -199,7 +189,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( char* author = NULL; ret = pkgmgrinfo_pkginfo_get_author_name(info, &author); - if ( (ret != PMINFO_R_OK) || (author == NULL) ) { + if ((ret != PMINFO_R_OK) || (author == NULL)) { LoggerE("[%s] Failed to get package author: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -207,7 +197,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( char* description = NULL; ret = pkgmgrinfo_pkginfo_get_description(info, &description); - if ( (ret != PMINFO_R_OK) || (description == NULL) ) { + if ((ret != PMINFO_R_OK) || (description == NULL)) { LoggerE("[%s] Failed to get package description: %d (%s)", id, ret, get_error_message(ret)); return false; } @@ -215,7 +205,7 @@ bool PackageInfoProvider:: ConvertToPackageToObject( package_info_h package_info; ret = package_info_create(id, &package_info); - if ( ret != PACKAGE_MANAGER_ERROR_NONE ) { + if (ret != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed to create package info: %d (%s)", ret, get_error_message(ret)); return false; } @@ -227,9 +217,9 @@ bool PackageInfoProvider:: ConvertToPackageToObject( }; picojson::array array_data; - ret = package_info_foreach_app_from_package(package_info, - PACKAGE_INFO_ALLAPP, PackageAppInfoCb, &array_data); - if ( ret != PACKAGE_MANAGER_ERROR_NONE ) { + ret = package_info_foreach_app_from_package(package_info, PACKAGE_INFO_ALLAPP, PackageAppInfoCb, + &array_data); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed to get app info: %d (%s)", ret, get_error_message(ret)); return false; } @@ -243,17 +233,13 @@ namespace { void GetSize(const std::string& id, int service_mode, picojson::object* out) { LoggerD("Enter"); pkgmgr_client* pc = pkgmgr_client_new(PC_REQUEST); - int size = pkgmgr_client_usr_request_service(PM_REQUEST_GET_SIZE, service_mode, - pc, - NULL, - id.c_str(), - getuid(), NULL, NULL, NULL); + int size = pkgmgr_client_usr_request_service(PM_REQUEST_GET_SIZE, service_mode, pc, NULL, + id.c_str(), getuid(), NULL, NULL, NULL); pkgmgr_client_free(pc); if (size < 0) { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get size"), - out, - ("Request service failed: %d (%s)", size, get_error_message(size))); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get size"), out, + ("Request service failed: %d (%s)", size, get_error_message(size))); } else { ReportSuccess(picojson::value(static_cast(size)), *out); } @@ -261,28 +247,25 @@ void GetSize(const std::string& id, int service_mode, picojson::object* out) { } // namespace -void PackageInfoProvider::GetTotalSize(const std::string& id, - picojson::object* out) { +void PackageInfoProvider::GetTotalSize(const std::string& id, picojson::object* out) { LoggerD("Enter"); GetSize(id, PM_GET_TOTAL_SIZE, out); } -void PackageInfoProvider::GetDataSize(const std::string& id, - picojson::object* out) { +void PackageInfoProvider::GetDataSize(const std::string& id, picojson::object* out) { LoggerD("Enter"); GetSize(id, PM_GET_DATA_SIZE, out); } -bool PackageInfoProvider::GetCurrentPackageId( - char** package_id) { +bool PackageInfoProvider::GetCurrentPackageId(char** package_id) { LoggerD("Enter"); int ret = 0; - char *app_id = NULL; + char* app_id = NULL; int pid = getpid(); ret = app_manager_get_app_id(pid, &app_id); - if ( ret != APP_MANAGER_ERROR_NONE ) { + if (ret != APP_MANAGER_ERROR_NONE) { LoggerE("Failed to get app id: %d (%s)", ret, get_error_message(ret)); return false; } @@ -290,14 +273,14 @@ bool PackageInfoProvider::GetCurrentPackageId( app_info_h handle; ret = app_info_create(app_id, &handle); free(app_id); - if ( ret != APP_MANAGER_ERROR_NONE ) { + if (ret != APP_MANAGER_ERROR_NONE) { LoggerE("Fail to get app info: %d (%s)", ret, get_error_message(ret)); return false; } ret = app_info_get_package(handle, package_id); app_info_destroy(handle); - if ( (ret != APP_MANAGER_ERROR_NONE) || (*package_id == NULL) ) { + if ((ret != APP_MANAGER_ERROR_NONE) || (*package_id == NULL)) { LoggerE("Fail to get pkg id: %d (%s)", ret, get_error_message(ret)); return false; } @@ -305,8 +288,6 @@ bool PackageInfoProvider::GetCurrentPackageId( return true; } - - #undef REPORT_ERROR } // namespace package diff --git a/src/package/package_info_provider.h b/src/package/package_info_provider.h index e08cfee..894b2b8 100644 --- a/src/package/package_info_provider.h +++ b/src/package/package_info_provider.h @@ -46,11 +46,9 @@ class PackageInfoProvider { * will be stored in out["error"]. */ static void GetPackageInfo(picojson::object& out); - static void GetPackageInfo(const char* package_id, - picojson::object& out); + static void GetPackageInfo(const char* package_id, picojson::object& out); - static bool ConvertToPackageToObject( - const pkgmgrinfo_pkginfo_h info, picojson::object& out); + static bool ConvertToPackageToObject(const pkgmgrinfo_pkginfo_h info, picojson::object& out); static void GetTotalSize(const std::string& id, picojson::object* out); static void GetDataSize(const std::string& id, picojson::object* out); diff --git a/src/package/package_instance.cc b/src/package/package_instance.cc index 3a24edb..4467ae6 100644 --- a/src/package/package_instance.cc +++ b/src/package/package_instance.cc @@ -19,11 +19,11 @@ #include #include -#include "package/package_info_provider.h" #include "common/logger.h" -#include "common/task-queue.h" #include "common/picojson.h" +#include "common/task-queue.h" #include "common/tools.h" +#include "package/package_info_provider.h" namespace extension { namespace package { @@ -51,9 +51,7 @@ typedef enum _PackageThreadWorkType { class PackageUserData { public: - PackageUserData(PackageInstance* ins, - int id, - PackageThreadWorkType task) { + PackageUserData(PackageInstance* ins, int id, PackageThreadWorkType task) { instance_ = ins; callback_id_ = id; work_ = task; @@ -66,46 +64,40 @@ class PackageUserData { }; typedef std::shared_ptr PackageUserDataPtr; -static void* PackageThreadWork( - const PackageUserDataPtr& userData) { +static void* PackageThreadWork(const PackageUserDataPtr& userData) { LoggerD("Enter"); - switch ( userData->work_ ) { + switch (userData->work_) { case PackageThreadWorkGetPackagesInfo: { picojson::object output; PackageInfoProvider::GetPackagesInfo(output); userData->data_ = output; break; } - default: { - LoggerE("Invalid Callback Type"); - } + default: { LoggerE("Invalid Callback Type"); } } return NULL; } -static gboolean PackageAfterWork( - const PackageUserDataPtr& userData) { +static gboolean PackageAfterWork(const PackageUserDataPtr& userData) { LoggerD("Enter"); - userData->data_["callbackId"] = - picojson::value(static_cast(userData->callback_id_)); + userData->data_["callbackId"] = picojson::value(static_cast(userData->callback_id_)); picojson::value result = picojson::value(userData->data_); common::Instance::PostMessage(userData->instance_, result.serialize().c_str()); return FALSE; } -static void PackageRequestCb( - int id, const char *type, const char *package, - package_manager_event_type_e event_type, - package_manager_event_state_e event_state, int progress, - package_manager_error_e error, void *user_data) { +static void PackageRequestCb(int id, const char* type, const char* package, + package_manager_event_type_e event_type, + package_manager_event_state_e event_state, int progress, + package_manager_error_e error, void* user_data) { LoggerD("Enter"); PackageInstance* instance = static_cast(user_data); - if ( !instance ) { + if (!instance) { LoggerE("instance is NULL"); return; } @@ -116,10 +108,11 @@ static void PackageRequestCb( LoggerE("[Failed]"); param["status"] = picojson::value("error"); param["error"] = UnknownException( - "It is not allowed to install the package by the platform or " \ - "any other platform error occurs").ToJSON(); + "It is not allowed to install the package by the platform or " + "any other platform error occurs") + .ToJSON(); } else if (PACKAGE_MANAGER_EVENT_STATE_STARTED == event_state || - PACKAGE_MANAGER_EVENT_STATE_PROCESSING == event_state) { + PACKAGE_MANAGER_EVENT_STATE_PROCESSING == event_state) { // this 'or' condition is needed to handle onprogress callback even on uninstall process, // with this additional check manual TCT uninstall/onprogress pass param["status"] = picojson::value("progress"); @@ -131,27 +124,26 @@ static void PackageRequestCb( } instance->InvokeCallback(id, param); - if ( event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED - || event_state == PACKAGE_MANAGER_EVENT_STATE_FAILED ) { + if (event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED || + event_state == PACKAGE_MANAGER_EVENT_STATE_FAILED) { LoggerD("Request has been completed"); instance->DeregisterCallback(id); } } -static void PackageListenerCb( - const char *type, const char *package, - package_manager_event_type_e event_type, - package_manager_event_state_e event_state, int progress, - package_manager_error_e error, void *user_data) { +static void PackageListenerCb(const char* type, const char* package, + package_manager_event_type_e event_type, + package_manager_event_state_e event_state, int progress, + package_manager_error_e error, void* user_data) { LoggerD("Enter"); PackageInstance* instance = static_cast(user_data); - if ( !instance ) { + if (!instance) { LoggerE("instance is NULL"); return; } - if ( error != PACKAGE_MANAGER_ERROR_NONE ) { + if (error != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed"); return; } @@ -159,24 +151,23 @@ static void PackageListenerCb( picojson::object param; param["listener"] = picojson::value("infoEvent"); - LoggerD("Listener type: %d , state: %d, progress: %d", - event_type, event_state, progress); - if ( event_type == PACKAGE_MANAGER_EVENT_TYPE_INSTALL - && event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED ) { + LoggerD("Listener type: %d , state: %d, progress: %d", event_type, event_state, progress); + if (event_type == PACKAGE_MANAGER_EVENT_TYPE_INSTALL && + event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED) { LoggerD("[Installed]"); param["status"] = picojson::value("installed"); picojson::object info; PackageInfoProvider::GetPackageInfo(package, info); param["info"] = picojson::value(info["result"]); instance->InvokeListener(param); - } else if ( event_type == PACKAGE_MANAGER_EVENT_TYPE_UNINSTALL - && event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED ) { + } else if (event_type == PACKAGE_MANAGER_EVENT_TYPE_UNINSTALL && + event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED) { LoggerD("[Uninstalled]"); param["status"] = picojson::value("uninstalled"); param["id"] = picojson::value(std::string(package)); instance->InvokeListener(param); - } else if ( event_type == PACKAGE_MANAGER_EVENT_TYPE_UPDATE - && event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED ) { + } else if (event_type == PACKAGE_MANAGER_EVENT_TYPE_UPDATE && + event_state == PACKAGE_MANAGER_EVENT_STATE_COMPLETED) { LoggerD("[Updated]"); param["status"] = picojson::value("updated"); picojson::object info; @@ -187,55 +178,55 @@ static void PackageListenerCb( } static std::string ltrim(const std::string& s) { - std::string str = s; - std::string::iterator i; - for (i = str.begin(); i != str.end(); ++i) { - if ( !isspace(*i) ) { - break; - } - } - if ( i == str.end() ) { - str.clear(); - } else { - str.erase(str.begin(), i); + std::string str = s; + std::string::iterator i; + for (i = str.begin(); i != str.end(); ++i) { + if (!isspace(*i)) { + break; } - return str; + } + if (i == str.end()) { + str.clear(); + } else { + str.erase(str.begin(), i); + } + return str; } static std::string convertUriToPath(const std::string& uri) { - std::string result; - std::string schema("file://"); - std::string str = ltrim(uri); + std::string result; + std::string schema("file://"); + std::string str = ltrim(uri); - std::string _schema = str.substr(0, schema.size()); - if ( _schema == schema ) { - result = str.substr(schema.size()); - } else { - result = str; - } + std::string _schema = str.substr(0, schema.size()); + if (_schema == schema) { + result = str.substr(schema.size()); + } else { + result = str; + } - return result; + return result; } PackageInstance::PackageInstance() { LoggerD("Enter"); int ret = package_manager_request_create(&request_); - if (ret != PACKAGE_MANAGER_ERROR_NONE ) { + if (ret != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed to created package manager request: %d (%s)", ret, get_error_message(ret)); request_ = NULL; } if (request_) { - ret = package_manager_request_set_event_cb(request_, PackageRequestCb, - static_cast(this)); - if (ret != PACKAGE_MANAGER_ERROR_NONE ) { + ret = + package_manager_request_set_event_cb(request_, PackageRequestCb, static_cast(this)); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed to set request event callback: %d (%s)", ret, get_error_message(ret)); } } ret = package_manager_create(&manager_); - if (ret != PACKAGE_MANAGER_ERROR_NONE ) { + if (ret != PACKAGE_MANAGER_ERROR_NONE) { LoggerE("Failed to created package manager: %d (%s)", ret, get_error_message(ret)); manager_ = NULL; } @@ -244,25 +235,18 @@ PackageInstance::PackageInstance() { using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&PackageInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&PackageInstance::x, this, _1, _2)); REGISTER_SYNC("PackageManager_setPackageInfoEventListener", - PackageManagerSetpackageinfoeventlistener); - REGISTER_SYNC("PackageManager_install", - PackageManagerInstall); - REGISTER_SYNC("PackageManager_getPackagesInfo", - PackageManagerGetpackagesinfo); - REGISTER_SYNC("PackageManager_uninstall", - PackageManagerUninstall); + PackageManagerSetpackageinfoeventlistener); + REGISTER_SYNC("PackageManager_install", PackageManagerInstall); + REGISTER_SYNC("PackageManager_getPackagesInfo", PackageManagerGetpackagesinfo); + REGISTER_SYNC("PackageManager_uninstall", PackageManagerUninstall); REGISTER_SYNC("PackageManager_unsetPackageInfoEventListener", - PackageManagerUnsetpackageinfoeventlistener); - REGISTER_SYNC("PackageManager_getPackageInfo", - PackageManagerGetpackageinfo); - REGISTER_SYNC("PackageManager_getTotalSize", - PackageManagerGetTotalSize); - REGISTER_SYNC("PackageManager_getDataSize", - PackageManagerGetDataSize); - #undef REGISTER_SYNC + PackageManagerUnsetpackageinfoeventlistener); + REGISTER_SYNC("PackageManager_getPackageInfo", PackageManagerGetpackageinfo); + REGISTER_SYNC("PackageManager_getTotalSize", PackageManagerGetTotalSize); + REGISTER_SYNC("PackageManager_getDataSize", PackageManagerGetDataSize); +#undef REGISTER_SYNC } PackageInstance::~PackageInstance() { @@ -272,14 +256,13 @@ PackageInstance::~PackageInstance() { package_manager_destroy(manager_); } -#define CHECK_EXIST(args, name, out) \ - if ( !args.contains(name) ) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } -void PackageInstance::RegisterCallback( - int request_id, int callback_id) { +void PackageInstance::RegisterCallback(int request_id, int callback_id) { LoggerD("Enter"); callbacks_map_[request_id] = callback_id; } @@ -289,20 +272,17 @@ void PackageInstance::DeregisterCallback(int request_id) { callbacks_map_.erase(request_id); } -void PackageInstance::InvokeCallback( - int request_id, picojson::object& param) { +void PackageInstance::InvokeCallback(int request_id, picojson::object& param) { LoggerD("Enter"); int callback_id = callbacks_map_[request_id]; - param["callbackId"] = picojson::value( - static_cast(callback_id)); + param["callbackId"] = picojson::value(static_cast(callback_id)); picojson::value result = picojson::value(param); Instance::PostMessage(this, result.serialize().c_str()); } -void PackageInstance::PackageManagerInstall( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerInstall(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInstall, &out); @@ -310,33 +290,30 @@ void PackageInstance::PackageManagerInstall( CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "packageFileURI", out) - int callback_id = static_cast( - args.get("callbackId").get()); + int callback_id = static_cast(args.get("callbackId").get()); const std::string& packageFileURI = convertUriToPath(args.get("packageFileURI").get()); - if ( !request_ ) { + if (!request_) { LoggerE("package_manager_request_h is NULL"); InvokeErrorCallbackAsync(callback_id, - UnknownException("It is not allowed to install the package by " \ - "the platform or any other platform error occurs")); + UnknownException("It is not allowed to install the package by " + "the platform or any other platform error occurs")); return; } int request_id = 0; - int ret = package_manager_request_install( - request_, packageFileURI.c_str(), &request_id); - if ( ret != PACKAGE_MANAGER_ERROR_NONE ) { - if ( ret == PACKAGE_MANAGER_ERROR_INVALID_PARAMETER ) { + int ret = package_manager_request_install(request_, packageFileURI.c_str(), &request_id); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (ret == PACKAGE_MANAGER_ERROR_INVALID_PARAMETER) { LoggerE("The package is not found at the specified location"); - InvokeErrorCallbackAsync(callback_id, - NotFoundException( - "The package is not found at the specified location")); + InvokeErrorCallbackAsync( + callback_id, NotFoundException("The package is not found at the specified location")); } else { LoggerE("Failed to install package: %d (%s)", ret, get_error_message(ret)); InvokeErrorCallbackAsync(callback_id, - UnknownException("It is not allowed to install the package by " \ - "the platform or any other platform error occurs")); + UnknownException("It is not allowed to install the package by " + "the platform or any other platform error occurs")); } } else { RegisterCallback(request_id, callback_id); @@ -345,8 +322,7 @@ void PackageInstance::PackageManagerInstall( ReportSuccess(out); } -void PackageInstance::PackageManagerUninstall( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerUninstall(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInstall, &out); @@ -354,40 +330,40 @@ void PackageInstance::PackageManagerUninstall( CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "id", out) - int callback_id = - static_cast(args.get("callbackId").get()); + int callback_id = static_cast(args.get("callbackId").get()); const std::string& id = args.get("id").get(); - if ( !request_ ) { + if (!request_) { LoggerE("package_manager_request_h is NULL"); InvokeErrorCallbackAsync(callback_id, - UnknownException("It is not allowed to install the package by " \ - "the platform or any other platform error occurs")); + UnknownException("It is not allowed to install the package by " + "the platform or any other platform error occurs")); return; } package_info_h pkg_info; int ret = package_manager_get_package_info(id.c_str(), &pkg_info); - if ( ret != PACKAGE_MANAGER_ERROR_NONE ) { - if ( ret == PACKAGE_MANAGER_ERROR_NO_SUCH_PACKAGE ) { - LoggerE("The package is not found at the specified location"); - InvokeErrorCallbackAsync(callback_id, - NotFoundException( - "The package is not found at the specified location")); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (ret == PACKAGE_MANAGER_ERROR_NO_SUCH_PACKAGE) { + LoggerE("The package is not found at the specified location"); + InvokeErrorCallbackAsync( + callback_id, NotFoundException("The package is not found at the specified location")); } else { - LoggerE("Failed to get package info: %d (%s)", ret, get_error_message(ret)); - InvokeErrorCallbackAsync(callback_id, UnknownException( - "It is not allowed to get package information by the platform or " \ - "any other platform error occurs")); + LoggerE("Failed to get package info: %d (%s)", ret, get_error_message(ret)); + InvokeErrorCallbackAsync( + callback_id, + UnknownException("It is not allowed to get package information by the platform or " + "any other platform error occurs")); } } else { int request_id = 0; int ret = package_manager_request_uninstall(request_, id.c_str(), &request_id); - if ( ret != PACKAGE_MANAGER_ERROR_NONE ) { - LoggerE("Failed to uninstall package: %d (%s)", ret, get_error_message(ret)); - InvokeErrorCallbackAsync(callback_id, UnknownException( - "It is not allowed to install the package by the platform or " \ - "any other platform error occurs")); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Failed to uninstall package: %d (%s)", ret, get_error_message(ret)); + InvokeErrorCallbackAsync( + callback_id, + UnknownException("It is not allowed to install the package by the platform or " + "any other platform error occurs")); } else { RegisterCallback(request_id, callback_id); } @@ -395,29 +371,27 @@ void PackageInstance::PackageManagerUninstall( ReportSuccess(out); } -void PackageInstance::PackageManagerGetpackagesinfo( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerGetpackagesinfo(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); CHECK_EXIST(args, "callbackId", out) - int callback_id = - static_cast(args.get("callbackId").get()); + int callback_id = static_cast(args.get("callbackId").get()); - PackageUserDataPtr userData(new PackageUserData( - this, callback_id, PackageThreadWorkGetPackagesInfo)); - TaskQueue::GetInstance().Queue( - PackageThreadWork, PackageAfterWork, userData); + PackageUserDataPtr userData( + new PackageUserData(this, callback_id, PackageThreadWorkGetPackagesInfo)); + TaskQueue::GetInstance().Queue(PackageThreadWork, PackageAfterWork, userData); ReportSuccess(out); } -void PackageInstance::PackageManagerGetpackageinfo( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerGetpackageinfo(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); - if ( args.contains("id") ) { + if (args.contains("id")) { std::string id = args.get("id").get(); PackageInfoProvider::GetPackageInfo(id.c_str(), out); } else { @@ -434,8 +408,7 @@ void PackageInstance::PackageManagerGetTotalSize(const picojson::value& args, if (id.is()) { PackageInfoProvider::GetTotalSize(id.get(), &out); } else { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Missing id parameter"), - &out); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Missing id parameter"), &out); } } @@ -448,8 +421,7 @@ void PackageInstance::PackageManagerGetDataSize(const picojson::value& args, if (id.is()) { PackageInfoProvider::GetDataSize(id.get(), &out); } else { - LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Missing id parameter"), - &out); + LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Missing id parameter"), &out); } } @@ -459,38 +431,32 @@ void PackageInstance::InvokeListener(picojson::object& param) { Instance::PostMessage(this, result.serialize().c_str()); } -void PackageInstance:: - PackageManagerSetpackageinfoeventlistener( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerSetpackageinfoeventlistener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); CHECK_EXIST(args, "callbackId", out) - if ( is_package_info_listener_set_ ) { + if (is_package_info_listener_set_) { LoggerD("Already set"); ReportSuccess(out); return; } - if ( !manager_ ) { - LogAndReportError( - UnknownException("The package list change event cannot be " \ - "generated because of a platform error"), - out, - ("package_manager_h is NULL")); + if (!manager_) { + LogAndReportError(UnknownException("The package list change event cannot be " + "generated because of a platform error"), + out, ("package_manager_h is NULL")); return; } - int ret = package_manager_set_event_cb( - manager_, PackageListenerCb, static_cast(this)); - if (ret != PACKAGE_MANAGER_ERROR_NONE ) { - LogAndReportError( - UnknownException("The package list change event cannot be " \ - "generated because of a platform error"), - out, - ("Failed to set event callback: %d (%s)", ret, get_error_message(ret))); + int ret = package_manager_set_event_cb(manager_, PackageListenerCb, static_cast(this)); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LogAndReportError(UnknownException("The package list change event cannot be " + "generated because of a platform error"), + out, ("Failed to set event callback: %d (%s)", ret, get_error_message(ret))); return; } @@ -498,35 +464,31 @@ void PackageInstance:: ReportSuccess(out); } -void PackageInstance:: - PackageManagerUnsetpackageinfoeventlistener( - const picojson::value& args, picojson::object& out) { +void PackageInstance::PackageManagerUnsetpackageinfoeventlistener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); - if ( !is_package_info_listener_set_ ) { + if (!is_package_info_listener_set_) { LoggerD("Listener is not set"); ReportSuccess(out); return; } - if ( !manager_ ) { - LogAndReportError( - UnknownException("The listener removal request fails" \ - "because of a platform error"), - out, - ("package_manager_h is NULL")); + if (!manager_) { + LogAndReportError(UnknownException("The listener removal request fails" + "because of a platform error"), + out, ("package_manager_h is NULL")); return; } int ret = package_manager_unset_event_cb(manager_); - if (ret != PACKAGE_MANAGER_ERROR_NONE ) { - LogAndReportError( - UnknownException("The listener removal request fails" \ - "because of a platform error"), - out, - ("Failed to unset event callback: %d (%s)", ret, get_error_message(ret))); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LogAndReportError(UnknownException("The listener removal request fails" + "because of a platform error"), + out, + ("Failed to unset event callback: %d (%s)", ret, get_error_message(ret))); return; } @@ -534,17 +496,14 @@ void PackageInstance:: ReportSuccess(out); } -void PackageInstance::InvokeErrorCallbackAsync( - int callback_id, const PlatformException& ex) { +void PackageInstance::InvokeErrorCallbackAsync(int callback_id, const PlatformException& ex) { LoggerD("Enter"); picojson::object param; LogAndReportError(ex, param); - PackageUserDataPtr userData(new PackageUserData( - this, callback_id, PackageThreadWorkNone)); + PackageUserDataPtr userData(new PackageUserData(this, callback_id, PackageThreadWorkNone)); userData->data_ = param; - TaskQueue::GetInstance().Async - (PackageAfterWork, userData); + TaskQueue::GetInstance().Async(PackageAfterWork, userData); } #undef CHECK_EXIST diff --git a/src/package/package_instance.h b/src/package/package_instance.h index 2d22d81..3ae7163 100644 --- a/src/package/package_instance.h +++ b/src/package/package_instance.h @@ -43,25 +43,18 @@ class PackageInstance : public common::ParsedInstance { std::map callbacks_map_; // void RegisterCallback(int request_id, int callback_id); - void InvokeErrorCallbackAsync - (int callback_id, const common::PlatformException& ex); - - void PackageManagerInstall - (const picojson::value& args, picojson::object& out); - void PackageManagerUninstall( - const picojson::value& args, picojson::object& out); - void PackageManagerGetpackagesinfo - (const picojson::value& args, picojson::object& out); - void PackageManagerGetpackageinfo - (const picojson::value& args, picojson::object& out); - void PackageManagerGetTotalSize(const picojson::value& args, - picojson::object& out); - void PackageManagerGetDataSize(const picojson::value& args, - picojson::object& out); - void PackageManagerSetpackageinfoeventlistener - (const picojson::value& args, picojson::object& out); - void PackageManagerUnsetpackageinfoeventlistener - (const picojson::value& args, picojson::object& out); + void InvokeErrorCallbackAsync(int callback_id, const common::PlatformException& ex); + + void PackageManagerInstall(const picojson::value& args, picojson::object& out); + void PackageManagerUninstall(const picojson::value& args, picojson::object& out); + void PackageManagerGetpackagesinfo(const picojson::value& args, picojson::object& out); + void PackageManagerGetpackageinfo(const picojson::value& args, picojson::object& out); + void PackageManagerGetTotalSize(const picojson::value& args, picojson::object& out); + void PackageManagerGetDataSize(const picojson::value& args, picojson::object& out); + void PackageManagerSetpackageinfoeventlistener(const picojson::value& args, + picojson::object& out); + void PackageManagerUnsetpackageinfoeventlistener(const picojson::value& args, + picojson::object& out); }; } // namespace package diff --git a/src/playerutil/playerutil_extension.cc b/src/playerutil/playerutil_extension.cc index a358fa4..f8af4d4 100644 --- a/src/playerutil/playerutil_extension.cc +++ b/src/playerutil/playerutil_extension.cc @@ -28,9 +28,7 @@ PlayerUtilExtension::PlayerUtilExtension() { SetExtensionName("tizen.playerutil"); SetJavaScriptAPI(kSource_playerutil_api); - const char* entry_points[] = { - nullptr - }; + const char* entry_points[] = {nullptr}; SetExtraJSEntryPoints(entry_points); } diff --git a/src/playerutil/playerutil_extension.h b/src/playerutil/playerutil_extension.h index 3733611..5d07d01 100644 --- a/src/playerutil/playerutil_extension.h +++ b/src/playerutil/playerutil_extension.h @@ -35,4 +35,3 @@ class PlayerUtilExtension : public common::Extension { } // namespace extension #endif // PLAYERUTIL_EXTENSION_H_ - diff --git a/src/playerutil/playerutil_instance.cc b/src/playerutil/playerutil_instance.cc index d295a8c..65ffe8d 100644 --- a/src/playerutil/playerutil_instance.cc +++ b/src/playerutil/playerutil_instance.cc @@ -16,8 +16,8 @@ #include "playerutil/playerutil_instance.h" -#include #include +#include #include "common/logger.h" #include "common/scope_exit.h" @@ -34,13 +34,11 @@ PlayerUtilInstance::PlayerUtilInstance() { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&PlayerUtilInstance::x, this, _1)) +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&PlayerUtilInstance::x, this, _1)) REGISTER_SYNC("PlayerUtil_getLatencyMode", GetLatencyMode); REGISTER_SYNC("PlayerUtil_setLatencyMode", SetLatencyMode); #undef REGISTER_SYNC - } PlayerUtilInstance::~PlayerUtilInstance() { @@ -50,7 +48,7 @@ PlayerUtilInstance::~PlayerUtilInstance() { common::TizenResult PlayerUtilInstance::GetLatencyMode(const picojson::object& args) { ScopeLogger(); - Ewk_Context *context = ewk_context_default_get(); + Ewk_Context* context = ewk_context_default_get(); Ewk_Audio_Latency_Mode latency_mode = ewk_context_audio_latency_mode_get(context); @@ -67,8 +65,9 @@ common::TizenResult PlayerUtilInstance::SetLatencyMode(const picojson::object& a CHECK_EXIST(args, kLatencyMode); auto latency_it = args.find(kLatencyMode)->second; if (latency_it.is()) { - Ewk_Audio_Latency_Mode latency_mode = PlayerUtilUtils::ToLatencyMode(latency_it.get()); - Ewk_Context *context = ewk_context_default_get(); + Ewk_Audio_Latency_Mode latency_mode = + PlayerUtilUtils::ToLatencyMode(latency_it.get()); + Ewk_Context* context = ewk_context_default_get(); auto ret = ewk_context_audio_latency_mode_set(context, latency_mode); if (EINA_TRUE != ret) { diff --git a/src/playerutil/playerutil_instance.h b/src/playerutil/playerutil_instance.h index ebdbef3..a8eba46 100644 --- a/src/playerutil/playerutil_instance.h +++ b/src/playerutil/playerutil_instance.h @@ -19,7 +19,6 @@ #include "common/tizen_instance.h" - namespace extension { namespace playerutil { @@ -27,6 +26,7 @@ class PlayerUtilInstance : public common::TizenInstance { public: PlayerUtilInstance(); virtual ~PlayerUtilInstance(); + private: common::TizenResult GetLatencyMode(const picojson::object& args); common::TizenResult SetLatencyMode(const picojson::object& args); diff --git a/src/playerutil/playerutil_utils.cc b/src/playerutil/playerutil_utils.cc index 7861efd..dd6739c 100644 --- a/src/playerutil/playerutil_utils.cc +++ b/src/playerutil/playerutil_utils.cc @@ -22,35 +22,36 @@ namespace extension { namespace playerutil { namespace { -#define PLAYER_UTIL_LATENCY_MODE_E \ +#define PLAYER_UTIL_LATENCY_MODE_E \ X(EWK_AUDIO_LATENCY_MODE_HIGH, "HIGH") \ - X(EWK_AUDIO_LATENCY_MODE_MID, "MID") \ - X(EWK_AUDIO_LATENCY_MODE_LOW, "LOW") \ + X(EWK_AUDIO_LATENCY_MODE_MID, "MID") \ + X(EWK_AUDIO_LATENCY_MODE_LOW, "LOW") \ XD(EWK_AUDIO_LATENCY_MODE_LOW, "unknown") } // namespace const std::string kLatencyMode = "latencyMode"; -#define X(v, s) case v: return s; -#define XD(v, s) \ - default: \ +#define X(v, s) \ + case v: \ + return s; +#define XD(v, s) \ + default: \ LoggerE("Unknown value: %d, returning default: %s", e, s); \ return s; std::string PlayerUtilUtils::FromLatencyMode(Ewk_Audio_Latency_Mode e) { ScopeLogger(); - switch (e) { - PLAYER_UTIL_LATENCY_MODE_E - } + switch (e) { PLAYER_UTIL_LATENCY_MODE_E } } #undef X #undef XD -#define X(v, s) if (e == s) return v; -#define XD(v, s) \ +#define X(v, s) \ + if (e == s) return v; +#define XD(v, s) \ LoggerE("Unknown value: %s, returning default: %d", e.c_str(), v); \ return v; @@ -62,5 +63,5 @@ Ewk_Audio_Latency_Mode PlayerUtilUtils::ToLatencyMode(const std::string& e) { #undef X #undef XD -} // namespace playerutil -} // namespace extension +} // namespace playerutil +} // namespace extension diff --git a/src/playerutil/playerutil_utils.h b/src/playerutil/playerutil_utils.h index 50c13d1..612a1d3 100644 --- a/src/playerutil/playerutil_utils.h +++ b/src/playerutil/playerutil_utils.h @@ -28,8 +28,8 @@ namespace extension { namespace playerutil { -#define CHECK_EXIST(args, name) \ - if (args.end() == args.find(name)) { \ +#define CHECK_EXIST(args, name) \ + if (args.end() == args.find(name)) { \ return common::TypeMismatchError(std::string(name) + " is required argument"); \ } @@ -41,7 +41,7 @@ class PlayerUtilUtils { static Ewk_Audio_Latency_Mode ToLatencyMode(const std::string& e); }; -} // namespace playerutil -} // namespace extension +} // namespace playerutil +} // namespace extension -#endif // WEBAPI_PLUGINS_PLAYER_UTIL_UTILS_H__ +#endif // WEBAPI_PLUGINS_PLAYER_UTIL_UTILS_H__ diff --git a/src/power/power_extension.cc b/src/power/power_extension.cc old mode 100755 new mode 100644 index e497351..6f7d3af --- a/src/power/power_extension.cc +++ b/src/power/power_extension.cc @@ -30,7 +30,8 @@ PowerExtension::PowerExtension() { SetJavaScriptAPI(kSource_power_api); } -PowerExtension::~PowerExtension() {} +PowerExtension::~PowerExtension() { +} common::Instance* PowerExtension::CreateInstance() { return new extension::power::PowerInstance; diff --git a/src/power/power_extension.h b/src/power/power_extension.h old mode 100755 new mode 100644 index 4a4d965..e672d60 --- a/src/power/power_extension.h +++ b/src/power/power_extension.h @@ -28,5 +28,4 @@ class PowerExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // POWER_POWER_EXTENSION_H_ - +#endif // POWER_POWER_EXTENSION_H_ diff --git a/src/power/power_instance.cc b/src/power/power_instance.cc old mode 100755 new mode 100644 index 746f21e..8027ba1 --- a/src/power/power_instance.cc +++ b/src/power/power_instance.cc @@ -18,12 +18,12 @@ #include +#include #include #include -#include -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" #include "common/tools.h" @@ -36,19 +36,16 @@ namespace { // The privileges that required in Power API const std::string kPrivilegePower = "http://tizen.org/privilege/power"; -const std::map kPowerResourceMap = { - {"SCREEN", POWER_RESOURCE_SCREEN}, - {"CPU", POWER_RESOURCE_CPU} -}; +const std::map kPowerResourceMap = {{"SCREEN", POWER_RESOURCE_SCREEN}, + {"CPU", POWER_RESOURCE_CPU}}; const std::map kPowerStateMap = { {"SCREEN_OFF", POWER_STATE_SCREEN_OFF}, {"SCREEN_DIM", POWER_STATE_SCREEN_DIM}, {"SCREEN_NORMAL", POWER_STATE_SCREEN_NORMAL}, {"SCREEN_BRIGHT", POWER_STATE_SCREEN_BRIGHT}, - {"CPU_AWAKE", POWER_STATE_CPU_AWAKE} -}; -} // namespace + {"CPU_AWAKE", POWER_STATE_CPU_AWAKE}}; +} // namespace using namespace common; using namespace extension::power; @@ -58,8 +55,7 @@ PowerInstance::PowerInstance() { using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&PowerInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&PowerInstance::x, this, _1, _2)); REGISTER_SYNC("PowerManager_turnScreenOff", PowerManagerTurnscreenoff); REGISTER_SYNC("PowerManager_restoreScreenBrightness", PowerManagerRestorescreenbrightness); REGISTER_SYNC("PowerManager_request", PowerManagerRequest); @@ -68,7 +64,7 @@ PowerInstance::PowerInstance() { REGISTER_SYNC("PowerManager_isScreenOn", PowerManagerIsscreenon); REGISTER_SYNC("PowerManager_turnScreenOn", PowerManagerTurnscreenon); REGISTER_SYNC("PowerManager_setScreenBrightness", PowerManagerSetscreenbrightness); - #undef REGISTER_SYNC +#undef REGISTER_SYNC PowerManager::GetInstance()->AddListener(this); } @@ -96,11 +92,11 @@ enum PowerCallbacks { PowerManagerSetscreenstatechangelistenerCallback }; -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } void PowerInstance::PowerManagerRequest(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); @@ -109,9 +105,8 @@ void PowerInstance::PowerManagerRequest(const picojson::value& args, picojson::o const std::string& resource = args.get("resource").get(); const std::string& state = args.get("state").get(); - PlatformResult result = - PowerManager::GetInstance()->Request(kPowerResourceMap.at(resource), - kPowerStateMap.at(state)); + PlatformResult result = PowerManager::GetInstance()->Request(kPowerResourceMap.at(resource), + kPowerStateMap.at(state)); if (result.IsError()) LogAndReportError(result, &out); else @@ -121,8 +116,7 @@ void PowerInstance::PowerManagerRequest(const picojson::value& args, picojson::o void PowerInstance::PowerManagerRelease(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const std::string& resource = args.get("resource").get(); - PlatformResult result = - PowerManager::GetInstance()->Release(kPowerResourceMap.at(resource)); + PlatformResult result = PowerManager::GetInstance()->Release(kPowerResourceMap.at(resource)); if (result.IsError()) LogAndReportError(result, &out); else @@ -133,8 +127,7 @@ void PowerInstance::PowerManagerGetscreenbrightness(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); double brightness; - PlatformResult result = - PowerManager::GetInstance()->GetScreenBrightness(&brightness); + PlatformResult result = PowerManager::GetInstance()->GetScreenBrightness(&brightness); if (result.IsError()) LogAndReportError(result, &out); else @@ -149,8 +142,7 @@ void PowerInstance::PowerManagerSetscreenbrightness(const picojson::value& args, CHECK_EXIST(args, "brightness", out) double brightness = args.get("brightness").get(); - PlatformResult result = - PowerManager::GetInstance()->SetScreenBrightness(brightness); + PlatformResult result = PowerManager::GetInstance()->SetScreenBrightness(brightness); if (result.IsError()) LogAndReportError(result, &out); else @@ -167,10 +159,10 @@ void PowerInstance::PowerManagerIsscreenon(const picojson::value& args, picojson ReportSuccess(picojson::value(state), out); } -void PowerInstance::PowerManagerRestorescreenbrightness(const picojson::value& args, picojson::object& out) { +void PowerInstance::PowerManagerRestorescreenbrightness(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); - PlatformResult result = - PowerManager::GetInstance()->RestoreScreenBrightness(); + PlatformResult result = PowerManager::GetInstance()->RestoreScreenBrightness(); if (result.IsError()) LogAndReportError(result, &out); else @@ -179,7 +171,9 @@ void PowerInstance::PowerManagerRestorescreenbrightness(const picojson::value& a void PowerInstance::PowerManagerTurnscreenon(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); - LoggerW("DEPRECATION WARNING: turnScreenOn() is deprecated and will be removed from next release. Use request() instead."); + LoggerW( + "DEPRECATION WARNING: turnScreenOn() is deprecated and will be removed from next release. " + "Use request() instead."); CHECK_PRIVILEGE_ACCESS(kPrivilegePower, &out); @@ -192,7 +186,9 @@ void PowerInstance::PowerManagerTurnscreenon(const picojson::value& args, picojs void PowerInstance::PowerManagerTurnscreenoff(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); - LoggerW("DEPRECATION WARNING: turnScreenOff() is deprecated and will be removed from next release. Use release() instead."); + LoggerW( + "DEPRECATION WARNING: turnScreenOff() is deprecated and will be removed from next release. " + "Use release() instead."); CHECK_PRIVILEGE_ACCESS(kPrivilegePower, &out); @@ -222,5 +218,5 @@ void PowerInstance::OnScreenStateChanged(PowerState prev_state, PowerState new_s } #undef CHECK_EXIST -} // namespace power -} // namespace extension +} // namespace power +} // namespace extension diff --git a/src/power/power_instance.h b/src/power/power_instance.h old mode 100755 new mode 100644 index d156825..33d8efe --- a/src/power/power_instance.h +++ b/src/power/power_instance.h @@ -24,9 +24,7 @@ namespace extension { namespace power { -class PowerInstance - : public common::ParsedInstance, - public PowerManagerListener { +class PowerInstance : public common::ParsedInstance, public PowerManagerListener { public: PowerInstance(); virtual ~PowerInstance(); @@ -46,7 +44,7 @@ class PowerInstance void OnScreenStateChanged(PowerState prev_state, PowerState new_state); }; -} // namespace power -} // namespace extension +} // namespace power +} // namespace extension -#endif // POWER_POWER_INSTANCE_H_ +#endif // POWER_POWER_INSTANCE_H_ diff --git a/src/power/power_manager.cc b/src/power/power_manager.cc index 4bde5f6..946b600 100644 --- a/src/power/power_manager.cc +++ b/src/power/power_manager.cc @@ -18,13 +18,13 @@ #include -#include #include +#include -#include +#include #include #include -#include +#include #include "common/logger.h" #include "power_platform_proxy.h" @@ -42,22 +42,20 @@ PowerManager::PowerManager() should_be_read_from_cache_(false), set_custom_brightness_(false), current_requested_state_(POWER_STATE_NONE) { - LoggerD("Enter"); display_state_e platform_state = DISPLAY_STATE_NORMAL; int ret = device_display_get_state(&platform_state); - if (DEVICE_ERROR_NONE != ret) - LoggerE("device_display_get_state failed (%d)", ret); + if (DEVICE_ERROR_NONE != ret) LoggerE("device_display_get_state failed (%d)", ret); switch (platform_state) { - case DISPLAY_STATE_NORMAL : + case DISPLAY_STATE_NORMAL: current_state_ = POWER_STATE_SCREEN_NORMAL; break; - case DISPLAY_STATE_SCREEN_DIM : + case DISPLAY_STATE_SCREEN_DIM: current_state_ = POWER_STATE_SCREEN_DIM; break; - case DISPLAY_STATE_SCREEN_OFF : + case DISPLAY_STATE_SCREEN_OFF: current_state_ = POWER_STATE_SCREEN_OFF; break; default: @@ -65,22 +63,19 @@ PowerManager::PowerManager() break; } - ret = device_add_callback(DEVICE_CALLBACK_DISPLAY_STATE, - PowerManager::OnPlatformStateChangedCB, + ret = device_add_callback(DEVICE_CALLBACK_DISPLAY_STATE, PowerManager::OnPlatformStateChangedCB, static_cast(this)); - if (DEVICE_ERROR_NONE != ret) - LoggerE("device_add_callback failed (%d)", ret); + if (DEVICE_ERROR_NONE != ret) LoggerE("device_add_callback failed (%d)", ret); } PowerManager::~PowerManager() { LoggerD("Enter"); - int ret = device_remove_callback(DEVICE_CALLBACK_DISPLAY_STATE, - PowerManager::OnPlatformStateChangedCB); - if (DEVICE_ERROR_NONE != ret) - LoggerE("device_remove_callback failed (%d)", ret); + int ret = + device_remove_callback(DEVICE_CALLBACK_DISPLAY_STATE, PowerManager::OnPlatformStateChangedCB); + if (DEVICE_ERROR_NONE != ret) LoggerE("device_remove_callback failed (%d)", ret); } -PowerManager* PowerManager::GetInstance(){ +PowerManager* PowerManager::GetInstance() { LoggerD("Enter"); static PowerManager instance; return &instance; @@ -89,31 +84,33 @@ PowerManager* PowerManager::GetInstance(){ void PowerManager::OnPlatformStateChangedCB(device_callback_e type, void* value, void* user_data) { LoggerD("Enter"); PowerManager* object = static_cast(user_data); - if (object == NULL){ + if (object == NULL) { LoggerE("User data is NULL"); return; } - if (type != DEVICE_CALLBACK_DISPLAY_STATE){ + if (type != DEVICE_CALLBACK_DISPLAY_STATE) { LoggerE("type is not DISPLAY_STATE"); return; } display_state_e state = static_cast(reinterpret_cast(value)); PowerState current = POWER_STATE_SCREEN_OFF; switch (state) { - case DISPLAY_STATE_NORMAL : - current = object->bright_state_enabled_ ? POWER_STATE_SCREEN_BRIGHT : POWER_STATE_SCREEN_NORMAL; + case DISPLAY_STATE_NORMAL: + current = + object->bright_state_enabled_ ? POWER_STATE_SCREEN_BRIGHT : POWER_STATE_SCREEN_NORMAL; // TODO: Remove log along with removal of deprecation power state if (POWER_STATE_SCREEN_BRIGHT == current) { - LoggerW("DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release."); + LoggerW( + "DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next " + "release."); } break; - case DISPLAY_STATE_SCREEN_DIM : + case DISPLAY_STATE_SCREEN_DIM: current = POWER_STATE_SCREEN_DIM; break; - case DISPLAY_STATE_SCREEN_OFF : - { + case DISPLAY_STATE_SCREEN_OFF: { current = POWER_STATE_SCREEN_OFF; if (object->set_custom_brightness_ == true) { PlatformResult result = object->RestoreScreenBrightness(); @@ -132,8 +129,7 @@ void PowerManager::OnPlatformStateChangedCB(device_callback_e type, void* value, void PowerManager::AddListener(PowerManagerListener* listener) { LoggerD("Enter"); auto it = std::find(listeners_.begin(), listeners_.end(), listener); - if (it == listeners_.end()) - listeners_.push_back(listener); + if (it == listeners_.end()) listeners_.push_back(listener); } void PowerManager::RemoveListener(PowerManagerListener* listener) { @@ -148,99 +144,91 @@ PlatformResult PowerManager::Request(PowerResource resource, PowerState state) { if (resource == POWER_RESOURCE_CPU && state != POWER_STATE_CPU_AWAKE) return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid PowerState"); - if(current_requested_state_ == POWER_STATE_SCREEN_DIM) { + if (current_requested_state_ == POWER_STATE_SCREEN_DIM) { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().UnlockState(&result); if (!error_code || result < 0) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "device_power_request_unlock error", - ("deviceUnlockState error %d", result)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "device_power_request_unlock error", + ("deviceUnlockState error %d", result)); } } int ret = 0; switch (state) { - case POWER_STATE_CPU_AWAKE: - { + case POWER_STATE_CPU_AWAKE: { ret = device_power_request_lock(POWER_LOCK_CPU, 0); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "device_power_request_lock error", - ("device_power_request_lock error %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "device_power_request_lock error", + ("device_power_request_lock error %d", ret)); } break; } - case POWER_STATE_SCREEN_DIM: - { + case POWER_STATE_SCREEN_DIM: { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().LockState(&result); if (!error_code || result < 0) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "device_power_request_lock error", - ("device_power_request_lock error %d", result)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "device_power_request_lock error", + ("device_power_request_lock error %d", result)); } break; } - case POWER_STATE_SCREEN_NORMAL: - { + case POWER_STATE_SCREEN_NORMAL: { ret = device_power_request_lock(POWER_LOCK_DISPLAY, 0); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "device_power_request_lock error", - ("device_power_request_lock error %d", ret)); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "device_power_request_lock error", + ("device_power_request_lock error %d", ret)); } break; } - case POWER_STATE_SCREEN_BRIGHT: - { - LoggerW("DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release."); + case POWER_STATE_SCREEN_BRIGHT: { + LoggerW( + "DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next " + "release."); int max_brightness; ret = device_display_get_max_brightness(0, &max_brightness); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while getting max brightness", - ("Platform error while getting max brightness: %d", ret)); + "Platform error while getting max brightness", + ("Platform error while getting max brightness: %d", ret)); } PlatformResult set_result = SetPlatformBrightness(max_brightness); - if (set_result.IsError()) - return set_result; + if (set_result.IsError()) return set_result; LoggerD("Succeeded setting the brightness to a max level: %d", max_brightness); ret = device_display_change_state(DISPLAY_STATE_NORMAL); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "device_display_change_state error", - ("device_display_change_state(DISPLAY_STATE_NORMAL) error %d", ret)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "device_display_change_state error", + ("device_display_change_state(DISPLAY_STATE_NORMAL) error %d", ret)); } ret = device_power_request_lock(POWER_LOCK_DISPLAY, 0); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "device_power_request_lock error", - ("device_power_request_lock error %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "device_power_request_lock error", + ("device_power_request_lock error %d", ret)); } bright_state_enabled_ = true; display_state_e platform_state = DISPLAY_STATE_NORMAL; ret = device_display_get_state(&platform_state); - if (DEVICE_ERROR_NONE != ret) - LoggerE("device_display_get_state failed (%d)", ret); + if (DEVICE_ERROR_NONE != ret) LoggerE("device_display_get_state failed (%d)", ret); if (DISPLAY_STATE_NORMAL == platform_state) { // TODO: Remove log along with removal of deprecation power state - LoggerW("DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release."); + LoggerW( + "DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next " + "release."); BroadcastScreenState(POWER_STATE_SCREEN_BRIGHT); } break; } case POWER_STATE_SCREEN_OFF: return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "SCREEN_OFF state cannot be requested"); + "SCREEN_OFF state cannot be requested"); default: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while locking state"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while locking state"); } current_requested_state_ = state; @@ -252,22 +240,21 @@ PlatformResult PowerManager::Release(PowerResource resource) { int ret; if (POWER_RESOURCE_SCREEN == resource) { ret = device_power_release_lock(POWER_LOCK_DISPLAY); - if (DEVICE_ERROR_NONE != ret) - LoggerE("Platform return value from dim unlock: %d", ret); + if (DEVICE_ERROR_NONE != ret) LoggerE("Platform return value from dim unlock: %d", ret); if (bright_state_enabled_) { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().SetBrightnessFromSettings(&result); if (!error_code || DEVICE_ERROR_NONE != result) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while setting restore brightness", - ("Platform error while setting restore brightness %d", result)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Platform error while setting restore brightness", + ("Platform error while setting restore brightness %d", result)); } } bright_state_enabled_ = false; display_state_e platform_state = DISPLAY_STATE_NORMAL; - if(current_requested_state_ == POWER_STATE_SCREEN_DIM) { + if (current_requested_state_ == POWER_STATE_SCREEN_DIM) { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().UnlockState(&result); if (!error_code || DEVICE_ERROR_NONE != result) { @@ -286,8 +273,7 @@ PlatformResult PowerManager::Release(PowerResource resource) { current_requested_state_ = POWER_STATE_NONE; } else if (POWER_RESOURCE_CPU == resource) { ret = device_power_release_lock(POWER_LOCK_CPU); - if (DEVICE_ERROR_NONE != ret) - LoggerE("Platform return value from off unlock: %d", ret); + if (DEVICE_ERROR_NONE != ret) LoggerE("Platform return value from off unlock: %d", ret); } return PlatformResult(ErrorCode::NO_ERROR); @@ -309,11 +295,10 @@ PlatformResult PowerManager::GetScreenBrightness(double* output) { int max_brightness; int ret = device_display_get_max_brightness(0, &max_brightness); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while getting max brightness", - ("Platform error while getting brightness: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while getting max brightness", + ("Platform error while getting brightness: %d", ret)); } - *output = (double)brightness/(double)max_brightness; + *output = (double)brightness / (double)max_brightness; return PlatformResult(ErrorCode::NO_ERROR); } @@ -321,13 +306,12 @@ PlatformResult PowerManager::SetScreenBrightness(double brightness) { LoggerD("Enter"); if (brightness > 1 || brightness < 0) return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "brightness should be 0 <= brightness <= 1"); + "brightness should be 0 <= brightness <= 1"); int max_brightness; int ret = device_display_get_max_brightness(0, &max_brightness); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while getting max brightness", - ("Platform error while setting restore brightness: %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while getting max brightness", + ("Platform error while setting restore brightness: %d", ret)); } int platform_brightness = (int)(brightness * max_brightness); @@ -335,8 +319,7 @@ PlatformResult PowerManager::SetScreenBrightness(double brightness) { platform_brightness = 1; } PlatformResult set_result = SetPlatformBrightness(platform_brightness); - if (set_result.IsError()) - return set_result; + if (set_result.IsError()) return set_result; LoggerD("Set the brightness value: %d", platform_brightness); return set_result; } @@ -348,7 +331,7 @@ PlatformResult PowerManager::IsScreenOn(bool* state) { int ret = device_display_get_state(&platform_state); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error while getting screen state.", - ("device_display_get_state failed (%d)", ret)); + ("device_display_get_state failed (%d)", ret)); } *state = (DISPLAY_STATE_SCREEN_OFF != platform_state); @@ -359,9 +342,8 @@ PlatformResult PowerManager::SetScreenState(bool onoff) { LoggerD("Enter"); int ret = device_display_change_state(onoff ? DISPLAY_STATE_NORMAL : DISPLAY_STATE_SCREEN_OFF); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while changing screen state", - ("Platform error while changing screen state %d", ret)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while changing screen state", + ("Platform error while changing screen state %d", ret)); } int timeout = 100; @@ -376,7 +358,7 @@ PlatformResult PowerManager::SetScreenState(bool onoff) { break; } - struct timespec sleep_time = { 0, 100L * 1000L * 1000L }; + struct timespec sleep_time = {0, 100L * 1000L * 1000L}; nanosleep(&sleep_time, nullptr); } @@ -388,9 +370,8 @@ PlatformResult PowerManager::RestoreScreenBrightness() { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().SetBrightnessFromSettings(&result); if (!error_code || DEVICE_ERROR_NONE != result) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while restoring brightness", - ("Platform error while restoring brightness %d", result)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while restoring brightness", + ("Platform error while restoring brightness %d", result)); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -403,7 +384,8 @@ PlatformResult PowerManager::SetPlatformBrightness(int brightness) { should_be_read_from_cache_ = true; return PlatformResult(ErrorCode::NO_ERROR); } else if (current_state_ == POWER_STATE_SCREEN_BRIGHT) { - LoggerW("DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release."); + LoggerW( + "DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release."); current_brightness_ = brightness; LoggerD("Current state is not normal state the value is saved in cache: %d", brightness); @@ -416,9 +398,9 @@ PlatformResult PowerManager::SetPlatformBrightness(int brightness) { int result = 0; auto error_code = PowerPlatformProxy::GetInstance().SetBrightness(brightness, &result); if (!error_code || result != 0) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform error while setting brightness.", - ("Platform error while setting %d brightness: %d", brightness, result)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Platform error while setting brightness.", + ("Platform error while setting %d brightness: %d", brightness, result)); } set_custom_brightness_ = true; current_brightness_ = brightness; @@ -447,7 +429,9 @@ PlatformResult PowerManager::GetPlatformBrightness(int* result) { int is_auto_brightness = 0; vconf_get_int(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, &is_auto_brightness); if (is_auto_brightness == 1) { - int ret = vconf_get_int(VCONFKEY_SETAPPL_PREFIX"/automatic_brightness_level" /*prevent RSA build error*/, &brightness); + int ret = vconf_get_int(VCONFKEY_SETAPPL_PREFIX + "/automatic_brightness_level" /*prevent RSA build error*/, + &brightness); if (ret != 0) { // RSA binary has no AUTOMATIC_BRIGHTNESS vconf_get_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, &brightness); @@ -462,14 +446,13 @@ PlatformResult PowerManager::GetPlatformBrightness(int* result) { } } - LoggerD("BRIGHTNESS(%s) %d", is_auto_brightness == 1 ? "auto" : "fix" , brightness); + LoggerD("BRIGHTNESS(%s) %d", is_auto_brightness == 1 ? "auto" : "fix", brightness); *result = brightness; return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult PowerManager::RestoreSettedBrightness() { LoggerD("Enter"); PlatformResult result(ErrorCode::NO_ERROR); @@ -489,8 +472,7 @@ PlatformResult PowerManager::RestoreSettedBrightness() { void PowerManager::BroadcastScreenState(PowerState current) { LoggerD("Enter"); - if (current_state_ == current) - return; + if (current_state_ == current) return; PowerState prev_state = current_state_; current_state_ = current; @@ -511,5 +493,5 @@ void PowerManager::BroadcastScreenState(PowerState current) { } } -} // namespace power -} // namespace extension +} // namespace power +} // namespace extension diff --git a/src/power/power_manager.h b/src/power/power_manager.h old mode 100755 new mode 100644 index 7af09e4..da82348 --- a/src/power/power_manager.h +++ b/src/power/power_manager.h @@ -17,9 +17,9 @@ #ifndef POWER_POWER_MANAGER_H_ #define POWER_POWER_MANAGER_H_ -#include -#include #include +#include +#include #include "common/platform_result.h" @@ -42,7 +42,7 @@ enum PowerState { class PowerManagerListener { public: - virtual void OnScreenStateChanged(PowerState prev_state, PowerState new_state)=0; + virtual void OnScreenStateChanged(PowerState prev_state, PowerState new_state) = 0; }; class PowerManager { @@ -58,6 +58,7 @@ class PowerManager { common::PlatformResult SetScreenState(bool onoff); static PowerManager* GetInstance(); + private: common::PlatformResult GetPlatformBrightness(int* result); common::PlatformResult SetPlatformBrightness(int brightness); @@ -80,8 +81,7 @@ class PowerManager { PowerState current_requested_state_; }; -} // namespace power -} // namespace extension - -#endif // POWER_POWER_MANAGER_H_ +} // namespace power +} // namespace extension +#endif // POWER_POWER_MANAGER_H_ diff --git a/src/power/power_platform_proxy.cc b/src/power/power_platform_proxy.cc index c176d2f..f23f4a0 100644 --- a/src/power/power_platform_proxy.cc +++ b/src/power/power_platform_proxy.cc @@ -31,7 +31,9 @@ PowerPlatformProxy::PowerPlatformProxy() LoggerD("Entered"); } -PowerPlatformProxy::~PowerPlatformProxy() { LoggerD("Entered"); } +PowerPlatformProxy::~PowerPlatformProxy() { + LoggerD("Entered"); +} PowerPlatformProxy& PowerPlatformProxy::GetInstance() { LoggerD("Entered"); @@ -43,8 +45,7 @@ common::PlatformResult PowerPlatformProxy::LockState(int* result) { LoggerD("Entered PPP LockState"); if (!gdbus_op_.LockState(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -53,19 +54,16 @@ common::PlatformResult PowerPlatformProxy::UnlockState(int* result) { LoggerD("Entered PPP UnlockState"); if (!gdbus_op_.UnlockState(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } -common::PlatformResult PowerPlatformProxy::SetBrightnessFromSettings( - int* result) { +common::PlatformResult PowerPlatformProxy::SetBrightnessFromSettings(int* result) { LoggerD("Entered PPP SetBrightnessFromSettings"); if (!gdbus_op_.ReleaseBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -74,8 +72,7 @@ common::PlatformResult PowerPlatformProxy::SetBrightness(int val, int* result) { LoggerD("Entered PPP SetBrightness"); if (!gdbus_op_.HoldBrightness(val, result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -84,8 +81,7 @@ common::PlatformResult PowerPlatformProxy::GetBrightness(int* result) { LoggerD("Entered PPP GetBrightness"); if (!gdbus_op_.CurrentBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -94,8 +90,7 @@ common::PlatformResult PowerPlatformProxy::IsCustomBrightness(int* result) { LoggerD("Entered PPP IsCustomBrightness"); if (!gdbus_op_.CustomBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); - return PlatformResult(ErrorCode::UNKNOWN_ERR, - "Failed to get reply from gdbus"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); } return PlatformResult(ErrorCode::NO_ERROR); } diff --git a/src/preference/preference_extension.cc b/src/preference/preference_extension.cc index 45d388f..c363c75 100644 --- a/src/preference/preference_extension.cc +++ b/src/preference/preference_extension.cc @@ -30,7 +30,8 @@ PreferenceExtension::PreferenceExtension() { SetJavaScriptAPI(kSource_preference_api); } -PreferenceExtension::~PreferenceExtension() {} +PreferenceExtension::~PreferenceExtension() { +} common::Instance* PreferenceExtension::CreateInstance() { return new extension::preference::PreferenceInstance; diff --git a/src/preference/preference_extension.h b/src/preference/preference_extension.h index 1df8fd1..9f2ba36 100644 --- a/src/preference/preference_extension.h +++ b/src/preference/preference_extension.h @@ -28,5 +28,4 @@ class PreferenceExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // PREFERENCE_PREFERENCE_EXTENSION_H_ - +#endif // PREFERENCE_PREFERENCE_EXTENSION_H_ diff --git a/src/preference/preference_instance.cc b/src/preference/preference_instance.cc index 851689b..c7ebe80 100644 --- a/src/preference/preference_instance.cc +++ b/src/preference/preference_instance.cc @@ -14,13 +14,12 @@ * limitations under the License. */ +#include "preference/preference_instance.h" #include "common/logger.h" #include "common/picojson.h" +#include "common/scope_exit.h" #include "common/task-queue.h" #include "common/tools.h" -#include "common/scope_exit.h" -#include "preference/preference_instance.h" - namespace extension { namespace preference { @@ -30,22 +29,20 @@ const char* kKey = "key"; const char* kValue = "value"; const common::ListenerToken kPreferenceChangeListenerToken{"PREFERENCE_CHANGED"}; -} // namespace +} // namespace -#define CHECK_EXIST(args, name) \ - if (args.end() == args.find(name)) { \ +#define CHECK_EXIST(args, name) \ + if (args.end() == args.find(name)) { \ return common::TypeMismatchError(std::string(name) + " is required argument"); \ } - PreferenceInstance::PreferenceInstance() { ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER(c,x) \ - RegisterSyncHandler(c, std::bind(&PreferenceInstance::x, this, _1)); +#define REGISTER(c, x) RegisterSyncHandler(c, std::bind(&PreferenceInstance::x, this, _1)); REGISTER("PreferenceManager_setValue", SetValue); REGISTER("PreferenceManager_getValue", GetValue); REGISTER("PreferenceManager_remove", Remove); @@ -54,18 +51,17 @@ PreferenceInstance::PreferenceInstance() { REGISTER("PreferenceManager_setChangeListener", SetChangeListener); REGISTER("PreferenceManager_unsetChangeListener", UnsetChangeListener); #undef REGISTER -#define REGISTER_ASYNC(c,x) \ - RegisterHandler(c, std::bind(&PreferenceInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterHandler(c, std::bind(&PreferenceInstance::x, this, _1, _2)); REGISTER_ASYNC("PreferenceManager_getAll", GetAll); #undef REGISTER_ASYNC } -PreferenceInstance::~PreferenceInstance() -{ +PreferenceInstance::~PreferenceInstance() { ScopeLogger(); } -common::TizenResult PreferenceInstance::GetAll(const picojson::object& args, const common::AsyncToken& token) { +common::TizenResult PreferenceInstance::GetAll(const picojson::object& args, + const common::AsyncToken& token) { ScopeLogger(); return manager_.GetAll(SimplePost(token)); @@ -132,5 +128,5 @@ common::TizenResult PreferenceInstance::UnsetChangeListener(const picojson::obje return manager_.UnsetChangeListener(key); } -} // namespace preference -} // namespace extension +} // namespace preference +} // namespace extension diff --git a/src/preference/preference_instance.h b/src/preference/preference_instance.h index 946bc72..3b4bfe6 100644 --- a/src/preference/preference_instance.h +++ b/src/preference/preference_instance.h @@ -24,11 +24,11 @@ namespace extension { namespace preference { class PreferenceInstance : public common::TizenInstance { -public: + public: PreferenceInstance(); virtual ~PreferenceInstance(); -private: + private: common::TizenResult GetAll(const picojson::object& args, const common::AsyncToken& token); common::TizenResult SetValue(const picojson::object& args); common::TizenResult GetValue(const picojson::object& args); @@ -41,7 +41,7 @@ private: PreferenceManager manager_; }; -} // namespace preference -} // namespace extension +} // namespace preference +} // namespace extension -#endif // PREFERENCE_PREFERENCE_INSTANCE_H_ +#endif // PREFERENCE_PREFERENCE_INSTANCE_H_ diff --git a/src/preference/preference_manager.cc b/src/preference/preference_manager.cc index e24be80..b00b317 100644 --- a/src/preference/preference_manager.cc +++ b/src/preference/preference_manager.cc @@ -20,8 +20,8 @@ #include "common/logger.h" #include "common/tools.h" -#include "preference/preference_manager.h" #include "preference/preference_instance.h" +#include "preference/preference_manager.h" namespace extension { namespace preference { @@ -141,7 +141,7 @@ void ChangedCb(const char* key, void* user_data) { LoggerE("preference_set_ function error"); } } -} // namespace +} // namespace PreferenceManager::~PreferenceManager() { ScopeLogger(); @@ -175,7 +175,8 @@ common::TizenResult PreferenceManager::GetAll(const common::PostCallback& callba return common::TizenSuccess(); } -common::TizenResult PreferenceManager::SetValue(const std::string& key, const picojson::value& value) { +common::TizenResult PreferenceManager::SetValue(const std::string& key, + const picojson::value& value) { ScopeLogger(); int ret = PREFERENCE_ERROR_NONE; @@ -217,7 +218,7 @@ common::TizenResult PreferenceManager::Remove(const std::string& key) { // unsetting listener if it is registered for key to be removed auto res = UnsetChangeListener(key); if (!res) { - //only log an error - listener could not be set + // only log an error - listener could not be set LoggerD("unsetting listener for given key failed, ignore error"); } @@ -234,7 +235,7 @@ common::TizenResult PreferenceManager::RemoveAll() { int ret = preference_remove_all(); if (ret == PREFERENCE_ERROR_NONE) { - //only clear vector (listeners are removed natively in preference_remove_all function) + // only clear vector (listeners are removed natively in preference_remove_all function) key_listeners_.clear(); return common::TizenSuccess(); } else { @@ -270,7 +271,7 @@ common::TizenResult PreferenceManager::SetChangeListener(const std::string& key, } } - int ret = preference_set_changed_cb(key.c_str(), ChangedCb, (void*) &post_changed_callback_); + int ret = preference_set_changed_cb(key.c_str(), ChangedCb, (void*)&post_changed_callback_); if (PREFERENCE_ERROR_NONE == ret) { key_listeners_.push_back(key); @@ -301,5 +302,5 @@ common::TizenResult PreferenceManager::UnsetChangeListener(const std::string& ke return common::NotFoundError(std::string("Listener for given key was not found")); } -} // namespace preference -} // namespace extension +} // namespace preference +} // namespace extension diff --git a/src/preference/preference_manager.h b/src/preference/preference_manager.h index 2f46539..6f7cc6d 100644 --- a/src/preference/preference_manager.h +++ b/src/preference/preference_manager.h @@ -26,7 +26,7 @@ namespace extension { namespace preference { class PreferenceManager { -public: + public: ~PreferenceManager(); common::TizenResult GetAll(const common::PostCallback& callback); common::TizenResult SetValue(const std::string& key, const picojson::value& value); @@ -34,16 +34,17 @@ public: common::TizenResult Remove(const std::string& key); common::TizenResult RemoveAll(void); common::TizenResult Exists(const std::string& key); - common::TizenResult SetChangeListener(const std::string& key, const common::PostCallback callback); + common::TizenResult SetChangeListener(const std::string& key, + const common::PostCallback callback); common::TizenResult UnsetChangeListener(const std::string& key); -private: + private: common::PostCallback post_changed_callback_; std::vector key_listeners_; static std::mutex key_listener_mtx_; }; -} // namespace preference -} // namespace extension +} // namespace preference +} // namespace extension -#endif // PREFERENCE_PREFERENCE_MANAGER_H_ +#endif // PREFERENCE_PREFERENCE_MANAGER_H_ diff --git a/src/push/push_extension.cc b/src/push/push_extension.cc index e231f0b..98eacba 100644 --- a/src/push/push_extension.cc +++ b/src/push/push_extension.cc @@ -24,19 +24,20 @@ namespace extension { namespace push { PushExtension::PushExtension() { - SetExtensionName("tizen.push"); - SetJavaScriptAPI(kSource_push_api); + SetExtensionName("tizen.push"); + SetJavaScriptAPI(kSource_push_api); } -PushExtension::~PushExtension() {} +PushExtension::~PushExtension() { +} common::Instance* PushExtension::CreateInstance() { - return new PushInstance; + return new PushInstance; } } // namespace push } // namespace extension common::Extension* CreateExtension() { - return new extension::push::PushExtension; + return new extension::push::PushExtension; } diff --git a/src/push/push_extension.h b/src/push/push_extension.h index 4118bb2..66aa874 100644 --- a/src/push/push_extension.h +++ b/src/push/push_extension.h @@ -25,15 +25,14 @@ namespace push { class PushExtension : public common::Extension { public: - PushExtension(); - virtual ~PushExtension(); + PushExtension(); + virtual ~PushExtension(); private: - virtual common::Instance* CreateInstance(); + virtual common::Instance* CreateInstance(); }; } // namespace push } // namespace extension #endif // SRC_PUSH_PUSH_EXTENSION_H_ - diff --git a/src/push/push_instance.cc b/src/push/push_instance.cc index 3e054e1..bc321f9 100644 --- a/src/push/push_instance.cc +++ b/src/push/push_instance.cc @@ -28,197 +28,173 @@ namespace { const std::string kPrivilegePush = "http://tizen.org/privilege/push"; -} // namespace +} // namespace PushInstance::PushInstance() { - LoggerD("Enter"); - using std::placeholders::_1; - using std::placeholders::_2; - - #define REGISTER_ASYNC(c, func) \ - RegisterSyncHandler(c, func); - #define REGISTER_SYNC(c, func) \ - RegisterSyncHandler(c, func); - - REGISTER_ASYNC("Push_registerService", - std::bind(&PushInstance::registerService, this, _1, _2)); - REGISTER_ASYNC("Push_registerApplication", - std::bind(&PushInstance::registerApplication, this, _1, _2)); - REGISTER_ASYNC("Push_unregisterService", - std::bind(&PushInstance::unregisterService, this, _1, _2)); - REGISTER_ASYNC("Push_unregisterApplication", - std::bind(&PushInstance::unregisterApplication, this, _1, _2)); - REGISTER_SYNC("Push_connectService", - std::bind(&PushInstance::connectService, this, _1, _2)); - REGISTER_SYNC("Push_connect", - std::bind(&PushInstance::connect, this, _1, _2)); - REGISTER_SYNC("Push_disconnectService", - std::bind(&PushInstance::disconnectService, this, _1, _2)); - REGISTER_SYNC("Push_disconnect", - std::bind(&PushInstance::disconnect, this, _1, _2)); - REGISTER_SYNC("Push_getRegistrationId", - std::bind(&PushInstance::getRegistrationId, this, _1, _2)); - REGISTER_SYNC("Push_getUnreadNotifications", - std::bind(&PushInstance::getUnreadNotifications, this, _1, _2)); - REGISTER_SYNC("Push_getPushMessage", - std::bind(&PushInstance::getPushMessage, this, _1, _2)); - - #undef REGISTER_ASYNC - #undef REGISTER_SYNC - - impl = new PushManager(this); + LoggerD("Enter"); + using std::placeholders::_1; + using std::placeholders::_2; + +#define REGISTER_ASYNC(c, func) RegisterSyncHandler(c, func); +#define REGISTER_SYNC(c, func) RegisterSyncHandler(c, func); + + REGISTER_ASYNC("Push_registerService", std::bind(&PushInstance::registerService, this, _1, _2)); + REGISTER_ASYNC("Push_registerApplication", + std::bind(&PushInstance::registerApplication, this, _1, _2)); + REGISTER_ASYNC("Push_unregisterService", + std::bind(&PushInstance::unregisterService, this, _1, _2)); + REGISTER_ASYNC("Push_unregisterApplication", + std::bind(&PushInstance::unregisterApplication, this, _1, _2)); + REGISTER_SYNC("Push_connectService", std::bind(&PushInstance::connectService, this, _1, _2)); + REGISTER_SYNC("Push_connect", std::bind(&PushInstance::connect, this, _1, _2)); + REGISTER_SYNC("Push_disconnectService", + std::bind(&PushInstance::disconnectService, this, _1, _2)); + REGISTER_SYNC("Push_disconnect", std::bind(&PushInstance::disconnect, this, _1, _2)); + REGISTER_SYNC("Push_getRegistrationId", + std::bind(&PushInstance::getRegistrationId, this, _1, _2)); + REGISTER_SYNC("Push_getUnreadNotifications", + std::bind(&PushInstance::getUnreadNotifications, this, _1, _2)); + REGISTER_SYNC("Push_getPushMessage", std::bind(&PushInstance::getPushMessage, this, _1, _2)); + +#undef REGISTER_ASYNC +#undef REGISTER_SYNC + + impl = new PushManager(this); } +void PushInstance::registerService(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); -void PushInstance::registerService(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->registerService( - args.get("callbackId").get()); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error occured")); - } else { - ReportSuccess(out); - } + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + common::PlatformResult result = impl->registerService(args.get("callbackId").get()); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error occured")); + } else { + ReportSuccess(out); + } } -void PushInstance::registerApplication(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->registerApplication( - args.get("callbackId").get()); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error occured")); - } else { - ReportSuccess(out); - } +void PushInstance::registerApplication(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); + + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + common::PlatformResult result = impl->registerApplication(args.get("callbackId").get()); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error occured")); + } else { + ReportSuccess(out); + } } -void PushInstance::unregisterService(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::unregisterService(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->unregisterService( - args.get("callbackId").get()); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error occured")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->unregisterService(args.get("callbackId").get()); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error occured")); + } else { + ReportSuccess(out); + } } -void PushInstance::unregisterApplication(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::unregisterApplication(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->unregisterApplication( - args.get("callbackId").get()); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error occured")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->unregisterApplication(args.get("callbackId").get()); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error occured")); + } else { + ReportSuccess(out); + } } -void PushInstance::connectService(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::connectService(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->connectService(); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error while connect service")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->connectService(); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error while connect service")); + } else { + ReportSuccess(out); + } } -void PushInstance::connect(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::connect(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->connect(); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error while connect service")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->connect(); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error while connect service")); + } else { + ReportSuccess(out); + } } -void PushInstance::disconnectService(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::disconnectService(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->disconnectService(); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error while disconnect service")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->disconnectService(); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error while disconnect service")); + } else { + ReportSuccess(out); + } } -void PushInstance::disconnect(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::disconnect(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->disconnect(); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error while disconnect service")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->disconnect(); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error while disconnect service")); + } else { + ReportSuccess(out); + } } +void PushInstance::getRegistrationId(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); -void PushInstance::getRegistrationId(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); - - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - std::string id; - common::PlatformResult result = impl->getRegistrationId(id); - if (result.IsError()) { - // this method should fail silently and return null - picojson::value res = picojson::value(); - ReportSuccess(res, out); - } else { - picojson::value res(id); - ReportSuccess(res, out); - } + std::string id; + common::PlatformResult result = impl->getRegistrationId(id); + if (result.IsError()) { + // this method should fail silently and return null + picojson::value res = picojson::value(); + ReportSuccess(res, out); + } else { + picojson::value res(id); + ReportSuccess(res, out); + } } -void PushInstance::getUnreadNotifications(const picojson::value& args, - picojson::object& out) { - LoggerD("Enter"); +void PushInstance::getUnreadNotifications(const picojson::value& args, picojson::object& out) { + LoggerD("Enter"); - CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); + CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); - common::PlatformResult result = impl->getUnreadNotifications(); - if (result.IsError()) { - LogAndReportError(result, &out, ("Error occured")); - } else { - ReportSuccess(out); - } + common::PlatformResult result = impl->getUnreadNotifications(); + if (result.IsError()) { + LogAndReportError(result, &out, ("Error occured")); + } else { + ReportSuccess(out); + } } -void PushInstance::getPushMessage(const picojson::value& args, - picojson::object& out) { +void PushInstance::getPushMessage(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -248,54 +224,53 @@ void PushInstance::onPushState(push_service_state_e state, common::PlatformResul Instance::PostMessage(this, res.serialize().c_str()); } -void PushInstance::onPushRegister(double callbackId, - common::PlatformResult result, const std::string& id) { - picojson::value res{picojson::object()}; - picojson::object& dict = res.get(); - - dict["callbackId"] = picojson::value(callbackId); - if (result.IsError()) { - dict["error"] = result.ToJSON(); - } else { - dict["registrationId"] = picojson::value(id); - } - Instance::PostMessage(this, res.serialize().c_str()); +void PushInstance::onPushRegister(double callbackId, common::PlatformResult result, + const std::string& id) { + picojson::value res{picojson::object()}; + picojson::object& dict = res.get(); + + dict["callbackId"] = picojson::value(callbackId); + if (result.IsError()) { + dict["error"] = result.ToJSON(); + } else { + dict["registrationId"] = picojson::value(id); + } + Instance::PostMessage(this, res.serialize().c_str()); } void PushInstance::onPushNotify(push_service_notification_h noti) { - LoggerD("Enter"); - picojson::value res{picojson::object()}; - picojson::object& dict = res.get(); + LoggerD("Enter"); + picojson::value res{picojson::object()}; + picojson::object& dict = res.get(); - picojson::value push_message{picojson::object()}; - picojson::object& push_message_obj = push_message.get(); + picojson::value push_message{picojson::object()}; + picojson::object& push_message_obj = push_message.get(); - PushManagerCommon::notificationToJson(noti, &push_message_obj); + PushManagerCommon::notificationToJson(noti, &push_message_obj); - dict["listenerId"] = picojson::value("Push_Notification_Listener"); - dict["pushMessage"] = push_message; - Instance::PostMessage(this, res.serialize().c_str()); + dict["listenerId"] = picojson::value("Push_Notification_Listener"); + dict["pushMessage"] = push_message; + Instance::PostMessage(this, res.serialize().c_str()); } -void PushInstance::onDeregister(double callbackId, - common::PlatformResult result) { - LoggerD("Enter"); - picojson::value res{picojson::object()}; - picojson::object& dict = res.get(); - - dict["callbackId"] = picojson::value(callbackId); - if (result.IsError()) { - dict["error"] = result.ToJSON(); - } - Instance::PostMessage(this, res.serialize().c_str()); +void PushInstance::onDeregister(double callbackId, common::PlatformResult result) { + LoggerD("Enter"); + picojson::value res{picojson::object()}; + picojson::object& dict = res.get(); + + dict["callbackId"] = picojson::value(callbackId); + if (result.IsError()) { + dict["error"] = result.ToJSON(); + } + Instance::PostMessage(this, res.serialize().c_str()); } PushInstance::~PushInstance() { - LoggerD("Enter"); - if (impl) { - delete impl; - impl = nullptr; - } + LoggerD("Enter"); + if (impl) { + delete impl; + impl = nullptr; + } } } // namespace push diff --git a/src/push/push_instance.h b/src/push/push_instance.h index 12b0dd9..860321f 100644 --- a/src/push/push_instance.h +++ b/src/push/push_instance.h @@ -24,30 +24,30 @@ namespace extension { namespace push { -class PushInstance: public common::ParsedInstance, public EventListener { +class PushInstance : public common::ParsedInstance, public EventListener { public: - PushInstance(); - virtual ~PushInstance(); - virtual void onPushState(push_service_state_e state, common::PlatformResult result); - virtual void onPushRegister(double callbackId, - common::PlatformResult result, const std::string& id); - virtual void onPushNotify(push_service_notification_h noti); - virtual void onDeregister(double callbackId, common::PlatformResult result); + PushInstance(); + virtual ~PushInstance(); + virtual void onPushState(push_service_state_e state, common::PlatformResult result); + virtual void onPushRegister(double callbackId, common::PlatformResult result, + const std::string& id); + virtual void onPushNotify(push_service_notification_h noti); + virtual void onDeregister(double callbackId, common::PlatformResult result); private: - void registerService(const picojson::value& args, picojson::object& out); - void registerApplication(const picojson::value& args, picojson::object& out); - void unregisterService(const picojson::value& args, picojson::object& out); - void unregisterApplication(const picojson::value& args, picojson::object& out); - void connectService(const picojson::value& args, picojson::object& out); - void connect(const picojson::value& args, picojson::object& out); - void disconnectService(const picojson::value& args, picojson::object& out); - void disconnect(const picojson::value& args, picojson::object& out); - void getRegistrationId(const picojson::value& args, picojson::object& out); - void getUnreadNotifications(const picojson::value& args, picojson::object& out); - void getPushMessage(const picojson::value& args, picojson::object& out); - - PushManager* impl; + void registerService(const picojson::value& args, picojson::object& out); + void registerApplication(const picojson::value& args, picojson::object& out); + void unregisterService(const picojson::value& args, picojson::object& out); + void unregisterApplication(const picojson::value& args, picojson::object& out); + void connectService(const picojson::value& args, picojson::object& out); + void connect(const picojson::value& args, picojson::object& out); + void disconnectService(const picojson::value& args, picojson::object& out); + void disconnect(const picojson::value& args, picojson::object& out); + void getRegistrationId(const picojson::value& args, picojson::object& out); + void getUnreadNotifications(const picojson::value& args, picojson::object& out); + void getPushMessage(const picojson::value& args, picojson::object& out); + + PushManager* impl; }; } // namespace push diff --git a/src/push/push_manager.cc b/src/push/push_manager.cc index 84ec17a..3851c4c 100644 --- a/src/push/push_manager.cc +++ b/src/push/push_manager.cc @@ -15,17 +15,17 @@ */ #include "push/push_manager.h" -#include -#include #include #include #include #include +#include +#include #include -#include "push/push_manager_common.h" #include "common/extension.h" #include "common/logger.h" +#include "push/push_manager_common.h" namespace extension { namespace push { @@ -39,23 +39,21 @@ struct PushManagerHolder { }; // TODO remove on next release - 2.4 API only -#define CHECK_CONNECTION() \ - if (!m_handle) { \ - int ret = push_service_connect(m_pkgId.c_str(), onPushState,\ - onPushNotify, this, &m_handle);\ - if (ret != PUSH_SERVICE_ERROR_NONE) { \ - LoggerE("Failed to connect to push (%d)", ret);\ - }\ - m_ignoreNotificationEvents = true;\ - } - - -PushManager::PushManager(EventListener* listener) : - m_listener (listener), - m_handle (nullptr), - app_control_(nullptr), - operation_(nullptr), - m_ignoreNotificationEvents (true) { +#define CHECK_CONNECTION() \ + if (!m_handle) { \ + int ret = push_service_connect(m_pkgId.c_str(), onPushState, onPushNotify, this, &m_handle); \ + if (ret != PUSH_SERVICE_ERROR_NONE) { \ + LoggerE("Failed to connect to push (%d)", ret); \ + } \ + m_ignoreNotificationEvents = true; \ + } + +PushManager::PushManager(EventListener* listener) + : m_listener(listener), + m_handle(nullptr), + app_control_(nullptr), + operation_(nullptr), + m_ignoreNotificationEvents(true) { LoggerD("Enter"); initPkgId(); InitAppControl(); @@ -80,34 +78,34 @@ PushManager::~PushManager() { } void PushManager::initPkgId() { - LoggerD("Enter"); - int pid = getpid(); - char *temp = nullptr; - int ret = app_manager_get_app_id(pid, &temp); - if (APP_MANAGER_ERROR_NONE != ret || nullptr == temp) { - LoggerE("Failed to get appid (%d)", ret); - return; - } + LoggerD("Enter"); + int pid = getpid(); + char* temp = nullptr; + int ret = app_manager_get_app_id(pid, &temp); + if (APP_MANAGER_ERROR_NONE != ret || nullptr == temp) { + LoggerE("Failed to get appid (%d)", ret); + return; + } - std::string m_appId = temp; - free(temp); - temp = NULL; + std::string m_appId = temp; + free(temp); + temp = NULL; - app_info_h info; - ret = app_manager_get_app_info(m_appId.c_str(), &info); - if (ret != APP_MANAGER_ERROR_NONE) { - LoggerE("Failed to get app info (%d)", ret); - return; - } + app_info_h info; + ret = app_manager_get_app_info(m_appId.c_str(), &info); + if (ret != APP_MANAGER_ERROR_NONE) { + LoggerE("Failed to get app info (%d)", ret); + return; + } - ret = app_info_get_package(info, &temp); - if (ret == APP_MANAGER_ERROR_NONE && temp != NULL) { - m_pkgId = temp; - free(temp); - } else { - LoggerE("Failed to get pkg id (%d)", ret); - } - app_info_destroy(info); + ret = app_info_get_package(info, &temp); + if (ret == APP_MANAGER_ERROR_NONE && temp != NULL) { + m_pkgId = temp; + free(temp); + } else { + LoggerE("Failed to get pkg id (%d)", ret); + } + app_info_destroy(info); } void PushManager::InitAppControl() { @@ -115,8 +113,7 @@ void PushManager::InitAppControl() { const auto encoded_bundle = PushManagerCommon::GetEncodedBundle(); - auto bundle = bundle_decode((bundle_raw*) (encoded_bundle.c_str()), - encoded_bundle.length()); + auto bundle = bundle_decode((bundle_raw*)(encoded_bundle.c_str()), encoded_bundle.length()); if (nullptr == bundle) { LoggerE("Failed to decode bundle"); return; @@ -136,16 +133,16 @@ void PushManager::InitAppControl() { } bool PushManager::checkRegistered_2_4() { - LoggerD("Enter"); - bool result = false; - char* temp = NULL; - int ret = push_service_get_registration_id(m_handle, &temp); - if (ret != PUSH_SERVICE_ERROR_NONE) { - return result; - } - result = (NULL != temp ? true : false); - free(temp); + LoggerD("Enter"); + bool result = false; + char* temp = NULL; + int ret = push_service_get_registration_id(m_handle, &temp); + if (ret != PUSH_SERVICE_ERROR_NONE) { return result; + } + result = (NULL != temp ? true : false); + free(temp); + return result; } PlatformResult PushManager::connectService() { @@ -159,17 +156,16 @@ PlatformResult PushManager::connect() { LoggerD("Enter"); if (!m_handle) { - int ret = push_service_connect(m_pkgId.c_str(), onPushState, - onPushNotify, this, &m_handle); + int ret = push_service_connect(m_pkgId.c_str(), onPushState, onPushNotify, this, &m_handle); if (PUSH_SERVICE_ERROR_NONE != ret) { - return LogAndCreateResult(PushManagerCommon::ConvertPushError(ret), "Failed to connect to push service", + return LogAndCreateResult(PushManagerCommon::ConvertPushError(ret), + "Failed to connect to push service", ("push_service_connect failed (%d)", ret)); } } return common::PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult PushManager::disconnectService() { LoggerD("Enter"); // disconnecting from push server @@ -227,29 +223,27 @@ common::PlatformResult PushManager::unregisterService(double callbackId) { PushManagerHolder* holder = new PushManagerHolder{this, callbackId}; if (!checkRegistered_2_4()) { - LoggerD("Already unregistered, call unregister callback"); - if (!g_idle_add(onFakeDeregister_2_4, holder)) { - delete holder; - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error", ("g_idle_add failed")); - } + LoggerD("Already unregistered, call unregister callback"); + if (!g_idle_add(onFakeDeregister_2_4, holder)) { + delete holder; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("g_idle_add failed")); + } } else { - int ret = push_service_deregister(m_handle, onDeregister_2_4, holder); - if (ret != PUSH_SERVICE_ERROR_NONE) { - delete holder; - if (ret == PUSH_SERVICE_ERROR_INVALID_PARAMETER) { - LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_INVALID_PARAMETER"); - } else if (ret == PUSH_SERVICE_ERROR_OUT_OF_MEMORY) { - LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_OUT_OF_MEMORY"); - } else if (ret == PUSH_SERVICE_ERROR_NOT_CONNECTED) { - LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_NOT_CONNECTED"); - } else if (ret == PUSH_SERVICE_ERROR_OPERATION_FAILED) { - LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_OPERATION_FAILED"); - } - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error", - ("Failed to deregister: push_service_deregister failed (%d)", ret)); + int ret = push_service_deregister(m_handle, onDeregister_2_4, holder); + if (ret != PUSH_SERVICE_ERROR_NONE) { + delete holder; + if (ret == PUSH_SERVICE_ERROR_INVALID_PARAMETER) { + LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_INVALID_PARAMETER"); + } else if (ret == PUSH_SERVICE_ERROR_OUT_OF_MEMORY) { + LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_OUT_OF_MEMORY"); + } else if (ret == PUSH_SERVICE_ERROR_NOT_CONNECTED) { + LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_NOT_CONNECTED"); + } else if (ret == PUSH_SERVICE_ERROR_OPERATION_FAILED) { + LoggerE("[push_service_deregister] PUSH_SERVICE_ERROR_OPERATION_FAILED"); } + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", + ("Failed to deregister: push_service_deregister failed (%d)", ret)); + } } return common::PlatformResult(ErrorCode::NO_ERROR); } @@ -273,7 +267,8 @@ common::PlatformResult PushManager::getRegistrationId(std::string& id) { char* temp = nullptr; int ret = push_service_get_registration_id(m_handle, &temp); if (PUSH_SERVICE_ERROR_NONE != ret) { - return LogAndCreateResult(PushManagerCommon::ConvertPushError_2_4(ret), "Failed to get registration id", + return LogAndCreateResult(PushManagerCommon::ConvertPushError_2_4(ret), + "Failed to get registration id", ("push_service_get_registration_id failed (%d)", ret)); } id = temp; @@ -284,12 +279,14 @@ common::PlatformResult PushManager::getRegistrationId(std::string& id) { common::PlatformResult PushManager::getUnreadNotifications() { LoggerD("Enter"); if (!m_handle) { - return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Not connected with push service"); + return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, + "Not connected with push service"); } int ret = push_service_request_unread_notification(m_handle); if (PUSH_SERVICE_ERROR_NONE != ret) { - return LogAndCreateResult(PushManagerCommon::ConvertPushError_2_4(ret), "Failed to get unread notifications", + return LogAndCreateResult(PushManagerCommon::ConvertPushError_2_4(ret), + "Failed to get unread notifications", ("push_service_request_unread_notification failed (%d)", ret)); } return common::PlatformResult(ErrorCode::NO_ERROR); @@ -298,8 +295,7 @@ common::PlatformResult PushManager::getUnreadNotifications() { PlatformResult PushManager::getPushMessage(picojson::value* out) { LoggerD("Enter"); push_service_notification_h handle = nullptr; - int ret = push_service_app_control_to_notification(app_control_, operation_, - &handle); + int ret = push_service_app_control_to_notification(app_control_, operation_, &handle); if (PUSH_SERVICE_ERROR_NONE != ret) { if (PUSH_SERVICE_ERROR_NO_DATA == ret || PUSH_SERVICE_ERROR_NOT_SUPPORTED == ret) { @@ -323,7 +319,6 @@ PlatformResult PushManager::getPushMessage(picojson::value* out) { return common::PlatformResult(ErrorCode::NO_ERROR); } - void PushManager::onPushState(push_service_state_e state, const char* err, void* user_data) { LoggerD("Enter %d, err: %s", state, err); PushManager* impl = static_cast(user_data); @@ -350,7 +345,8 @@ void PushManager::onPushNotify(push_service_notification_h noti, void* user_data impl->m_listener->onPushNotify(noti); } -void PushManager::onApplicationRegister(push_service_result_e result, const char* msg, void* user_data) { +void PushManager::onApplicationRegister(push_service_result_e result, const char* msg, + void* user_data) { LoggerD("Enter"); PushManagerHolder* holder = static_cast(user_data); @@ -369,7 +365,7 @@ void PushManager::onApplicationRegister(push_service_result_e result, const char if (PUSH_SERVICE_RESULT_SUCCESS == result) { LoggerD("Success"); - char *temp = nullptr; + char* temp = nullptr; int ret = push_service_get_registration_id(impl->m_handle, &temp); if (PUSH_SERVICE_ERROR_NONE == ret) { LoggerD("Registration id retrieved"); @@ -392,7 +388,8 @@ void PushManager::onApplicationRegister(push_service_result_e result, const char } // TODO duplicated code due to different error handling in 2.4 API. remove on next release -void PushManager::onApplicationRegister_2_4(push_service_result_e result, const char* msg, void* user_data) { +void PushManager::onApplicationRegister_2_4(push_service_result_e result, const char* msg, + void* user_data) { LoggerD("Enter"); PushManagerHolder* holder = static_cast(user_data); @@ -411,7 +408,7 @@ void PushManager::onApplicationRegister_2_4(push_service_result_e result, const if (PUSH_SERVICE_RESULT_SUCCESS == result) { LoggerD("Success"); - char *temp = nullptr; + char* temp = nullptr; int ret = push_service_get_registration_id(impl->m_handle, &temp); if (PUSH_SERVICE_ERROR_NONE == ret) { LoggerD("Registration id retrieved"); @@ -436,70 +433,68 @@ void PushManager::onApplicationRegister_2_4(push_service_result_e result, const impl->m_listener->onPushRegister(callbackId, res, id); } -void PushManager::onDeregister(push_service_result_e result, const char* msg, - void* user_data) { - LoggerD("Enter"); - PushManagerHolder* holder = static_cast(user_data); - // automatically releases memory - PushManager* impl = dynamic_cast(holder->impl); - std::unique_ptr holder_ptr(holder); - double callbackId = holder->callbackId; - - if (nullptr == impl || !impl->m_listener) { - LoggerW("Listener not set, ignoring"); - return; - } - if (PUSH_SERVICE_RESULT_SUCCESS == result) { - impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); +void PushManager::onDeregister(push_service_result_e result, const char* msg, void* user_data) { + LoggerD("Enter"); + PushManagerHolder* holder = static_cast(user_data); + // automatically releases memory + PushManager* impl = dynamic_cast(holder->impl); + std::unique_ptr holder_ptr(holder); + double callbackId = holder->callbackId; + + if (nullptr == impl || !impl->m_listener) { + LoggerW("Listener not set, ignoring"); + return; + } + if (PUSH_SERVICE_RESULT_SUCCESS == result) { + impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); + } else { + PlatformResult res(ErrorCode::NO_ERROR); + if (PUSH_SERVICE_RESULT_TIMEOUT == result) { + res = LogAndCreateResult(ErrorCode::TIMEOUT_ERR, nullptr == msg ? "Timeout error" : msg); } else { - PlatformResult res(ErrorCode::NO_ERROR); - if (PUSH_SERVICE_RESULT_TIMEOUT == result) { - res = LogAndCreateResult(ErrorCode::TIMEOUT_ERR, nullptr == msg ? "Timeout error" : msg); - } else { - res = LogAndCreateResult(ErrorCode::ABORT_ERR, msg == nullptr ? "Abort error" : msg); - } - impl->m_listener->onDeregister(callbackId, res); + res = LogAndCreateResult(ErrorCode::ABORT_ERR, msg == nullptr ? "Abort error" : msg); } + impl->m_listener->onDeregister(callbackId, res); + } } // TODO duplicated code due to different error handling in 2.4 API. remove on next release -void PushManager::onDeregister_2_4(push_service_result_e result, const char* msg, - void* user_data) { - LoggerD("Enter"); - PushManagerHolder* holder = static_cast(user_data); - // automatically releases memory - PushManager* impl = dynamic_cast(holder->impl); - std::unique_ptr holder_ptr(holder); - double callbackId = holder->callbackId; - - if (nullptr == impl || !impl->m_listener) { - LoggerW("Listener not set, ignoring"); - return; - } - if (PUSH_SERVICE_RESULT_SUCCESS == result) { - impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); - } else { - impl->m_listener->onDeregister(callbackId, LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - msg == nullptr ? "Unknown error" : msg)); - } +void PushManager::onDeregister_2_4(push_service_result_e result, const char* msg, void* user_data) { + LoggerD("Enter"); + PushManagerHolder* holder = static_cast(user_data); + // automatically releases memory + PushManager* impl = dynamic_cast(holder->impl); + std::unique_ptr holder_ptr(holder); + double callbackId = holder->callbackId; + + if (nullptr == impl || !impl->m_listener) { + LoggerW("Listener not set, ignoring"); + return; + } + if (PUSH_SERVICE_RESULT_SUCCESS == result) { + impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); + } else { + impl->m_listener->onDeregister( + callbackId, + LogAndCreateResult(ErrorCode::UNKNOWN_ERR, msg == nullptr ? "Unknown error" : msg)); + } } gboolean PushManager::onFakeDeregister_2_4(gpointer user_data) { - LoggerD("Enter"); - PushManagerHolder* holder = static_cast(user_data); - // automatically releases memory - std::unique_ptr holder_ptr(holder); - PushManager* impl = dynamic_cast(holder->impl); - double callbackId = holder->callbackId; - - if (nullptr == impl || !impl->m_listener) { - LoggerW("Listener not set, ignoring"); - return G_SOURCE_REMOVE; - } - impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); + LoggerD("Enter"); + PushManagerHolder* holder = static_cast(user_data); + // automatically releases memory + std::unique_ptr holder_ptr(holder); + PushManager* impl = dynamic_cast(holder->impl); + double callbackId = holder->callbackId; + + if (nullptr == impl || !impl->m_listener) { + LoggerW("Listener not set, ignoring"); return G_SOURCE_REMOVE; + } + impl->m_listener->onDeregister(callbackId, PlatformResult(ErrorCode::NO_ERROR)); + return G_SOURCE_REMOVE; } } // namespace push } // namespace extension - diff --git a/src/push/push_manager.h b/src/push/push_manager.h index dc086be..d176933 100644 --- a/src/push/push_manager.h +++ b/src/push/push_manager.h @@ -17,11 +17,11 @@ #ifndef SRC_PUSH_PUSH_MANAGER_H_ #define SRC_PUSH_PUSH_MANAGER_H_ -#include #include +#include +#include #include #include -#include #include "common/platform_result.h" #include "push_manager_common.h" @@ -30,7 +30,7 @@ namespace push { class PushManager { public: - PushManager(EventListener* listener); + PushManager(EventListener *listener); virtual ~PushManager(); common::PlatformResult connectService(); @@ -43,7 +43,7 @@ class PushManager { common::PlatformResult unregisterApplication(double callbackId); common::PlatformResult getRegistrationId(std::string &id); common::PlatformResult getUnreadNotifications(); - common::PlatformResult getPushMessage(picojson::value* out); + common::PlatformResult getPushMessage(picojson::value *out); private: void initPkgId(); @@ -53,24 +53,20 @@ class PushManager { bool checkRegistered_2_4(); static gboolean onFakeDeregister_2_4(gpointer user_data); static void onApplicationRegister_2_4(push_service_result_e result, const char *msg, - void *user_data); - static void onDeregister_2_4(push_service_result_e result, const char *msg, - void *user_data); + void *user_data); + static void onDeregister_2_4(push_service_result_e result, const char *msg, void *user_data); ///////////////////////////////////////////// - static void onPushState(push_service_state_e state, const char *err, - void *user_data); + static void onPushState(push_service_state_e state, const char *err, void *user_data); static void onPushNotify(push_service_notification_h noti, void *user_data); - static void onApplicationRegister(push_service_result_e result, const char *msg, - void *user_data); - static void onDeregister(push_service_result_e result, const char *msg, - void *user_data); + static void onApplicationRegister(push_service_result_e result, const char *msg, void *user_data); + static void onDeregister(push_service_result_e result, const char *msg, void *user_data); - EventListener* m_listener; + EventListener *m_listener; push_service_connection_h m_handle; std::string m_pkgId; app_control_h app_control_; - char* operation_; + char *operation_; // TODO remove on next release - 2.4 API only bool m_ignoreNotificationEvents; @@ -81,4 +77,3 @@ class PushManager { } // namespace extension #endif // SRC_PUSH_PUSH_MANAGER_H_ - diff --git a/src/push/push_manager_common.cc b/src/push/push_manager_common.cc index 863583e..c8feace 100644 --- a/src/push/push_manager_common.cc +++ b/src/push/push_manager_common.cc @@ -15,12 +15,12 @@ */ #include "push/push_manager_common.h" -#include -#include #include #include #include #include +#include +#include #include #include "common/extension.h" @@ -35,8 +35,8 @@ using common::ErrorCode; std::string PushManagerCommon::StateToString(push_service_state_e state) { LoggerD("Entered"); - switch(state) { - case PUSH_SERVICE_STATE_REGISTERED : + switch (state) { + case PUSH_SERVICE_STATE_REGISTERED: return "REGISTERED"; default: return "UNREGISTERED"; @@ -59,7 +59,8 @@ std::string PushManagerCommon::GetEncodedBundle() { return result; } -void PushManagerCommon::notificationToJson(push_service_notification_h noti, picojson::object* obj) { +void PushManagerCommon::notificationToJson(push_service_notification_h noti, + picojson::object* obj) { LoggerD("Enter"); char* temp = nullptr; @@ -153,7 +154,7 @@ ErrorCode PushManagerCommon::ConvertPushError(int e) { LoggerD("Enter"); ErrorCode error; - switch(e) { + switch (e) { case PUSH_SERVICE_ERROR_NONE: error = ErrorCode::NO_ERROR; break; @@ -175,7 +176,7 @@ ErrorCode PushManagerCommon::ConvertPushError_2_4(int e) { LoggerD("Enter"); ErrorCode error; - switch(e) { + switch (e) { case PUSH_SERVICE_ERROR_NONE: error = ErrorCode::NO_ERROR; break; @@ -194,7 +195,5 @@ ErrorCode PushManagerCommon::ConvertPushError_2_4(int e) { return error; } - } // namespace push } // namespace extension - diff --git a/src/push/push_manager_common.h b/src/push/push_manager_common.h index 1dfbf99..db4bbdd 100644 --- a/src/push/push_manager_common.h +++ b/src/push/push_manager_common.h @@ -17,11 +17,11 @@ #ifndef SRC_PUSH_PUSH_MANAGER_COMMON_H_ #define SRC_PUSH_PUSH_MANAGER_COMMON_H_ -#include #include +#include +#include #include #include -#include #include "common/platform_result.h" namespace extension { @@ -29,26 +29,25 @@ namespace push { class EventListener { public: - virtual void onPushState(push_service_state_e state, common::PlatformResult result) = 0; - virtual void onPushNotify(push_service_notification_h noti) = 0; - virtual void onPushRegister(double callbackId, - common::PlatformResult result, const std::string& id) = 0; - virtual void onDeregister(double callbackId, - common::PlatformResult result) = 0; - virtual ~EventListener() {} + virtual void onPushState(push_service_state_e state, common::PlatformResult result) = 0; + virtual void onPushNotify(push_service_notification_h noti) = 0; + virtual void onPushRegister(double callbackId, common::PlatformResult result, + const std::string& id) = 0; + virtual void onDeregister(double callbackId, common::PlatformResult result) = 0; + virtual ~EventListener() { + } }; class PushManagerCommon { - public : - static std::string StateToString(push_service_state_e state); - static std::string GetEncodedBundle(); - static void notificationToJson(push_service_notification_h noti, picojson::object* obj); - static common::ErrorCode ConvertPushError(int e); - static common::ErrorCode ConvertPushError_2_4(int e); + public: + static std::string StateToString(push_service_state_e state); + static std::string GetEncodedBundle(); + static void notificationToJson(push_service_notification_h noti, picojson::object* obj); + static common::ErrorCode ConvertPushError(int e); + static common::ErrorCode ConvertPushError_2_4(int e); }; } // namespace push } // namespace extension #endif // SRC_PUSH_PUSH_MANAGER_COMMON_H_ - diff --git a/src/radio/radio_extension.h b/src/radio/radio_extension.h index b3c6cda..27a78df 100644 --- a/src/radio/radio_extension.h +++ b/src/radio/radio_extension.h @@ -28,5 +28,4 @@ class RadioExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif //RADIO_RADIO_EXTENSION_H_ - +#endif // RADIO_RADIO_EXTENSION_H_ diff --git a/src/radio/radio_instance.cc b/src/radio/radio_instance.cc index 6e21874..d506196 100644 --- a/src/radio/radio_instance.cc +++ b/src/radio/radio_instance.cc @@ -28,14 +28,12 @@ namespace radio { using namespace common; using namespace extension::radio; -RadioInstance::RadioInstance() - : manager_(*this) { +RadioInstance::RadioInstance() : manager_(*this) { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&RadioInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&RadioInstance::x, this, _1, _2)); REGISTER_SYNC("FMRadio_Start", Start); REGISTER_SYNC("FMRadio_Stop", Stop); @@ -49,14 +47,13 @@ RadioInstance::RadioInstance() REGISTER_SYNC("FMRadio_RadioStateGetter", StateGetter); REGISTER_SYNC("FMRadio_MuteSetter", MuteSetter); REGISTER_SYNC("FMRadio_MuteGetter", MuteGetter); - #undef REGISTER_SYNC - #define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&RadioInstance::x, this, _1, _2)); +#undef REGISTER_SYNC +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&RadioInstance::x, this, _1, _2)); REGISTER_ASYNC("FMRadio_SeekUp", SeekUp); REGISTER_ASYNC("FMRadio_SeekDown", SeekDown); REGISTER_ASYNC("FMRadio_ScanStart", ScanStart); REGISTER_ASYNC("FMRadio_ScanStop", ScanStop); - #undef REGISTER_ASYNC +#undef REGISTER_ASYNC LoggerD("RadioInstance()"); } @@ -65,39 +62,33 @@ RadioInstance::~RadioInstance() { LoggerD("Enter"); } -void RadioInstance::MuteGetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::MuteGetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); ReportSuccess(picojson::value(manager_.IsMuted()), out); } -void RadioInstance::MuteSetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::MuteSetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); manager_.SetMute(args.get("mute").get()); ReportSuccess(out); } -void RadioInstance::AntennaGetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::AntennaGetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); ReportSuccess(picojson::value(manager_.HasAntenna()), out); } -void RadioInstance::StateGetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::StateGetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); ReportSuccess(picojson::value(manager_.GetState()), out); } -void RadioInstance::FrequencyGetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::FrequencyGetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); ReportSuccess(picojson::value(manager_.GetFrequency()), out); } -void RadioInstance::SignalStrengthGetter(const picojson::value& args, - picojson::object& out) { +void RadioInstance::SignalStrengthGetter(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); ReportSuccess(picojson::value(manager_.GetSignalStrength()), out); } @@ -108,8 +99,7 @@ void RadioInstance::SeekUp(const picojson::value& args, picojson::object& out) { ReportSuccess(out); } -void RadioInstance::SeekDown(const picojson::value& args, - picojson::object& out) { +void RadioInstance::SeekDown(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); manager_.SeekDown(args.get("callbackId").get()); ReportSuccess(out); @@ -139,15 +129,13 @@ void RadioInstance::Stop(const picojson::value& args, picojson::object& out) { } } -void RadioInstance::ScanStart(const picojson::value& args, - picojson::object& out) { +void RadioInstance::ScanStart(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); manager_.ScanStart(args.get("callbackId").get()); ReportSuccess(out); } -void RadioInstance::ScanStop(const picojson::value& args, - picojson::object& out) { +void RadioInstance::ScanStop(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); manager_.ScanStop(args.get("callbackId").get()); ReportSuccess(out); @@ -179,8 +167,7 @@ void RadioInstance::UnsetFMRadioInterruptedListener(const picojson::value& args, } } -void RadioInstance::SetAntennaChangeListener(const picojson::value& args, - picojson::object& out) { +void RadioInstance::SetAntennaChangeListener(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); PlatformResult result = manager_.SetAntennaChangeListener(); @@ -192,8 +179,7 @@ void RadioInstance::SetAntennaChangeListener(const picojson::value& args, } } -void RadioInstance::UnsetAntennaChangeListener(const picojson::value& args, - picojson::object& out) { +void RadioInstance::UnsetAntennaChangeListener(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); PlatformResult result = manager_.UnsetAntennaChangeListener(); @@ -205,5 +191,5 @@ void RadioInstance::UnsetAntennaChangeListener(const picojson::value& args, } } -} // namespace radio -} // namespace extension +} // namespace radio +} // namespace extension diff --git a/src/radio/radio_instance.h b/src/radio/radio_instance.h index 4784906..93ebf59 100644 --- a/src/radio/radio_instance.h +++ b/src/radio/radio_instance.h @@ -51,7 +51,7 @@ class RadioInstance : public common::ParsedInstance { FMRadioManager manager_; }; -} // namespace radio -} // namespace extension +} // namespace radio +} // namespace extension #endif diff --git a/src/radio/radio_manager.cc b/src/radio/radio_manager.cc old mode 100755 new mode 100644 index d94f4e9..f348b37 --- a/src/radio/radio_manager.cc +++ b/src/radio/radio_manager.cc @@ -16,12 +16,12 @@ #include "radio_manager.h" -#include -#include -#include #include #include +#include #include +#include +#include #include "common/extension.h" #include "common/logger.h" @@ -44,9 +44,9 @@ const int kHighestFrequency = 108000; const char* RADIO_STATE_ERROR = "ERROR"; std::map radio_state = { - { RADIO_STATE_READY, "READY" }, - { RADIO_STATE_PLAYING, "PLAYING" }, - { RADIO_STATE_SCANNING, "SCANNING" }, + {RADIO_STATE_READY, "READY"}, + {RADIO_STATE_PLAYING, "PLAYING"}, + {RADIO_STATE_SCANNING, "SCANNING"}, }; static const double FREQ_LOWER = 87.5; @@ -88,7 +88,9 @@ PlatformResult CheckError(const std::string& str, int err) { string TranslateInterruptedCode(int code) { LoggerD("Enter"); -#define STRINGIFY(c) case c: return #c +#define STRINGIFY(c) \ + case c: \ + return #c switch (code) { STRINGIFY(RADIO_INTERRUPTED_BY_MEDIA); STRINGIFY(RADIO_INTERRUPTED_BY_CALL); @@ -98,7 +100,8 @@ string TranslateInterruptedCode(int code) { STRINGIFY(RADIO_INTERRUPTED_BY_EMERGENCY); STRINGIFY(RADIO_INTERRUPTED_BY_RESUMABLE_MEDIA); STRINGIFY(RADIO_INTERRUPTED_BY_NOTIFICATION); - default: return "UNKNOWN_INTERRUPTED_ERROR_CODE"; + default: + return "UNKNOWN_INTERRUPTED_ERROR_CODE"; } #undef STRINGIFY } @@ -117,14 +120,12 @@ void RadioSeekCallback(int frequency, void* user_data) { RadioData* data = static_cast(user_data); if (frequency >= kLowestFrequency && frequency <= kHighestFrequency) { - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostResultCallbackSuccess, &data->manager_, - data->callback_id_)); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostResultCallbackSuccess, &data->manager_, data->callback_id_)); } else { - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostResultFailure, &data->manager_, - data->callback_id_, PlatformResult(ErrorCode::UNKNOWN_ERR, - "Unsupported frequency"))); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostResultFailure, &data->manager_, data->callback_id_, + PlatformResult(ErrorCode::UNKNOWN_ERR, "Unsupported frequency"))); } delete data; } @@ -139,8 +140,8 @@ void ScanStartCallback(int frequency, void* user_data) { auto& obj = event.get(); obj.insert(std::make_pair("frequency", picojson::value(ToMHz(frequency)))); obj.insert(std::make_pair("listenerId", picojson::value("FMRadio_Onfrequencyfound"))); - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostMessage, &data->manager_, event.serialize())); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostMessage, &data->manager_, event.serialize())); } void PostAsyncSuccess(FMRadioManager* manager, double callbackId, picojson::value* event) { @@ -163,25 +164,25 @@ void ScanCompleteCallback(void* user_data) { } obj.insert(std::make_pair("frequencies", picojson::value(frequencies))); - common::TaskQueue::GetInstance().Async(std::bind(&PostAsyncSuccess, - &data->manager_, data->callback_id_, event)); + common::TaskQueue::GetInstance().Async( + std::bind(&PostAsyncSuccess, &data->manager_, data->callback_id_, event)); data->manager_.SetScanData(nullptr); delete data; } -void ScanStopCallback(void *user_data) { +void ScanStopCallback(void* user_data) { LoggerD("Enter"); RadioData* data = static_cast(user_data); - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostResultCallbackSuccess, &data->manager_, data->callback_id_)); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostResultCallbackSuccess, &data->manager_, data->callback_id_)); delete data->manager_.GetScanData(); data->manager_.SetScanData(nullptr); delete data; } -void RadioInterruptedCallback(radio_interrupted_code_e code, void *user_data) { +void RadioInterruptedCallback(radio_interrupted_code_e code, void* user_data) { LoggerD("Enter"); picojson::value event{picojson::object()}; @@ -190,19 +191,17 @@ void RadioInterruptedCallback(radio_interrupted_code_e code, void *user_data) { obj.insert(std::make_pair("listenerId", picojson::value("FMRadio_Interrupted"))); if (code == RADIO_INTERRUPTED_COMPLETED) { - obj.insert( - std::make_pair("action", picojson::value("oninterruptfinished"))); + obj.insert(std::make_pair("action", picojson::value("oninterruptfinished"))); } else { obj.insert(std::make_pair("action", picojson::value("oninterrupted"))); obj.insert(std::make_pair("reason", picojson::value(TranslateInterruptedCode(code)))); } FMRadioManager* manager = static_cast(user_data); - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostMessage, manager, event.serialize())); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostMessage, manager, event.serialize())); } - void RadioAntennaCallback(runtime_info_key_e key, void* user_data) { LoggerD("Enter"); @@ -219,11 +218,11 @@ void RadioAntennaCallback(runtime_info_key_e key, void* user_data) { obj.insert(std::make_pair("listenerId", picojson::value("FMRadio_Antenna"))); FMRadioManager* manager = static_cast(user_data); - common::TaskQueue::GetInstance().Async(std::bind( - &FMRadioManager::PostMessage, manager, event.serialize())); + common::TaskQueue::GetInstance().Async( + std::bind(&FMRadioManager::PostMessage, manager, event.serialize())); } -} // namespace +} // namespace bool FMRadioManager::IsMuted() { LoggerD("Enter"); @@ -238,11 +237,11 @@ bool FMRadioManager::IsMuted() { return muted; } -RadioScanData *FMRadioManager::GetScanData() { +RadioScanData* FMRadioManager::GetScanData() { return this->scan_data; } -void FMRadioManager::SetScanData(RadioScanData *scan_data) { +void FMRadioManager::SetScanData(RadioScanData* scan_data) { this->scan_data = scan_data; } @@ -260,8 +259,7 @@ bool FMRadioManager::HasAntenna() { LoggerD("Enter"); bool connected = false; - const auto err = runtime_info_get_value_bool(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, - &connected); + const auto err = runtime_info_get_value_bool(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, &connected); if (RUNTIME_INFO_ERROR_NONE != err) { LoggerE("runtime_info_get_value_bool() failed: %d", err); @@ -327,9 +325,7 @@ double FMRadioManager::GetSignalStrength() { } FMRadioManager::FMRadioManager(RadioInstance& instance) - : instance_(instance), - radio_instance_(nullptr), - scan_data(nullptr) { + : instance_(instance), radio_instance_(nullptr), scan_data(nullptr) { LoggerD("Enter"); const auto err = radio_create(&radio_instance_); @@ -450,11 +446,9 @@ void FMRadioManager::ScanStart(double callback_id) { RadioScanData* user_data = new RadioScanData(*this); user_data->callback_id_ = callback_id; - err = radio_set_scan_completed_cb(radio_instance_, ScanCompleteCallback, - user_data); + err = radio_set_scan_completed_cb(radio_instance_, ScanCompleteCallback, user_data); if (RADIO_ERROR_NONE != err) { - PostResultFailure(callback_id, - GetPlatformResult("radio_set_scan_completed_cb", err)); + PostResultFailure(callback_id, GetPlatformResult("radio_set_scan_completed_cb", err)); delete user_data; return; } @@ -478,8 +472,7 @@ void FMRadioManager::ScanStop(double callback_id) { auto err = radio_unset_scan_completed_cb(radio_instance_); if (RADIO_ERROR_NONE != err) { LoggerE("Failed"); - PostResultFailure(callback_id, - GetPlatformResult("radio_unset_scan_completed_cb", err)); + PostResultFailure(callback_id, GetPlatformResult("radio_unset_scan_completed_cb", err)); delete user_data; delete this->scan_data; this->scan_data = nullptr; @@ -499,9 +492,7 @@ void FMRadioManager::ScanStop(double callback_id) { common::PlatformResult FMRadioManager::SetFMRadioInterruptedListener() { LoggerD("Enter"); - const auto err = radio_set_interrupted_cb(radio_instance_, - RadioInterruptedCallback, - this); + const auto err = radio_set_interrupted_cb(radio_instance_, RadioInterruptedCallback, this); return CheckError("radio_set_interrupted_cb", err); } @@ -515,10 +506,8 @@ common::PlatformResult FMRadioManager::UnsetFMRadioInterruptedListener() { common::PlatformResult FMRadioManager::SetAntennaChangeListener() { LoggerD("Enter"); - const auto err = runtime_info_set_changed_cb( - RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, - RadioAntennaCallback, - this); + const auto err = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, + RadioAntennaCallback, this); return CheckError("runtime_info_set_changed_cb", err); } @@ -559,6 +548,5 @@ void FMRadioManager::PostResultFailure(double callbackId, const PlatformResult& PostMessage(event.serialize()); } -} // namespace radio -} // namespace extension - +} // namespace radio +} // namespace extension diff --git a/src/radio/radio_manager.h b/src/radio/radio_manager.h old mode 100755 new mode 100644 index fd9ea34..e32611d --- a/src/radio/radio_manager.h +++ b/src/radio/radio_manager.h @@ -18,9 +18,9 @@ #define FMRADIO_FMRADIO_MANAGER_H_ #include +#include #include #include -#include #include #include @@ -53,8 +53,8 @@ class FMRadioManager { common::PlatformResult UnsetAntennaChangeListener(); bool IsMuted(); - RadioScanData *GetScanData(); - void SetScanData(RadioScanData *scan_data); + RadioScanData* GetScanData(); + void SetScanData(RadioScanData* scan_data); void SetMute(bool mute); common::PlatformResult SetFrequency(double frequency); double GetFrequency(); @@ -70,13 +70,11 @@ class FMRadioManager { private: RadioInstance& instance_; radio_h radio_instance_; - RadioScanData *scan_data; + RadioScanData* scan_data; }; struct RadioData { - explicit RadioData(FMRadioManager& manager) - : manager_(manager), - callback_id_(0.0) { + explicit RadioData(FMRadioManager& manager) : manager_(manager), callback_id_(0.0) { } FMRadioManager& manager_; @@ -88,7 +86,7 @@ struct RadioScanData : public RadioData { std::vector frequencies_; }; -} // namespace radio -} // namespace extension +} // namespace radio +} // namespace extension -#endif // RADIO_RADIO_MANAGER_H_ +#endif // RADIO_RADIO_MANAGER_H_ diff --git a/src/secureelement/secureelement_extension.cc b/src/secureelement/secureelement_extension.cc index 0035898..e176927 100644 --- a/src/secureelement/secureelement_extension.cc +++ b/src/secureelement/secureelement_extension.cc @@ -30,7 +30,8 @@ SecureElementExtension::SecureElementExtension() { SetJavaScriptAPI(kSource_secureelement_api); } -SecureElementExtension::~SecureElementExtension() {} +SecureElementExtension::~SecureElementExtension() { +} common::Instance* SecureElementExtension::CreateInstance() { return new extension::secureelement::SecureElementInstance(); diff --git a/src/secureelement/secureelement_extension.h b/src/secureelement/secureelement_extension.h index 377925f..0a4db24 100644 --- a/src/secureelement/secureelement_extension.h +++ b/src/secureelement/secureelement_extension.h @@ -20,12 +20,13 @@ #include "common/extension.h" class SecureElementExtension : public common::Extension { -public: - SecureElementExtension(); - virtual ~SecureElementExtension(); -private: - // common::Extension implementation. - virtual common::Instance* CreateInstance(); + public: + SecureElementExtension(); + virtual ~SecureElementExtension(); + + private: + // common::Extension implementation. + virtual common::Instance* CreateInstance(); }; #endif // SECUREELEMENT_SECUREELEMENT_EXTENSION_H_ diff --git a/src/secureelement/secureelement_instance.cc b/src/secureelement/secureelement_instance.cc index 3455575..4dbff5e 100644 --- a/src/secureelement/secureelement_instance.cc +++ b/src/secureelement/secureelement_instance.cc @@ -16,11 +16,11 @@ #include "secureelement/secureelement_instance.h" -#include #include +#include -#include "common/tools.h" #include "common/scope_exit.h" +#include "common/tools.h" namespace extension { namespace secureelement { @@ -66,7 +66,7 @@ TizenResult ConvertErrorCode(int error) { } } -void SecureElementEventCb(int reader, smartcard_reader_event_type_e event_type, void *user_data) { +void SecureElementEventCb(int reader, smartcard_reader_event_type_e event_type, void* user_data) { ScopeLogger(); std::string action = ""; @@ -101,18 +101,15 @@ void SecureElementEventCb(int reader, smartcard_reader_event_type_e event_type, instance->Instance::PostMessage(instance, result.serialize().c_str()); } -} //namespace +} // namespace -SecureElementInstance::SecureElementInstance() : - is_initialized_(false), - is_listener_set_(false) { +SecureElementInstance::SecureElementInstance() : is_initialized_(false), is_listener_set_(false) { ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SecureElementInstance::x, this, _1)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&SecureElementInstance::x, this, _1)); REGISTER_SYNC("SEService_registerSEListener", RegisterSEListener); REGISTER_SYNC("SEService_unregisterSEListener", UnregisterSEListener); @@ -128,8 +125,7 @@ SecureElementInstance::SecureElementInstance() : REGISTER_SYNC("SEChannel_getSelectResponse", GetSelectResponse); #undef REGISTER_SYNC -#define REGISTER(c,x) \ - RegisterHandler(c, std::bind(&SecureElementInstance::x, this, _1, _2)); +#define REGISTER(c, x) RegisterHandler(c, std::bind(&SecureElementInstance::x, this, _1, _2)); REGISTER("SEService_getReaders", GetReaders); REGISTER("SEReader_openSession", OpenSession); @@ -151,7 +147,8 @@ SecureElementInstance::~SecureElementInstance() { } // Service methods -TizenResult SecureElementInstance::GetReaders(picojson::object const& args, const common::AsyncToken& token) { +TizenResult SecureElementInstance::GetReaders(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeSecureElement); @@ -293,7 +290,8 @@ TizenResult SecureElementInstance::IsPresent(picojson::object const& args) { return TizenSuccess(picojson::value(is_present)); } -TizenResult SecureElementInstance::OpenSession(picojson::object const& args, const common::AsyncToken& token) { +TizenResult SecureElementInstance::OpenSession(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeSecureElement); @@ -356,7 +354,8 @@ TizenResult SecureElementInstance::IsBasicChannel(int channel, picojson::value& return TizenSuccess(val); } -TizenResult SecureElementInstance::OpenBasicChannel(picojson::object const& args, const common::AsyncToken& token) { +TizenResult SecureElementInstance::OpenBasicChannel(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeSecureElement); @@ -372,7 +371,7 @@ TizenResult SecureElementInstance::OpenBasicChannel(picojson::object const& args size_t v_aid_size = v_aid.size(); unsigned char* aid = new unsigned char[v_aid_size]; SCOPE_EXIT { - delete [] aid; + delete[] aid; }; for (size_t i = 0; i < v_aid_size; i++) { @@ -399,7 +398,8 @@ TizenResult SecureElementInstance::OpenBasicChannel(picojson::object const& args return TizenSuccess(); } -TizenResult SecureElementInstance::OpenLogicalChannel(picojson::object const& args, const common::AsyncToken& token) { +TizenResult SecureElementInstance::OpenLogicalChannel(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeSecureElement); @@ -415,7 +415,7 @@ TizenResult SecureElementInstance::OpenLogicalChannel(picojson::object const& ar size_t v_aid_size = v_aid.size(); unsigned char* aid = new unsigned char[v_aid_size]; SCOPE_EXIT { - delete [] aid; + delete[] aid; }; for (size_t i = 0; i < v_aid_size; i++) { @@ -530,7 +530,8 @@ TizenResult SecureElementInstance::CloseChannel(picojson::object const& args) { return TizenSuccess(); } -TizenResult SecureElementInstance::Transmit(picojson::object const& args, const common::AsyncToken& token) { +TizenResult SecureElementInstance::Transmit(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeSecureElement); @@ -544,7 +545,7 @@ TizenResult SecureElementInstance::Transmit(picojson::object const& args, const size_t v_cmd_size = v_cmd.size(); unsigned char* cmd = new unsigned char[v_cmd_size]; SCOPE_EXIT { - delete [] cmd; + delete[] cmd; }; for (size_t i = 0; i < v_cmd_size; i++) { @@ -610,5 +611,5 @@ TizenResult SecureElementInstance::GetSelectResponse(picojson::object const& arg return TizenSuccess(response); } -} // namespace secureelement -} // namespace extension +} // namespace secureelement +} // namespace extension diff --git a/src/secureelement/secureelement_instance.h b/src/secureelement/secureelement_instance.h index d4e1295..0a08b31 100644 --- a/src/secureelement/secureelement_instance.h +++ b/src/secureelement/secureelement_instance.h @@ -22,46 +22,48 @@ namespace extension { namespace secureelement { -class SecureElementInstance: public common::TizenInstance { -public: - SecureElementInstance(); - virtual ~SecureElementInstance(); +class SecureElementInstance : public common::TizenInstance { + public: + SecureElementInstance(); + virtual ~SecureElementInstance(); -private: - /* Service methods */ - common::TizenResult GetReaders(picojson::object const& args, const common::AsyncToken& token); - common::TizenResult RegisterSEListener(picojson::object const& args); - common::TizenResult UnregisterSEListener(picojson::object const& args); - common::TizenResult Shutdown(picojson::object const& args); + private: + /* Service methods */ + common::TizenResult GetReaders(picojson::object const& args, const common::AsyncToken& token); + common::TizenResult RegisterSEListener(picojson::object const& args); + common::TizenResult UnregisterSEListener(picojson::object const& args); + common::TizenResult Shutdown(picojson::object const& args); - /* Reader methods */ - common::TizenResult GetName(picojson::object const& args); - common::TizenResult IsPresent(picojson::object const& args); - common::TizenResult OpenSession(picojson::object const& args, const common::AsyncToken& token); - common::TizenResult CloseSessions(picojson::object const& args); + /* Reader methods */ + common::TizenResult GetName(picojson::object const& args); + common::TizenResult IsPresent(picojson::object const& args); + common::TizenResult OpenSession(picojson::object const& args, const common::AsyncToken& token); + common::TizenResult CloseSessions(picojson::object const& args); - /* Session methods */ - common::TizenResult IsBasicChannel(int channel, picojson::value& val); - common::TizenResult OpenBasicChannel(picojson::object const& args, const common::AsyncToken& token); - common::TizenResult OpenLogicalChannel(picojson::object const& args, const common::AsyncToken& token); - common::TizenResult GetATR(picojson::object const& args); - common::TizenResult IsSessionClosed(picojson::object const& args); - common::TizenResult CloseSession(picojson::object const& args); - common::TizenResult CloseChannels(picojson::object const& args); + /* Session methods */ + common::TizenResult IsBasicChannel(int channel, picojson::value& val); + common::TizenResult OpenBasicChannel(picojson::object const& args, + const common::AsyncToken& token); + common::TizenResult OpenLogicalChannel(picojson::object const& args, + const common::AsyncToken& token); + common::TizenResult GetATR(picojson::object const& args); + common::TizenResult IsSessionClosed(picojson::object const& args); + common::TizenResult CloseSession(picojson::object const& args); + common::TizenResult CloseChannels(picojson::object const& args); - /* Channel methods */ - common::TizenResult CloseChannel(picojson::object const& args); - common::TizenResult Transmit(picojson::object const& args, const common::AsyncToken& token); - common::TizenResult GetSelectResponse(picojson::object const& args); + /* Channel methods */ + common::TizenResult CloseChannel(picojson::object const& args); + common::TizenResult Transmit(picojson::object const& args, const common::AsyncToken& token); + common::TizenResult GetSelectResponse(picojson::object const& args); - common::TizenResult Deinitialize(); - common::TizenResult UnregisterListener(); + common::TizenResult Deinitialize(); + common::TizenResult UnregisterListener(); - bool is_initialized_; - bool is_listener_set_; + bool is_initialized_; + bool is_listener_set_; }; -} // namespace secureelement -} // namespace extension +} // namespace secureelement +} // namespace extension -#endif // SECUREELEMENT_SECUREELEMENT_INSTANCE_H_ +#endif // SECUREELEMENT_SECUREELEMENT_INSTANCE_H_ diff --git a/src/sensor/sensor_extension.cc b/src/sensor/sensor_extension.cc index e9b165b..a1e1426 100644 --- a/src/sensor/sensor_extension.cc +++ b/src/sensor/sensor_extension.cc @@ -29,7 +29,8 @@ SensorExtension::SensorExtension() { SetJavaScriptAPI(kSource_sensor_api); } -SensorExtension::~SensorExtension() {} +SensorExtension::~SensorExtension() { +} common::Instance* SensorExtension::CreateInstance() { return new extension::sensor::SensorInstance(); diff --git a/src/sensor/sensor_extension.h b/src/sensor/sensor_extension.h index 2eb03d8..20da2d8 100644 --- a/src/sensor/sensor_extension.h +++ b/src/sensor/sensor_extension.h @@ -28,4 +28,4 @@ class SensorExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // SENSOR_SENSOR_EXTENSION_H_ +#endif // SENSOR_SENSOR_EXTENSION_H_ diff --git a/src/sensor/sensor_instance.cc b/src/sensor/sensor_instance.cc index ddacd9a..1165487 100644 --- a/src/sensor/sensor_instance.cc +++ b/src/sensor/sensor_instance.cc @@ -16,8 +16,8 @@ #include "sensor/sensor_instance.h" -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" namespace extension { @@ -25,21 +25,18 @@ namespace sensor { using namespace common; -SensorInstance::SensorInstance() - : service_(*this) { +SensorInstance::SensorInstance() : service_(*this) { LoggerD("Entered"); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SensorInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&SensorInstance::x, this, _1, _2)); REGISTER_SYNC("SensorService_getAvailableSensors", GetAvailableSensors); REGISTER_SYNC("Sensor_stop", SensorStop); REGISTER_SYNC("Sensor_setChangeListener", SensorSetChangeListener); REGISTER_SYNC("Sensor_unsetChangeListener", SensorUnsetChangeListener); #undef REGISTER_SYNC -#define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SensorInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&SensorInstance::x, this, _1, _2)); REGISTER_ASYNC("Sensor_start", SensorStart); REGISTER_ASYNC("Sensor_getData", SensorGetData); REGISTER_ASYNC("Sensor_getSensorHardwareInfo", GetSensorHardwareInfo); @@ -87,5 +84,5 @@ void SensorInstance::GetSensorHardwareInfo(const picojson::value& args, picojson service_.GetSensorHardwareInfo(args, out); } -} // namespace sensor -} // namespace extension +} // namespace sensor +} // namespace extension diff --git a/src/sensor/sensor_instance.h b/src/sensor/sensor_instance.h index 9aec82f..5abc2a7 100644 --- a/src/sensor/sensor_instance.h +++ b/src/sensor/sensor_instance.h @@ -41,7 +41,7 @@ class SensorInstance : public common::ParsedInstance { SensorService service_; }; -} // namespace sensor -} // namespace extension +} // namespace sensor +} // namespace extension -#endif // SENSOR_SENSOR_INSTANCE_H_ +#endif // SENSOR_SENSOR_INSTANCE_H_ diff --git a/src/sensor/sensor_service.cc b/src/sensor/sensor_service.cc old mode 100755 new mode 100644 index 98f6586..28a1951 --- a/src/sensor/sensor_service.cc +++ b/src/sensor/sensor_service.cc @@ -16,9 +16,9 @@ #include "sensor_service.h" -#include #include #include +#include #include "common/logger.h" #include "common/optional.h" @@ -36,10 +36,10 @@ namespace extension { namespace sensor { namespace { -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ } static std::map type_to_string_map; @@ -184,7 +184,7 @@ std::string GetSensorErrorMessage(const int error_code) { } } -PlatformResult GetSensorPlatformResult(const int error_code, const std::string &hint) { +PlatformResult GetSensorPlatformResult(const int error_code, const std::string& hint) { LoggerD("Entered"); std::string message = hint + " : " + GetSensorErrorMessage(error_code); @@ -212,27 +212,31 @@ bool MagneticEventComparator(sensor_event_s* l, sensor_event_s* r, const unsigne return DefaultEventComparator(l, r, value_count) ? l->accuracy == r->accuracy : false; } -} // namespace +} // namespace class SensorData { public: - typedef bool (*EventComparator)(sensor_event_s* l, sensor_event_s* r, const unsigned int value_count); + typedef bool (*EventComparator)(sensor_event_s* l, sensor_event_s* r, + const unsigned int value_count); - SensorData(SensorInstance& instance, sensor_type_e type_enum, - const std::string& name, const unsigned int sensor_value_count, EventComparator comparator = - DefaultEventComparator); + SensorData(SensorInstance& instance, sensor_type_e type_enum, const std::string& name, + const unsigned int sensor_value_count, + EventComparator comparator = DefaultEventComparator); virtual ~SensorData(); PlatformResult IsSupported(bool* supported); - virtual PlatformResult Start(const std::shared_ptr& result, - const std::function&)>& work); + virtual PlatformResult Start( + const std::shared_ptr& result, + const std::function&)>& work); virtual PlatformResult Stop(); virtual PlatformResult SetChangeListener(unsigned int interval, unsigned int batch_latency); virtual PlatformResult UnsetChangeListener(); virtual PlatformResult GetSensorData(picojson::object* data); virtual PlatformResult GetHardwareInfo(picojson::object* data); - sensor_type_e type() const { return type_enum_; } + sensor_type_e type() const { + return type_enum_; + } bool is_supported(); bool UpdateEvent(sensor_event_s* event); @@ -258,16 +262,15 @@ class SensorData { std::vector> delayed_success_callbacks_; }; -SensorData::SensorData(SensorInstance& instance, sensor_type_e type_enum, - const std::string& name, const unsigned int sensor_value_count, - EventComparator comparator) +SensorData::SensorData(SensorInstance& instance, sensor_type_e type_enum, const std::string& name, + const unsigned int sensor_value_count, EventComparator comparator) : type_enum_(type_enum), comparator_(comparator), sensor_value_count_(sensor_value_count), handle_(nullptr), listener_(nullptr), - previous_event_{0,0,0,-FLT_MAX}, // setting dumb non-zero value to differ init value from - // "good" zero values from sensor + previous_event_{0, 0, 0, -FLT_MAX}, // setting dumb non-zero value to differ init value from + // "good" zero values from sensor instance_(instance), is_change_listener_set_(false) { type_to_string_map.insert(std::make_pair(type_enum, name)); @@ -299,9 +302,9 @@ void SensorData::SensorCallback(sensor_h sensor, sensor_event_s* event, void* us if (!that->delayed_success_callbacks_.empty()) { for_each(that->delayed_success_callbacks_.begin(), that->delayed_success_callbacks_.end(), [](std::function& callback) { - LoggerD("Calling delayed start succcess callback"); - callback(); - }); + LoggerD("Calling delayed start succcess callback"); + callback(); + }); that->delayed_success_callbacks_.erase(that->delayed_success_callbacks_.begin(), that->delayed_success_callbacks_.end()); if (!that->is_change_listener_set_) { @@ -332,16 +335,16 @@ PlatformResult SensorData::CheckInitialization() { LoggerD("initialization of handle and listener"); int ret = sensor_get_default_sensor(type_enum_, &handle_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get default sensor.", - ("sensor_get_default_sensor() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to get default sensor.", + ("sensor_get_default_sensor() error: %d, message: %s", ret, get_error_message(ret))); } ret = sensor_create_listener(handle_, &listener_); if (SENSOR_ERROR_NONE != ret) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create listener.", - ("sensor_create_listener() error: %d, message: %s", ret, get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, "Failed to create listener.", + ("sensor_create_listener() error: %d, message: %s", ret, get_error_message(ret))); } } return PlatformResult(ErrorCode::NO_ERROR); @@ -413,7 +416,8 @@ PlatformResult SensorData::AddDelayedStartSuccessCb(const std::function& if (!is_change_listener_set_) { LoggerD("Adding temporary listener by hand"); - int ret = sensor_listener_set_event_cb(listener_, 10, // as small interval as possible for tmp listener + int ret = sensor_listener_set_event_cb(listener_, + 10, // as small interval as possible for tmp listener SensorCallback, this); if (SENSOR_ERROR_NONE != ret) { LoggerE("sensor_listener_set_event_cb returned error: %d", ret); @@ -425,8 +429,9 @@ PlatformResult SensorData::AddDelayedStartSuccessCb(const std::function& return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SensorData::Start(const std::shared_ptr& result, - const std::function&)>& report_result) { +PlatformResult SensorData::Start( + const std::shared_ptr& result, + const std::function&)>& report_result) { LoggerD("Entered: %s", type_to_string_map[type()].c_str()); auto res = CheckInitialization(); @@ -435,13 +440,13 @@ PlatformResult SensorData::Start(const std::shared_ptr& result, return res; } - auto delayed_success_callback = [this, result, report_result] () { + auto delayed_success_callback = [this, result, report_result]() { LoggerD("Delayed success callback"); ReportSuccess(result->get()); report_result(result); }; res = AddDelayedStartSuccessCb(delayed_success_callback); - if(!res) { + if (!res) { return res; } @@ -472,8 +477,8 @@ PlatformResult SensorData::Stop() { } // reseting delayed success callbacks flag and saved event values - previous_event_ = {0,0,0,-FLT_MAX}; // setting dumb non-zero value to differ init value from - // "good" zero values from sensor + previous_event_ = {0, 0, 0, -FLT_MAX}; // setting dumb non-zero value to differ init value from + // "good" zero values from sensor delayed_success_callbacks_.erase(delayed_success_callbacks_.begin(), delayed_success_callbacks_.end()); @@ -493,7 +498,7 @@ PlatformResult SensorData::SetChangeListener(unsigned int interval, unsigned int int ret = SENSOR_ERROR_NONE; if (batch_latency > 0) { ret = sensor_listener_set_max_batch_latency(listener_, batch_latency); - if (SENSOR_ERROR_NONE != ret ) { + if (SENSOR_ERROR_NONE != ret) { LoggerE("sensor_listener_set_max_batch_latency : %d", ret); return GetSensorPlatformResult(ret, "Unable to set batchLatency"); } @@ -564,8 +569,8 @@ PlatformResult SensorData::GetHardwareInfo(picojson::object* data) { } sensor_type_e type = type_enum_; - char *vendor = nullptr; - char *name = nullptr; + char* vendor = nullptr; + char* name = nullptr; float min_range = 0; float max_range = 0; float resolution = 0; @@ -577,8 +582,8 @@ PlatformResult SensorData::GetHardwareInfo(picojson::object* data) { free(vendor); }; - auto native_result = [](int ret) -> PlatformResult{ - switch(ret){ + auto native_result = [](int ret) -> PlatformResult { + switch (ret) { case SENSOR_ERROR_IO_ERROR: return PlatformResult(ErrorCode::IO_ERR); @@ -643,15 +648,14 @@ PlatformResult SensorData::GetHardwareInfo(picojson::object* data) { return PlatformResult(ErrorCode::NO_ERROR); } - - class HrmSensorData : public SensorData { public: explicit HrmSensorData(SensorInstance& instance); virtual ~HrmSensorData(); - virtual PlatformResult Start(const std::shared_ptr& result, - const std::function&)>& work); + virtual PlatformResult Start( + const std::shared_ptr& result, + const std::function&)>& work); virtual PlatformResult Stop(); virtual PlatformResult SetChangeListener(unsigned int interval, unsigned int batch_latency); virtual PlatformResult UnsetChangeListener(); @@ -660,7 +664,7 @@ class HrmSensorData : public SensorData { private: void AddSensor(SensorData* sensor); - PlatformResult CallMember(PlatformResult (SensorData::*member) ()); + PlatformResult CallMember(PlatformResult (SensorData::*member)()); PlatformResult CallMember( PlatformResult (SensorData::*member)( const std::shared_ptr&, @@ -690,7 +694,7 @@ void HrmSensorData::AddSensor(SensorData* sensor) { hrm_sensors_.insert(std::make_pair(sensor->type(), std::shared_ptr(sensor))); } -PlatformResult HrmSensorData::CallMember(PlatformResult (SensorData::*member) ()) { +PlatformResult HrmSensorData::CallMember(PlatformResult (SensorData::*member)()) { LoggerD("Entered: %s", type_to_string_map[type()].c_str()); bool is_any_supported = false; for (const auto& sensor : hrm_sensors_) { @@ -758,8 +762,9 @@ PlatformResult HrmSensorData::IsSupportedImpl(bool* supported) const { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult HrmSensorData::Start(const std::shared_ptr& result, - const std::function&)>& work) { +PlatformResult HrmSensorData::Start( + const std::shared_ptr& result, + const std::function&)>& work) { LoggerD("Entered: %s", type_to_string_map[type()].c_str()); return CallMember(&SensorData::Start, result, work); } @@ -820,8 +825,7 @@ PlatformResult HrmSensorData::GetHardwareInfo(picojson::object* data) { return PlatformResult(ErrorCode::ABORT_ERR); } -SensorService::SensorService(SensorInstance& instance) - : instance_(instance) { +SensorService::SensorService(SensorInstance& instance) : instance_(instance) { LoggerD("Entered"); // For amount of retrieved values from sensors please refer to native guides. @@ -833,7 +837,8 @@ SensorService::SensorService(SensorInstance& instance) AddSensor(new HrmSensorData(instance)); AddSensor(new SensorData(instance, SENSOR_GRAVITY, "GRAVITY", 3)); AddSensor(new SensorData(instance, SENSOR_GYROSCOPE, "GYROSCOPE", 3)); - AddSensor(new SensorData(instance, SENSOR_GYROSCOPE_ROTATION_VECTOR, "GYROSCOPE_ROTATION_VECTOR", 4)); + AddSensor( + new SensorData(instance, SENSOR_GYROSCOPE_ROTATION_VECTOR, "GYROSCOPE_ROTATION_VECTOR", 4)); AddSensor(new SensorData(instance, SENSOR_LINEAR_ACCELERATION, "LINEAR_ACCELERATION", 3)); AddSensor(new SensorData(instance, SENSOR_GEOMAGNETIC_UNCALIBRATED, "MAGNETIC_UNCALIBRATED", 6)); AddSensor(new SensorData(instance, SENSOR_GYROSCOPE_UNCALIBRATED, "GYROSCOPE_UNCALIBRATED", 6)); @@ -855,7 +860,8 @@ void SensorService::GetAvailableSensors(picojson::object& out) { for (const auto& sensor : sensors_) { auto res = sensor.second->IsSupported(&is_supported); if (!res) { - LogAndReportError(res, &out, ("Failed to check if sensor is supported: %s", type_to_string_map[sensor.first].c_str())); + LogAndReportError(res, &out, ("Failed to check if sensor is supported: %s", + type_to_string_map[sensor.first].c_str())); return; } @@ -873,37 +879,38 @@ void SensorService::SensorStart(const picojson::value& args, picojson::object& o int callback_id = static_cast(args.get("callbackId").get()); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; - LoggerD("input type: %s" , type_str.c_str()); + LoggerD("input type: %s", type_str.c_str()); sensor_type_e type_enum = string_to_type_map[type_str]; auto start_result = [this, callback_id](const std::shared_ptr& result) { LoggerD("Entered"); - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(&instance_, result->serialize().c_str()); }; - auto start = [this, type_enum, type_str, start_result](const std::shared_ptr& result) { + auto start = [this, type_enum, type_str, + start_result](const std::shared_ptr& result) { LoggerD("Entered"); auto sensor_data = GetSensor(type_enum); if (!sensor_data) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Sensor data is null"), - &(result->get())); + &(result->get())); return; } PlatformResult res = sensor_data->Start(result, start_result); if (!res) { - LogAndReportError(res, &(result->get()), ("Failed to start sensor: %s", type_str.c_str())); + LogAndReportError(res, &(result->get()), + ("Failed to start sensor: %s", type_str.c_str())); start_result(result); } }; auto data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Async( - start, - data); + TaskQueue::GetInstance().Async(start, data); ReportSuccess(out); } @@ -911,7 +918,7 @@ void SensorService::SensorStop(const picojson::value& args, picojson::object& ou LoggerD("Entered"); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; - LoggerD("input type: %s" , type_str.c_str()); + LoggerD("input type: %s", type_str.c_str()); sensor_type_e type_enum = string_to_type_map[type_str]; @@ -934,10 +941,11 @@ void SensorService::SensorSetChangeListener(const picojson::value& args, picojso const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; const auto interval = args.contains(kInterval) ? args.get(kInterval).get() : 100.0; - const auto batch_latency = args.contains(kBatchLatency) ? args.get(kBatchLatency).get() : 0.0; + const auto batch_latency = + args.contains(kBatchLatency) ? args.get(kBatchLatency).get() : 0.0; - LoggerD("input type: %s" , type_str.c_str()); - LoggerD("interval: %f" , interval); + LoggerD("input type: %s", type_str.c_str()); + LoggerD("interval: %f", interval); sensor_type_e type_enum = string_to_type_map[type_str]; @@ -947,9 +955,11 @@ void SensorService::SensorSetChangeListener(const picojson::value& args, picojso return; } - PlatformResult res = sensor_data->SetChangeListener(static_cast(interval), static_cast(batch_latency)); + PlatformResult res = sensor_data->SetChangeListener(static_cast(interval), + static_cast(batch_latency)); if (!res) { - LogAndReportError(res, &out, ("Failed to set change listener for sensor: %s", type_str.c_str())); + LogAndReportError(res, &out, + ("Failed to set change listener for sensor: %s", type_str.c_str())); } else { ReportSuccess(out); } @@ -959,7 +969,7 @@ void SensorService::SensorUnsetChangeListener(const picojson::value& args, picoj LoggerD("Entered"); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; - LoggerD("input type: %s" , type_str.c_str()); + LoggerD("input type: %s", type_str.c_str()); sensor_type_e type_enum = string_to_type_map[type_str]; @@ -971,7 +981,8 @@ void SensorService::SensorUnsetChangeListener(const picojson::value& args, picoj PlatformResult res = sensor_data->UnsetChangeListener(); if (!res) { - LogAndReportError(res, &out, ("Failed to remove change listener for sensor: %s", type_str.c_str())); + LogAndReportError(res, &out, + ("Failed to remove change listener for sensor: %s", type_str.c_str())); } else { ReportSuccess(out); } @@ -1013,24 +1024,23 @@ void SensorService::GetSensorData(const picojson::value& args, picojson::object& PlatformResult res = sensor_data->GetSensorData(&object); if (!res) { - LogAndReportError(res, &object, ("Failed to read data for sensor: %s", type_to_string_map[sensor_type].c_str())); + LogAndReportError(res, &object, ("Failed to read data for sensor: %s", + type_to_string_map[sensor_type].c_str())); } else { ReportSuccess(object); } }; auto get_data_result = [this, callback_id](const std::shared_ptr& result) { - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(&instance_, result->serialize().c_str()); }; auto data = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - get_data, - get_data_result, - data); + TaskQueue::GetInstance().Queue(get_data, get_data_result, data); ReportSuccess(out); } @@ -1050,33 +1060,33 @@ void SensorService::GetSensorHardwareInfo(const picojson::value& args, picojson: auto sensor_data = this->GetSensor(sensor_type); if (!sensor_data) { - LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "Sensor data is null"), &(result->get())); + LogAndReportError(PlatformResult(ErrorCode::ABORT_ERR, "Sensor data is null"), + &(result->get())); return; } PlatformResult res = sensor_data->GetHardwareInfo(&object); if (!res) { - LogAndReportError(res, &object, ("Failed to read data for sensor: %s", type_to_string_map[sensor_type].c_str())); + LogAndReportError(res, &object, ("Failed to read data for sensor: %s", + type_to_string_map[sensor_type].c_str())); - }else { + } else { ReportSuccess(object); } }; - auto get_info_result = [this, callback_id](const std::shared_ptr& result){ - result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; + auto get_info_result = [this, callback_id](const std::shared_ptr& result) { + result->get()["callbackId"] = + picojson::value{static_cast(callback_id)}; Instance::PostMessage(&instance_, result->serialize().c_str()); }; auto info = std::shared_ptr{new picojson::value{picojson::object()}}; - TaskQueue::GetInstance().Queue( - get_info, - get_info_result, - info); + TaskQueue::GetInstance().Queue(get_info, get_info_result, info); ReportSuccess(out); } -} // namespace sensor -} // namespace extension +} // namespace sensor +} // namespace extension diff --git a/src/sensor/sensor_service.h b/src/sensor/sensor_service.h index 73b322e..72a04fc 100644 --- a/src/sensor/sensor_service.h +++ b/src/sensor/sensor_service.h @@ -51,7 +51,7 @@ class SensorService { SensorInstance& instance_; }; -} // namespace sensor -} // namespace extension +} // namespace sensor +} // namespace extension -#endif // SENSOR_SENSOR_SERVICE_H_ +#endif // SENSOR_SENSOR_SERVICE_H_ diff --git a/src/sound/sound_extension.cc b/src/sound/sound_extension.cc index 400cdf5..a9a9b20 100644 --- a/src/sound/sound_extension.cc +++ b/src/sound/sound_extension.cc @@ -30,7 +30,8 @@ SoundExtension::SoundExtension() { SetJavaScriptAPI(kSource_sound_api); } -SoundExtension::~SoundExtension() {} +SoundExtension::~SoundExtension() { +} common::Instance* SoundExtension::CreateInstance() { return new extension::sound::SoundInstance(); diff --git a/src/sound/sound_extension.h b/src/sound/sound_extension.h index 8b964c5..742022c 100644 --- a/src/sound/sound_extension.h +++ b/src/sound/sound_extension.h @@ -28,4 +28,4 @@ class SoundExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // SOUND_SOUND_EXTENSION_H_ +#endif // SOUND_SOUND_EXTENSION_H_ diff --git a/src/sound/sound_instance.cc b/src/sound/sound_instance.cc index 544d7fa..3b99ef3 100644 --- a/src/sound/sound_instance.cc +++ b/src/sound/sound_instance.cc @@ -18,10 +18,10 @@ #include -#include "common/picojson.h" #include "common/logger.h" -#include "common/tools.h" +#include "common/picojson.h" #include "common/platform_exception.h" +#include "common/tools.h" #include "sound_manager.h" namespace extension { @@ -31,20 +31,20 @@ namespace { // The privileges that required in Sound API const std::string kPrivilegeSound = "http://tizen.org/privilege/volume.set"; -} // namespace +} // namespace using namespace common; using namespace extension::sound; -SoundInstance::SoundInstance(): manager_(*this) { +SoundInstance::SoundInstance() : manager_(*this) { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; - #define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SoundInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&SoundInstance::x, this, _1, _2)); REGISTER_SYNC("SoundManager_setVolume", SoundManagerSetVolume); - REGISTER_SYNC("SoundManager_unsetSoundModeChangeListener", SoundManagerUnsetSoundModeChangeListener); + REGISTER_SYNC("SoundManager_unsetSoundModeChangeListener", + SoundManagerUnsetSoundModeChangeListener); REGISTER_SYNC("SoundManager_getVolume", SoundManagerGetVolume); REGISTER_SYNC("SoundManager_unsetVolumeChangeListener", SoundManagerUnsetVolumeChangeListener); REGISTER_SYNC("SoundManager_setSoundModeChangeListener", SoundManagerSetSoundModeChangeListener); @@ -56,21 +56,20 @@ SoundInstance::SoundInstance(): manager_(*this) { SoundManagerAddDeviceStateChangeListener); REGISTER_SYNC("SoundManager_removeDeviceStateChangeListener", SoundManagerRemoveDeviceStateChangeListener); - #undef REGISTER_SYNC +#undef REGISTER_SYNC } SoundInstance::~SoundInstance() { LoggerD("Enter"); } -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } -void SoundInstance::SoundManagerGetSoundMode(const picojson::value& args, - picojson::object& out) { +void SoundInstance::SoundManagerGetSoundMode(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); std::string sound_mode_type; PlatformResult status = manager_.GetSoundMode(&sound_mode_type); @@ -82,8 +81,7 @@ void SoundInstance::SoundManagerGetSoundMode(const picojson::value& args, } } -void SoundInstance::SoundManagerSetVolume(const picojson::value& args, - picojson::object& out) { +void SoundInstance::SoundManagerSetVolume(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeSound, &out); PlatformResult status = manager_.SetVolume(args.get()); @@ -95,13 +93,10 @@ void SoundInstance::SoundManagerSetVolume(const picojson::value& args, } } - -void SoundInstance::SoundManagerGetVolume(const picojson::value& args, - picojson::object& out) { +void SoundInstance::SoundManagerGetVolume(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); double volume; - PlatformResult status = - manager_.GetVolume(args.get(), &volume); + PlatformResult status = manager_.GetVolume(args.get(), &volume); if (status.IsSuccess()) { ReportSuccess(picojson::value(volume), out); @@ -110,7 +105,8 @@ void SoundInstance::SoundManagerGetVolume(const picojson::value& args, } } -void SoundInstance::SoundManagerSetSoundModeChangeListener(const picojson::value& args, picojson::object& out) { +void SoundInstance::SoundManagerSetSoundModeChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); PlatformResult status = manager_.SetSoundModeChangeListener(this); @@ -121,7 +117,8 @@ void SoundInstance::SoundManagerSetSoundModeChangeListener(const picojson::value } } -void SoundInstance::SoundManagerUnsetSoundModeChangeListener(const picojson::value& args, picojson::object& out) { +void SoundInstance::SoundManagerUnsetSoundModeChangeListener(const picojson::value& args, + picojson::object& out) { PlatformResult status = manager_.UnsetSoundModeChangeListener(); LoggerD("Enter"); @@ -133,8 +130,7 @@ void SoundInstance::SoundManagerUnsetSoundModeChangeListener(const picojson::val } } -void SoundInstance::OnSoundModeChange(const std::string& newmode) -{ +void SoundInstance::OnSoundModeChange(const std::string& newmode) { LoggerD("Enter"); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); @@ -145,9 +141,8 @@ void SoundInstance::OnSoundModeChange(const std::string& newmode) Instance::PostMessage(this, event.serialize().c_str()); } - -void SoundInstance::SoundManagerSetVolumeChangeListener( - const picojson::value& args, picojson::object& out) { +void SoundInstance::SoundManagerSetVolumeChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); PlatformResult status = manager_.SetVolumeChangeListener(); @@ -158,8 +153,8 @@ void SoundInstance::SoundManagerSetVolumeChangeListener( } } -void SoundInstance::SoundManagerUnsetVolumeChangeListener( - const picojson::value& args, picojson::object& out) { +void SoundInstance::SoundManagerUnsetVolumeChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); PlatformResult status = manager_.UnsetVolumeChangeListener(); @@ -170,23 +165,20 @@ void SoundInstance::SoundManagerUnsetVolumeChangeListener( } } -void SoundInstance::SoundManagerGetConnectedDeviceList( - const picojson::value& args, picojson::object& out) { - +void SoundInstance::SoundManagerGetConnectedDeviceList(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); manager_.GetDeviceList(SOUND_DEVICE_ALL_MASK, out); } -void SoundInstance::SoundManagerGetActivatedDeviceList( - const picojson::value& args, picojson::object& out) { - +void SoundInstance::SoundManagerGetActivatedDeviceList(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); manager_.GetDeviceList(SOUND_DEVICE_STATE_ACTIVATED_MASK, out); } -void SoundInstance::SoundManagerAddDeviceStateChangeListener( - const picojson::value& args, picojson::object& out) { - +void SoundInstance::SoundManagerAddDeviceStateChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); PlatformResult result = manager_.AddDeviceStateChangeListener(); @@ -197,9 +189,8 @@ void SoundInstance::SoundManagerAddDeviceStateChangeListener( } } -void SoundInstance::SoundManagerRemoveDeviceStateChangeListener( - const picojson::value& args, picojson::object& out) { - +void SoundInstance::SoundManagerRemoveDeviceStateChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Entered"); PlatformResult result = manager_.RemoveDeviceStateChangeListener(); @@ -212,5 +203,5 @@ void SoundInstance::SoundManagerRemoveDeviceStateChangeListener( #undef CHECK_EXIST -} // namespace sound -} // namespace extension +} // namespace sound +} // namespace extension diff --git a/src/sound/sound_instance.h b/src/sound/sound_instance.h index 700246e..32a4c00 100644 --- a/src/sound/sound_instance.h +++ b/src/sound/sound_instance.h @@ -39,15 +39,15 @@ class SoundInstance : public common::ParsedInstance, public SoundManagerSoundMod void SoundManagerGetConnectedDeviceList(const picojson::value& args, picojson::object& out); void SoundManagerGetActivatedDeviceList(const picojson::value& args, picojson::object& out); void SoundManagerAddDeviceStateChangeListener(const picojson::value& args, picojson::object& out); - void SoundManagerRemoveDeviceStateChangeListener( - const picojson::value& args, picojson::object& out); + void SoundManagerRemoveDeviceStateChangeListener(const picojson::value& args, + picojson::object& out); void OnSoundModeChange(const std::string& newmode); SoundManager manager_; }; -} // namespace sound -} // namespace extension +} // namespace sound +} // namespace extension -#endif // SOUND_SOUND_INSTANCE_H_ +#endif // SOUND_SOUND_INSTANCE_H_ diff --git a/src/sound/sound_manager.cc b/src/sound/sound_manager.cc index a55a3a7..794e9c4 100644 --- a/src/sound/sound_manager.cc +++ b/src/sound/sound_manager.cc @@ -16,22 +16,22 @@ #include "sound/sound_manager.h" -#include #include +#include #include -#include #include +#include #include "common/converter.h" #include "common/logger.h" +#include "common/scope_exit.h" #include "common/task-queue.h" #include "common/tools.h" -#include "common/scope_exit.h" -//This constant was originally defined in vconf.h. However, in tizen 3, it -//appears, it is removed (or defined only in vconf-internals.h) -//It is not clear, if it is final solution, or not. +// This constant was originally defined in vconf.h. However, in tizen 3, it +// appears, it is removed (or defined only in vconf-internals.h) +// It is not clear, if it is final solution, or not. #ifndef VCONF_OK #define VCONF_OK 0 #endif @@ -45,15 +45,11 @@ using namespace common; using namespace common::tools; const std::map SoundManager::platform_enum_map_ = { - {"SYSTEM", SOUND_TYPE_SYSTEM}, - {"NOTIFICATION", SOUND_TYPE_NOTIFICATION}, - {"ALARM", SOUND_TYPE_ALARM}, - {"MEDIA", SOUND_TYPE_MEDIA}, - {"VOICE", SOUND_TYPE_VOICE}, - {"RINGTONE", SOUND_TYPE_RINGTONE}}; - -PlatformResult SoundManager::StrToPlatformEnum(const std::string& key, - sound_type_e* sound_type) { + {"SYSTEM", SOUND_TYPE_SYSTEM}, {"NOTIFICATION", SOUND_TYPE_NOTIFICATION}, + {"ALARM", SOUND_TYPE_ALARM}, {"MEDIA", SOUND_TYPE_MEDIA}, + {"VOICE", SOUND_TYPE_VOICE}, {"RINGTONE", SOUND_TYPE_RINGTONE}}; + +PlatformResult SoundManager::StrToPlatformEnum(const std::string& key, sound_type_e* sound_type) { LoggerD("Enter"); if (platform_enum_map_.find(key) == platform_enum_map_.end()) { std::string message = "Platform enum value not found for key " + key; @@ -65,8 +61,7 @@ PlatformResult SoundManager::StrToPlatformEnum(const std::string& key, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SoundManager::PlatformEnumToStr(const sound_type_e value, - std::string* sound_type) { +PlatformResult SoundManager::PlatformEnumToStr(const sound_type_e value, std::string* sound_type) { LoggerD("Enter"); for (auto& item : platform_enum_map_) { if (item.second == value) { @@ -76,8 +71,7 @@ PlatformResult SoundManager::PlatformEnumToStr(const sound_type_e value, } } - std::string message = - "Platform enum value " + std::to_string(value) + " not found"; + std::string message = "Platform enum value " + std::to_string(value) + " not found"; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); } @@ -140,17 +134,21 @@ SoundManager::~SoundManager() { UnsetSoundModeChangeListener(); if (is_sound_device_change_listener_) { - if (SOUND_MANAGER_ERROR_NONE != sound_manager_remove_device_connection_changed_cb(sound_device_connection_listener_id_)) { - LoggerE("Cannot unregister connection listener id == %d", sound_device_connection_listener_id_); + if (SOUND_MANAGER_ERROR_NONE != + sound_manager_remove_device_connection_changed_cb(sound_device_connection_listener_id_)) { + LoggerE("Cannot unregister connection listener id == %d", + sound_device_connection_listener_id_); } - if (SOUND_MANAGER_ERROR_NONE != sound_manager_remove_device_state_changed_cb(sound_device_state_listener_id_)) { + if (SOUND_MANAGER_ERROR_NONE != + sound_manager_remove_device_state_changed_cb(sound_device_state_listener_id_)) { LoggerE("Cannot unregister state listener id == %d", sound_device_state_listener_id_); } } if (is_volume_change_listener_) { - if (SOUND_MANAGER_ERROR_NONE != sound_manager_remove_volume_changed_cb(volume_change_listener_id_)) { + if (SOUND_MANAGER_ERROR_NONE != + sound_manager_remove_volume_changed_cb(volume_change_listener_id_)) { LoggerE("Cannot unregister volume listener id == %d", volume_change_listener_id_); } } @@ -183,9 +181,8 @@ PlatformResult SoundManager::GetMaxVolume(sound_type_e type, int* max_volume) { PlatformResult status = PlatformEnumToStr(type, &sound_type); if (status.IsError()) return status; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to find maxVolume", - ("Failed to find maxVolume of type: %s", sound_type.c_str())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to find maxVolume", + ("Failed to find maxVolume of type: %s", sound_type.c_str())); } *max_volume = it->second; @@ -205,25 +202,20 @@ void SoundManager::VolumeChangeCallback(sound_type_e type, unsigned int value) { picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); - response_obj.insert( - std::make_pair("listenerId", picojson::value("VolumeChangeListener"))); + response_obj.insert(std::make_pair("listenerId", picojson::value("VolumeChangeListener"))); std::string sound_type; PlatformResult status = PlatformEnumToStr(type, &sound_type); - if (status.IsError()) - return; + if (status.IsError()) return; - response_obj.insert( - std::make_pair("type", picojson::value(sound_type))); + response_obj.insert(std::make_pair("type", picojson::value(sound_type))); int max_volume; status = GetMaxVolume(type, &max_volume); - if (status.IsError()) - return; + if (status.IsError()) return; - response_obj.insert(std::make_pair( - "volume", - picojson::value(ConvertToSystemVolume(max_volume, value)))); + response_obj.insert( + std::make_pair("volume", picojson::value(ConvertToSystemVolume(max_volume, value)))); Instance::PostMessage(&instance_, response.serialize().c_str()); } @@ -237,21 +229,18 @@ PlatformResult SoundManager::GetSoundMode(std::string* sound_mode_type) { int ret = vconf_get_bool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &isEnableSound); if (VCONF_OK != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error: " + std::to_string(ret), - ("vconf_get_bool error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error: " + std::to_string(ret), + ("vconf_get_bool error: %d (%s)", ret, get_error_message(ret))); } ret = vconf_get_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &isEnableVibrate); if (VCONF_OK != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unknown error: " + std::to_string(ret), - ("vconf_get_bool error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error: " + std::to_string(ret), + ("vconf_get_bool error: %d (%s)", ret, get_error_message(ret))); } if (isEnableSound && isEnableVibrate) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Platform has wrong state.", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform has wrong state.", ("Wrong state (sound && vibration)")); } @@ -273,9 +262,8 @@ PlatformResult SoundManager::SetVolume(const picojson::object& args) { LoggerD("volume: %f", volume); if (volume > 1.0 || volume < 0.0) { - return LogAndCreateResult( - ErrorCode::INVALID_VALUES_ERR, - "Volume should be the value between 0 and 1."); + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, + "Volume should be the value between 0 and 1."); } sound_type_e sound_type; @@ -284,9 +272,8 @@ PlatformResult SoundManager::SetVolume(const picojson::object& args) { auto it = max_volume_map_.find(sound_type); if (it == max_volume_map_.end()) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to find maxVolume", - ("Failed to find maxVolume of type: %d", type.c_str())); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to find maxVolume", + ("Failed to find maxVolume of type: %d", type.c_str())); } int max_volume = it->second; @@ -295,16 +282,14 @@ PlatformResult SoundManager::SetVolume(const picojson::object& args) { int ret = sound_manager_set_volume(sound_type, value); if (ret != SOUND_MANAGER_ERROR_NONE) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to set volume", - ("Failed to set volume: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set volume", + ("Failed to set volume: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SoundManager::GetVolume(const picojson::object& args, - double* volume) { +PlatformResult SoundManager::GetVolume(const picojson::object& args, double* volume) { LoggerD("Enter"); const std::string& type = FromJson(args, "type"); int value = 0; @@ -319,9 +304,8 @@ PlatformResult SoundManager::GetVolume(const picojson::object& args, int ret = sound_manager_get_volume(type_enum, &value); if (ret != SOUND_MANAGER_ERROR_NONE) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get volume", - ("Failed to get volume: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get volume", + ("Failed to get volume: %d (%s)", ret, get_error_message(ret))); } *volume = ConvertToSystemVolume(max_volume, value); @@ -330,8 +314,7 @@ PlatformResult SoundManager::GetVolume(const picojson::object& args, return PlatformResult(ErrorCode::NO_ERROR); } -void SoundManager::soundModeChangedCb(keynode_t*, void* user_data) -{ +void SoundManager::soundModeChangedCb(keynode_t*, void* user_data) { LoggerD("Enter"); if (nullptr == user_data) { @@ -362,15 +345,13 @@ PlatformResult SoundManager::SetSoundModeChangeListener( int status = vconf_notify_key_changed(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, SoundManager::soundModeChangedCb, this); if (VCONF_OK != status) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SoundModeChangeListener not set"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SoundModeChangeListener not set"); } status = vconf_notify_key_changed(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, SoundManager::soundModeChangedCb, this); if (VCONF_OK != status) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SoundModeChangeListener not set"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SoundModeChangeListener not set"); } soundModeChangeListening = true; @@ -387,15 +368,13 @@ PlatformResult SoundManager::UnsetSoundModeChangeListener() { int status = vconf_ignore_key_changed(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, SoundManager::soundModeChangedCb); if (VCONF_OK != status) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SoundModeChangeListener not unset"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SoundModeChangeListener not unset"); } status = vconf_ignore_key_changed(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, SoundManager::soundModeChangedCb); if (VCONF_OK != status) { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "SoundModeChangeListener not unset"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "SoundModeChangeListener not unset"); } soundModeChangeListening = false; @@ -407,18 +386,14 @@ PlatformResult SoundManager::SetVolumeChangeListener() { if (!is_volume_change_listener_) { int ret = sound_manager_add_volume_changed_cb( [](sound_type_e type, unsigned int value, void* ud) { - return static_cast(ud) - ->VolumeChangeCallback(type, value); + return static_cast(ud)->VolumeChangeCallback(type, value); }, - static_cast(this), - &volume_change_listener_id_ - ); + static_cast(this), &volume_change_listener_id_); if (ret != SOUND_MANAGER_ERROR_NONE) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to set volume changed callback", - ("Failed to set volume changed callback: error: %d (%s)", - ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Failed to set volume changed callback", + ("Failed to set volume changed callback: error: %d (%s)", ret, get_error_message(ret))); } is_volume_change_listener_ = true; @@ -436,8 +411,8 @@ PlatformResult SoundManager::UnsetVolumeChangeListener() { int ret = sound_manager_remove_volume_changed_cb(volume_change_listener_id_); if (ret != SOUND_MANAGER_ERROR_NONE) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to unset volume changed callback", - ("sound_manager_unset_volume_changed_cb error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Failed to unset volume changed callback", + ("sound_manager_unset_volume_changed_cb error: %d (%s)", ret, get_error_message(ret))); } is_volume_change_listener_ = false; @@ -483,63 +458,61 @@ void SoundManager::GetDeviceList(sound_device_mask_e mask, picojson::object& out ReportSuccess(response, out); } -PlatformResult SoundManager::GetDeviceInfo(sound_device_h device, - bool is_connected, - bool check_connection, - picojson::object* obj) { +PlatformResult SoundManager::GetDeviceInfo(sound_device_h device, bool is_connected, + bool check_connection, picojson::object* obj) { LoggerD("Entered"); - //get id + // get id int id = 0; int ret = sound_manager_get_device_id(device, &id); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device id failed", - ("sound_manager_get_device_id error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device id failed", + ("sound_manager_get_device_id error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair("id", picojson::value(static_cast(id)))); - //get name - char *name = nullptr; + // get name + char* name = nullptr; ret = sound_manager_get_device_name(device, &name); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device name failed", - ("sound_manager_get_device_name error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device name failed", + ("sound_manager_get_device_name error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair("name", picojson::value(name))); - //get type + // get type sound_device_type_e type = SOUND_DEVICE_BUILTIN_SPEAKER; ret = sound_manager_get_device_type(device, &type); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device type failed", - ("sound_manager_get_device_type error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device type failed", + ("sound_manager_get_device_type error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair("device", picojson::value(SoundDeviceTypeToString(type)))); - //get direction + // get direction sound_device_io_direction_e direction = SOUND_DEVICE_IO_DIRECTION_IN; - ret = sound_manager_get_device_io_direction (device, &direction); + ret = sound_manager_get_device_io_direction(device, &direction); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device direction failed", - ("sound_manager_get_device_io_direction error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device direction failed", + ("sound_manager_get_device_io_direction error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair("direction", picojson::value(SoundIOTypeToString(direction)))); - //get state + // get state sound_device_state_e state = SOUND_DEVICE_STATE_DEACTIVATED; ret = sound_manager_get_device_state(device, &state); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device state failed", - ("sound_manager_get_device_state error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device state failed", + ("sound_manager_get_device_state error: %d (%s)", ret, get_error_message(ret))); } obj->insert(std::make_pair("isActivated", picojson::value(static_cast(state)))); - //get connection + // get connection if (check_connection) { return IsDeviceConnected(type, direction, obj); } @@ -565,9 +538,8 @@ PlatformResult SoundManager::IsDeviceConnected(sound_device_type_e type, mask = SOUND_DEVICE_IO_DIRECTION_BOTH_MASK; break; default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Invalid IO type", - ("Invalid IOType (%d)", direction)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Invalid IO type", + ("Invalid IOType (%d)", direction)); } sound_device_list_h device_list = nullptr; @@ -583,16 +555,16 @@ PlatformResult SoundManager::IsDeviceConnected(sound_device_type_e type, int ret = sound_manager_get_device_list(mask, &device_list); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device list failed", - ("sound_manager_get_device_list error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device list failed", + ("sound_manager_get_device_list error: %d (%s)", ret, get_error_message(ret))); } while (!(ret = sound_manager_get_next_device(device_list, &device))) { ret = sound_manager_get_device_type(device, &device_type); if (SOUND_MANAGER_ERROR_NONE != ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Getting device type failed", - ("sound_manager_get_device_type error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, "Getting device type failed", + ("sound_manager_get_device_type error: %d (%s)", ret, get_error_message(ret))); } if (type == device_type) { @@ -614,10 +586,10 @@ void SoundManager::DeviceChangeCB(sound_device_h device, bool is_connected, bool PlatformResult result = GetDeviceInfo(device, is_connected, check_connection, &response_obj); if (result.IsSuccess()) { - response_obj.insert(std::make_pair( - "listenerId", picojson::value("SoundDeviceStateChangeCallback"))); + response_obj.insert( + std::make_pair("listenerId", picojson::value("SoundDeviceStateChangeCallback"))); - auto call_response = [this, response]()->void { + auto call_response = [this, response]() -> void { Instance::PostMessage(&instance_, response.serialize().c_str()); }; @@ -625,15 +597,14 @@ void SoundManager::DeviceChangeCB(sound_device_h device, bool is_connected, bool } } -void DeviceConnectionChangedCB(sound_device_h device, bool is_connected, void *user_data) { +void DeviceConnectionChangedCB(sound_device_h device, bool is_connected, void* user_data) { LoggerD("Entered"); SoundManager* h = static_cast(user_data); h->DeviceChangeCB(device, is_connected, false); } -void DeviceStateChangedCB(sound_device_h device, sound_device_state_e unused, - void *user_data) { +void DeviceStateChangedCB(sound_device_h device, sound_device_state_e unused, void* user_data) { LoggerD("Entered"); SoundManager* h = static_cast(user_data); @@ -647,24 +618,22 @@ PlatformResult SoundManager::AddDeviceStateChangeListener() { sound_device_mask_e mask = SOUND_DEVICE_ALL_MASK; if (!is_sound_device_change_listener_) { - ret = sound_manager_add_device_connection_changed_cb(mask, DeviceConnectionChangedCB, - this, &sound_device_connection_listener_id_); + ret = sound_manager_add_device_connection_changed_cb(mask, DeviceConnectionChangedCB, this, + &sound_device_connection_listener_id_); if (SOUND_MANAGER_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Setting connection listener failed", - ("sound_manager_add_device_connection_changed_cb error: %d (%s)", - ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Setting connection listener failed", + ("sound_manager_add_device_connection_changed_cb error: %d (%s)", + ret, get_error_message(ret))); } - ret = sound_manager_add_device_state_changed_cb(mask, DeviceStateChangedCB, - this, &sound_device_state_listener_id_); + ret = sound_manager_add_device_state_changed_cb(mask, DeviceStateChangedCB, this, + &sound_device_state_listener_id_); if (SOUND_MANAGER_ERROR_NONE != ret) { // silently cleanup connection changed callback registered in previous step sound_manager_remove_device_connection_changed_cb(sound_device_connection_listener_id_); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Setting state listener failed", - ("sound_manager_add_device_state_changed_cb error: %d (%s)", - ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Setting state listener failed", + ("sound_manager_add_device_state_changed_cb error: %d (%s)", ret, + get_error_message(ret))); } is_sound_device_change_listener_ = true; @@ -677,18 +646,19 @@ PlatformResult SoundManager::RemoveDeviceStateChangeListener() { LoggerD("Entered"); if (is_sound_device_change_listener_) { - int ret = sound_manager_remove_device_connection_changed_cb(sound_device_connection_listener_id_); + int ret = + sound_manager_remove_device_connection_changed_cb(sound_device_connection_listener_id_); if (SOUND_MANAGER_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Removing connection listener failed", - ("sound_manager_remove_device_connection_changed_cb error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Removing connection listener failed", + ("sound_manager_remove_device_connection_changed_cb error: %d (%s)", + ret, get_error_message(ret))); } ret = sound_manager_remove_device_state_changed_cb(sound_device_state_listener_id_); if (SOUND_MANAGER_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Removing state listener failed", - ("sound_manager_remove_device_state_changed_cb error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Removing state listener failed", + ("sound_manager_remove_device_state_changed_cb error: %d (%s)", ret, + get_error_message(ret))); } is_sound_device_change_listener_ = false; diff --git a/src/sound/sound_manager.h b/src/sound/sound_manager.h index bb019bc..b668af5 100644 --- a/src/sound/sound_manager.h +++ b/src/sound/sound_manager.h @@ -19,16 +19,17 @@ #include +#include #include "common/picojson.h" #include "common/platform_result.h" -#include namespace extension { namespace sound { class SoundManagerSoundModeChangedListener { public: - virtual ~SoundManagerSoundModeChangedListener() {} + virtual ~SoundManagerSoundModeChangedListener() { + } virtual void OnSoundModeChange(const std::string& newmode) = 0; }; @@ -41,10 +42,8 @@ class SoundManager { common::PlatformResult GetSoundMode(std::string* sound_mode_type); common::PlatformResult SetVolume(const picojson::object& args); - common::PlatformResult GetVolume(const picojson::object& args, - double* volume); - common::PlatformResult SetSoundModeChangeListener( - SoundManagerSoundModeChangedListener* listener); + common::PlatformResult GetVolume(const picojson::object& args, double* volume); + common::PlatformResult SetSoundModeChangeListener(SoundManagerSoundModeChangedListener* listener); common::PlatformResult UnsetSoundModeChangeListener(); common::PlatformResult SetVolumeChangeListener(); common::PlatformResult UnsetVolumeChangeListener(); @@ -54,7 +53,6 @@ class SoundManager { common::PlatformResult RemoveDeviceStateChangeListener(); private: - std::map max_volume_map_; bool is_volume_change_listener_; int volume_change_listener_id_; @@ -65,15 +63,12 @@ class SoundManager { common::PlatformResult GetMaxVolume(sound_type_e type, int* max_volume); void VolumeChangeCallback(sound_type_e type, unsigned int value); - static common::PlatformResult StrToPlatformEnum(const std::string& key, - sound_type_e* sound_type); + static common::PlatformResult StrToPlatformEnum(const std::string& key, sound_type_e* sound_type); static common::PlatformResult PlatformEnumToStr(const sound_type_e value, std::string* sound_type); - common::PlatformResult GetDeviceInfo(sound_device_h device, - bool is_connected, - bool check_connection, - picojson::object* obj); + common::PlatformResult GetDeviceInfo(sound_device_h device, bool is_connected, + bool check_connection, picojson::object* obj); common::PlatformResult IsDeviceConnected(sound_device_type_e type, sound_device_io_direction_e direction, picojson::object* obj); diff --git a/src/systeminfo/systeminfo-utils.cpp b/src/systeminfo/systeminfo-utils.cpp index 7877f7f..d273da3 100644 --- a/src/systeminfo/systeminfo-utils.cpp +++ b/src/systeminfo/systeminfo-utils.cpp @@ -19,8 +19,8 @@ #include -#include #include +#include #include "common/logger.h" #include "common/platform_exception.h" @@ -45,8 +45,9 @@ PlatformResult SysteminfoUtils::GetVconfInt(const char *key, int *value) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); } -PlatformResult SysteminfoUtils::GetRuntimeInfoString(system_settings_key_e key, std::string* platform_string) { - char* platform_c_string; +PlatformResult SysteminfoUtils::GetRuntimeInfoString(system_settings_key_e key, + std::string *platform_string) { + char *platform_c_string; int err = system_settings_get_value_string(key, &platform_c_string); if (SYSTEM_SETTINGS_ERROR_NONE == err) { if (nullptr != platform_c_string) { @@ -55,15 +56,15 @@ PlatformResult SysteminfoUtils::GetRuntimeInfoString(system_settings_key_e key, return PlatformResult(ErrorCode::NO_ERROR); } } - const std::string error_msg = "Error when retrieving system setting information: " - + std::to_string(err); + const std::string error_msg = + "Error when retrieving system setting information: " + std::to_string(err); return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); } PlatformResult SysteminfoUtils::CheckTelephonySupport() { bool supported = false; - PlatformResult ret = SystemInfoDeviceCapability::GetValueBool( - "tizen.org/feature/network.telephony", &supported); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/network.telephony", &supported); if (ret.IsError()) { return ret; } @@ -76,15 +77,14 @@ PlatformResult SysteminfoUtils::CheckTelephonySupport() { PlatformResult SysteminfoUtils::CheckCameraFlashSupport() { bool supported = false; - PlatformResult ret = SystemInfoDeviceCapability::GetValueBool( - "tizen.org/feature/camera.back.flash", &supported); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/camera.back.flash", &supported); if (ret.IsError()) { return ret; } if (!supported) { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, - "Back-facing camera with a flash is not supported on this device"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Back-facing camera with a flash is not supported on this device"); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -97,24 +97,24 @@ PlatformResult SysteminfoUtils::CheckIfEthernetNetworkSupported() { int error = connection_create(&connection_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot create connection: " + std::to_string(error); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_create error: %d (%s)", error, get_error_message(error))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg, ("connection_create error: %d (%s)", + error, get_error_message(error))); } - std::unique_ptr::type, int (*)(connection_h)> connection_handle_ptr( - connection_handle, &connection_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(connection_h)> + connection_handle_ptr(connection_handle, + &connection_destroy); // automatically release the memory error = connection_get_ethernet_state(connection_handle, &connection_state); if (CONNECTION_ERROR_NOT_SUPPORTED == error) { std::string log_msg = "Cannot get ethernet connection state: Not supported"; return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, log_msg, - ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); + ErrorCode::NOT_SUPPORTED_ERR, log_msg, + ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SysteminfoUtils::GetTotalMemory(long long* result) { +PlatformResult SysteminfoUtils::GetTotalMemory(long long *result) { LoggerD("Entered"); unsigned int value = 0; @@ -123,8 +123,8 @@ PlatformResult SysteminfoUtils::GetTotalMemory(long long* result) { if (ret != DEVICE_ERROR_NONE) { std::string log_msg = "Failed to get total memory: " + std::to_string(ret); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("device_memory_get_total error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("device_memory_get_total error: %d (%s)", ret, get_error_message(ret))); } *result = static_cast(value) * MEMORY_TO_BYTE; @@ -132,7 +132,7 @@ PlatformResult SysteminfoUtils::GetTotalMemory(long long* result) { return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SysteminfoUtils::GetAvailableMemory(long long* result) { +PlatformResult SysteminfoUtils::GetAvailableMemory(long long *result) { LoggerD("Entered"); unsigned int value = 0; @@ -141,8 +141,8 @@ PlatformResult SysteminfoUtils::GetAvailableMemory(long long* result) { if (ret != DEVICE_ERROR_NONE) { std::string log_msg = "Failed to get total memory: " + std::to_string(ret); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("device_memory_get_available error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("device_memory_get_available error: %d (%s)", ret, get_error_message(ret))); } *result = static_cast(value) * MEMORY_TO_BYTE; @@ -150,34 +150,30 @@ PlatformResult SysteminfoUtils::GetAvailableMemory(long long* result) { } PlatformResult SysteminfoUtils::RegisterVconfCallback(const char *in_key, vconf_callback_fn cb, - void* event_ptr) { + void *event_ptr) { if (0 != vconf_notify_key_changed(in_key, cb, event_ptr)) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to register vconf callback", - ("Failed to register vconf callback: %s", in_key)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register vconf callback", + ("Failed to register vconf callback: %s", in_key)); } return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult SysteminfoUtils::UnregisterVconfCallback(const char *in_key, vconf_callback_fn cb) { if (0 != vconf_ignore_key_changed(in_key, cb)) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to unregister vconf callback", - ("Failed to unregister vconf callback: %s", in_key)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister vconf callback", + ("Failed to unregister vconf callback: %s", in_key)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SysteminfoUtils::RegisterTapiChangeCallback(TapiHandle *handle, - const char *noti_id, +PlatformResult SysteminfoUtils::RegisterTapiChangeCallback(TapiHandle *handle, const char *noti_id, tapi_notification_cb callback, void *user_data) { int ntv_ret = tel_register_noti_event(handle, noti_id, callback, user_data); if (TAPI_API_SUCCESS != ntv_ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to register tapi callback", - ("Failed to register tapi callback with key: %s - %d (%s)", - noti_id, ntv_ret, get_error_message(ntv_ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register tapi callback", + ("Failed to register tapi callback with key: %s - %d (%s)", noti_id, + ntv_ret, get_error_message(ntv_ret))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -186,13 +182,12 @@ PlatformResult SysteminfoUtils::UnregisterTapiChangeCallback(TapiHandle *handle, const char *noti_id) { int ntv_ret = tel_deregister_noti_event(handle, noti_id); if (TAPI_API_SUCCESS != ntv_ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to unregister tapi callback", - ("Failed to unregister tapi callback with key: %s - %d (%s)", - noti_id, ntv_ret, get_error_message(ntv_ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister tapi callback", + ("Failed to unregister tapi callback with key: %s - %d (%s)", noti_id, + ntv_ret, get_error_message(ntv_ret))); } return PlatformResult(ErrorCode::NO_ERROR); } -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi diff --git a/src/systeminfo/systeminfo-utils.h b/src/systeminfo/systeminfo-utils.h index 818933d..2541e08 100644 --- a/src/systeminfo/systeminfo-utils.h +++ b/src/systeminfo/systeminfo-utils.h @@ -17,12 +17,12 @@ #ifndef WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_UTILS_H__ #define WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_UTILS_H__ -#include -#include -#include -#include #include #include +#include +#include +#include +#include #include "common/picojson.h" #include "common/platform_result.h" #include "systeminfo/systeminfo_device_capability.h" @@ -42,14 +42,14 @@ class SysteminfoUtils { public: static common::PlatformResult GetVconfInt(const char *key, int *value); static common::PlatformResult GetRuntimeInfoString(system_settings_key_e key, - std::string* platform_string); + std::string *platform_string); static common::PlatformResult CheckTelephonySupport(); static common::PlatformResult CheckCameraFlashSupport(); static common::PlatformResult CheckIfEthernetNetworkSupported(); - static common::PlatformResult GetTotalMemory(long long* result); - static common::PlatformResult GetAvailableMemory(long long* result); + static common::PlatformResult GetTotalMemory(long long *result); + static common::PlatformResult GetAvailableMemory(long long *result); static common::PlatformResult RegisterVconfCallback(const char *in_key, vconf_callback_fn cb, - void* event_ptr); + void *event_ptr); static common::PlatformResult UnregisterVconfCallback(const char *in_key, vconf_callback_fn cb); static common::PlatformResult RegisterTapiChangeCallback(TapiHandle *handle, const char *noti_id, tapi_notification_cb callback, @@ -60,7 +60,7 @@ class SysteminfoUtils { typedef unsigned char byte; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi -#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_UTILS_H__ +#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_UTILS_H__ diff --git a/src/systeminfo/systeminfo_device_capability.cc b/src/systeminfo/systeminfo_device_capability.cc index c1976d2..c192912 100644 --- a/src/systeminfo/systeminfo_device_capability.cc +++ b/src/systeminfo/systeminfo_device_capability.cc @@ -16,8 +16,8 @@ #include "systeminfo_device_capability.h" -#include #include +#include #include "common/logger.h" @@ -41,7 +41,7 @@ const char* kProfileFull = "MOBILE_FULL"; const char* kProfileMobile = "MOBILE_WEB"; const char* kProfileWearable = "WEARABLE"; const char* kProfileTv = "TV"; -//opengles +// opengles const char* kOpenglesTextureDelimiter = "/"; const char* kOpenglesTextureUtc = "utc"; const char* kOpenglesTexturePtc = "ptc"; @@ -49,14 +49,14 @@ const char* kOpenglesTextureEtc = "etc"; const char* kOpenglesTexture3dc = "3dc"; const char* kOpenglesTextureAtc = "atc"; const char* kOpenglesTexturePvrtc = "pvrtc"; -//core cpu arch +// core cpu arch const char* kPlatformCoreDelimiter = " | "; const char* kPlatformCoreArmv6 = "armv6"; const char* kPlatformCoreArmv7 = "armv7"; const char* kPlatformCoreAarch64 = "aarch64"; const char* kPlatformCoreX86 = "x86"; const char* kPlatformCoreX86_64 = "x86_64"; -//core fpu arch +// core fpu arch const char* kPlatformCoreSse2 = "sse2"; const char* kPlatformCoreSse3 = "sse3"; const char* kPlatformCoreSsse3 = "ssse3"; @@ -66,7 +66,9 @@ const char* kPlatformCoreVfpv4 = "vfpv4"; /*API feature*/ /*Network feature*/ -const char* kTizenFeatureBluetoothAlwaysOn = "http://tizen.org/capability/network.bluetooth.always_on"; //hardcoded values for mobile/wearable: false, tv: true +const char* kTizenFeatureBluetoothAlwaysOn = + "http://tizen.org/capability/network.bluetooth.always_on"; // hardcoded values for + // mobile/wearable: false, tv: true const char* kTizenFeatureOpenglesTextureFormat = "http://tizen.org/feature/opengles.texture_format"; const char* kTizenFeatureCoreApiVersion = "http://tizen.org/feature/platform.core.api.version"; const char* kTizenFeaturePlatfromCoreCpuArch = "http://tizen.org/feature/platform.core.cpu.arch"; @@ -79,11 +81,12 @@ const char* kTizenFeatureScreen = "http://tizen.org/feature/screen"; const char* kTizenFeatureCpuFrequency = "http://tizen.org/feature/platform.core.cpu.frequency"; /*platform*/ const char* kTizenFeaturePlatformNativeApiVersion = "tizen.org/feature/platform.native.api.version"; -const char* kTizenFeaturePlatformNativeOspCompatible = "tizen.org/feature/platform.native.osp_compatible"; +const char* kTizenFeaturePlatformNativeOspCompatible = + "tizen.org/feature/platform.native.osp_compatible"; const char* kTizenFeaturePlatformVersionName = "http://tizen.org/feature/platform.version.name"; -} //namespace +} // namespace -PlatformResult SystemInfoDeviceCapability::GetValueBool(const char *key, bool* value) { +PlatformResult SystemInfoDeviceCapability::GetValueBool(const char* key, bool* value) { bool platform_result = false; int ret = system_info_get_platform_bool(key, &platform_result); if (SYSTEM_INFO_ERROR_NONE != ret) { @@ -92,8 +95,8 @@ PlatformResult SystemInfoDeviceCapability::GetValueBool(const char *key, bool* v std::string log_msg = "Platform error while getting bool value: "; log_msg += std::string(key) + " " + std::to_string(ret); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("system_info_get_custom_bool error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("system_info_get_custom_bool error: %d (%s)", ret, get_error_message(ret))); } } @@ -102,7 +105,7 @@ PlatformResult SystemInfoDeviceCapability::GetValueBool(const char *key, bool* v return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SystemInfoDeviceCapability::GetValueInt(const char *key, int* value) { +PlatformResult SystemInfoDeviceCapability::GetValueInt(const char* key, int* value) { int platform_result = 0; int ret = system_info_get_platform_int(key, &platform_result); if (SYSTEM_INFO_ERROR_NONE != ret) { @@ -111,8 +114,8 @@ PlatformResult SystemInfoDeviceCapability::GetValueInt(const char *key, int* val std::string log_msg = "Platform error while getting int value: "; log_msg += std::string(key) + " " + std::to_string(ret); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("system_info_get_custom_int error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("system_info_get_custom_int error: %d (%s)", ret, get_error_message(ret))); } } @@ -121,7 +124,7 @@ PlatformResult SystemInfoDeviceCapability::GetValueInt(const char *key, int* val return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SystemInfoDeviceCapability::GetValueString(const char *key, std::string* str_value) { +PlatformResult SystemInfoDeviceCapability::GetValueString(const char* key, std::string* str_value) { char* value = nullptr; int ret = system_info_get_platform_string(key, &value); @@ -131,8 +134,8 @@ PlatformResult SystemInfoDeviceCapability::GetValueString(const char *key, std:: std::string log_msg = "Platform error while getting string value: "; log_msg += std::string(key) + " " + std::to_string(ret); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("system_info_get_custom_string error: %d (%s)", ret, get_error_message(ret))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("system_info_get_custom_string error: %d (%s)", ret, get_error_message(ret))); } } @@ -146,7 +149,8 @@ PlatformResult SystemInfoDeviceCapability::GetValueString(const char *key, std:: return PlatformResult(ErrorCode::NO_ERROR); } -static PlatformResult CheckStringCapability(const std::string& key, std::string* value, bool* fetched) { +static PlatformResult CheckStringCapability(const std::string& key, std::string* value, + bool* fetched) { LoggerD("Entered CheckStringCapability"); *fetched = false; if (kTizenFeatureOpenglesTextureFormat == key) { @@ -187,11 +191,11 @@ static PlatformResult CheckStringCapability(const std::string& key, std::string* } else { size_t prefix_len = strlen("http://"); if (key.length() <= prefix_len) { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); } - PlatformResult ret = SystemInfoDeviceCapability::GetValueString(key.substr(prefix_len).c_str(), value); - if (ret.IsError()){ + PlatformResult ret = + SystemInfoDeviceCapability::GetValueString(key.substr(prefix_len).c_str(), value); + if (ret.IsError()) { return PlatformResult(ErrorCode::NO_ERROR); } } @@ -202,7 +206,7 @@ static PlatformResult CheckStringCapability(const std::string& key, std::string* static PlatformResult CheckBoolCapability(const std::string& key, bool* bool_value, bool* fetched) { LoggerD("Entered CheckBoolCapability"); *fetched = false; - if(kTizenFeatureBluetoothAlwaysOn == key) { + if (kTizenFeatureBluetoothAlwaysOn == key) { *bool_value = SystemInfoDeviceCapability::IsBluetoothAlwaysOn(); *fetched = true; } else if (kTizenFeatureScreen == key) { @@ -219,8 +223,8 @@ static PlatformResult CheckBoolCapability(const std::string& key, bool* bool_val if (key.length() <= prefix_len) { return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); } - PlatformResult ret = SystemInfoDeviceCapability::GetValueBool( - key.substr(prefix_len).c_str(), bool_value); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueBool(key.substr(prefix_len).c_str(), bool_value); if (ret.IsSuccess()) { *fetched = true; } @@ -241,11 +245,10 @@ static PlatformResult CheckIntCapability(const std::string& key, std::string* va } else { size_t prefix_len = strlen("http://"); if (key.length() <= prefix_len) { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); } - PlatformResult ret = SystemInfoDeviceCapability::GetValueInt( - key.substr(prefix_len).c_str(), &result); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueInt(key.substr(prefix_len).c_str(), &result); if (ret.IsError()) { *fetched = false; return PlatformResult(ErrorCode::NO_ERROR); @@ -257,13 +260,13 @@ static PlatformResult CheckIntCapability(const std::string& key, std::string* va } PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, - picojson::value* result) { + picojson::value* result) { LoggerD("Entered"); picojson::object& result_obj = result->get(); std::string value = ""; std::string type = ""; - bool bool_value = false ; + bool bool_value = false; bool is_fetched = false; PlatformResult ret = CheckBoolCapability(key, &bool_value, &is_fetched); @@ -284,7 +287,7 @@ PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, if (ret.IsError()) { return ret; } - if(is_fetched) { + if (is_fetched) { type = "string"; } } @@ -295,8 +298,7 @@ PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, } else if (type == "string" || type == "int") { result_obj.insert(std::make_pair("value", picojson::value(value))); } else { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "Value for given key was not found"); } result_obj.insert(std::make_pair("type", picojson::value(type))); @@ -305,8 +307,8 @@ PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, PlatformResult SystemInfoDeviceCapability::IsInputKeyboardLayout(bool* result) { std::string input_keyboard_layout = ""; - PlatformResult ret = GetValueString("tizen.org/feature/input.keyboard.layout", - &input_keyboard_layout); + PlatformResult ret = + GetValueString("tizen.org/feature/input.keyboard.layout", &input_keyboard_layout); if (ret.IsError()) { return ret; } @@ -414,9 +416,10 @@ PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreCpuArch(std::string* re bool bool_result = false; std::string arch = ""; - PlatformResult ret =SystemInfoDeviceCapability::GetValueString("tizen.org/feature/platform.core.cpu.arch", &arch); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueString("tizen.org/feature/platform.core.cpu.arch", &arch); if (ret.IsError()) { - LoggerE("GetValueString Error"); + LoggerE("GetValueString Error"); } ret = GetValueBool("tizen.org/feature/platform.core.cpu.arch.armv6", &bool_result); @@ -436,9 +439,9 @@ PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreCpuArch(std::string* re result += kPlatformCoreDelimiter; } - if(arch.compare("aarch64") == 0){ + if (arch.compare("aarch64") == 0) { result += kPlatformCoreAarch64; - }else{ + } else { result += kPlatformCoreArmv7; } } @@ -451,9 +454,9 @@ PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreCpuArch(std::string* re if (!result.empty()) { result += kPlatformCoreDelimiter; } - if(arch.compare("x86_64") == 0){ + if (arch.compare("x86_64") == 0) { result += kPlatformCoreX86_64; - }else{ + } else { result += kPlatformCoreX86; } } @@ -545,13 +548,13 @@ PlatformResult SystemInfoDeviceCapability::GetProfile(std::string* return_value) } *return_value = kProfileFull; - if ( kPlatformFull == profile ) { + if (kPlatformFull == profile) { *return_value = kProfileFull; - } else if ( kPlatformMobile == profile ) { + } else if (kPlatformMobile == profile) { *return_value = kProfileMobile; - } else if ( kPlatformWearable == profile ) { + } else if (kPlatformWearable == profile) { *return_value = kProfileWearable; - } else if ( kPlatformTv == profile ) { + } else if (kPlatformTv == profile) { *return_value = kProfileTv; } else { LoggerE("Profile is Unknown return MOBILE_FULL"); @@ -578,18 +581,15 @@ bool SystemInfoDeviceCapability::IsScreen() { return true; } - -#define MODEL_NAME "http://tizen.org/system/model_name" -#define MODEL_EMULATOR "Emulator" -bool _is_emulator(void) -{ +#define MODEL_NAME "http://tizen.org/system/model_name" +#define MODEL_EMULATOR "Emulator" +bool _is_emulator(void) { int ret; - char *model_name = NULL; + char* model_name = NULL; static bool emul = false; static int set = 0; - if (set) - return emul; + if (set) return emul; ret = system_info_get_platform_string(MODEL_NAME, &model_name); if (ret < 0) { @@ -597,8 +597,7 @@ bool _is_emulator(void) return emul; } - if (!strncmp(MODEL_EMULATOR, model_name, strlen(model_name) + 1)) - emul = true; + if (!strncmp(MODEL_EMULATOR, model_name, strlen(model_name) + 1)) emul = true; set = 1; free(model_name); @@ -612,22 +611,21 @@ PlatformResult SystemInfoDeviceCapability::GetPlatformCoreCpuFrequency(int* retu std::string freq; std::string file_name; - if(_is_emulator()) + if (_is_emulator()) file_name = "/proc/cpuinfo"; else file_name = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"; std::ifstream cpuinfo_freq(file_name); if (!cpuinfo_freq.is_open()) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unable to open file", - ("Failed to get cpu frequency")); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unable to open file", + ("Failed to get cpu frequency")); } - if(_is_emulator()) { - //get frequency value from cpuinfo file - //example entry for frequency looks like below - //cpu MHz : 3392.046 + if (_is_emulator()) { + // get frequency value from cpuinfo file + // example entry for frequency looks like below + // cpu MHz : 3392.046 std::size_t found; do { getline(cpuinfo_freq, freq); @@ -640,7 +638,7 @@ PlatformResult SystemInfoDeviceCapability::GetPlatformCoreCpuFrequency(int* retu } } else { getline(cpuinfo_freq, freq); - *return_value = std::stoi(freq) / 1000; // unit: MHz + *return_value = std::stoi(freq) / 1000; // unit: MHz } cpuinfo_freq.close(); @@ -662,10 +660,10 @@ PlatformResult SystemInfoDeviceCapability::GetNativeAPIVersion(std::string* retu PlatformResult SystemInfoDeviceCapability::GetPlatformVersionName(std::string* result) { LoggerD("Enter"); - //Because of lack of 'http://tizen.org/feature/platform.version.name' - //key on platform we use 'http://tizen.org/system/platform.name'. + // Because of lack of 'http://tizen.org/feature/platform.version.name' + // key on platform we use 'http://tizen.org/system/platform.name'. return GetValueString("tizen.org/system/platform.name", result); } -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi diff --git a/src/systeminfo/systeminfo_device_capability.h b/src/systeminfo/systeminfo_device_capability.h index 8285e61..b4b8164 100644 --- a/src/systeminfo/systeminfo_device_capability.h +++ b/src/systeminfo/systeminfo_device_capability.h @@ -27,9 +27,9 @@ namespace systeminfo { class SystemInfoDeviceCapability { public: static common::PlatformResult GetCapability(const std::string& key, picojson::value* result); - static common::PlatformResult GetValueBool(const char *key, bool* value); - static common::PlatformResult GetValueInt(const char *key, int* value); - static common::PlatformResult GetValueString(const char *key, std::string* str_value); + static common::PlatformResult GetValueBool(const char* key, bool* value); + static common::PlatformResult GetValueInt(const char* key, int* value); + static common::PlatformResult GetValueString(const char* key, std::string* str_value); static common::PlatformResult IsInputKeyboardLayout(bool* result); static common::PlatformResult GetOpenglesTextureFormat(std::string* result); @@ -44,7 +44,7 @@ class SystemInfoDeviceCapability { static bool IsScreen(); }; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi -#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_DEVICE_CAPABILITY_H__ +#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_DEVICE_CAPABILITY_H__ diff --git a/src/systeminfo/systeminfo_extension.cc b/src/systeminfo/systeminfo_extension.cc index 071b351..acc0404 100644 --- a/src/systeminfo/systeminfo_extension.cc +++ b/src/systeminfo/systeminfo_extension.cc @@ -30,7 +30,8 @@ SysteminfoExtension::SysteminfoExtension() { SetJavaScriptAPI(kSource_systeminfo_api); } -SysteminfoExtension::~SysteminfoExtension() {} +SysteminfoExtension::~SysteminfoExtension() { +} common::Instance* SysteminfoExtension::CreateInstance() { return new extension::systeminfo::SysteminfoInstance(); diff --git a/src/systeminfo/systeminfo_extension.h b/src/systeminfo/systeminfo_extension.h index 3e049de..f9ef23b 100644 --- a/src/systeminfo/systeminfo_extension.h +++ b/src/systeminfo/systeminfo_extension.h @@ -28,5 +28,4 @@ class SysteminfoExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // SYSTEMINFO_EXTENSION_H_ - +#endif // SYSTEMINFO_EXTENSION_H_ diff --git a/src/systeminfo/systeminfo_instance.cc b/src/systeminfo/systeminfo_instance.cc index 15961ec..56cbc77 100644 --- a/src/systeminfo/systeminfo_instance.cc +++ b/src/systeminfo/systeminfo_instance.cc @@ -20,8 +20,8 @@ #include #include -#include "common/picojson.h" #include "common/logger.h" +#include "common/picojson.h" #include "common/platform_exception.h" #include "common/task-queue.h" #include "common/tools.h" @@ -42,11 +42,11 @@ const std::string kListenerIdString = "listenerId"; const std::string kPrivilegeLED = "http://tizen.org/privilege/led"; -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), out); \ + return; \ + } } SysteminfoInstance::SysteminfoInstance() : manager_(this) { @@ -54,8 +54,7 @@ SysteminfoInstance::SysteminfoInstance() : manager_(this) { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SysteminfoInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&SysteminfoInstance::x, this, _1, _2)); REGISTER_SYNC("SystemInfo_getCapabilities", GetCapabilities); REGISTER_SYNC("SystemInfo_getCapability", GetCapability); REGISTER_SYNC("SystemInfo_addPropertyValueChangeListener", AddPropertyValueChangeListener); @@ -68,8 +67,8 @@ SysteminfoInstance::SysteminfoInstance() : manager_(this) { REGISTER_SYNC("SystemInfo_getMaxBrightness", GetMaxBrightness); #undef REGISTER_SYNC -#define REGISTER_ASYNC(c,x) \ - RegisterSyncHandler(c, std::bind(&SysteminfoInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) \ + RegisterSyncHandler(c, std::bind(&SysteminfoInstance::x, this, _1, _2)); REGISTER_ASYNC("SystemInfo_getPropertyValue", GetPropertyValue); REGISTER_ASYNC("SystemInfo_getPropertyValueArray", GetPropertyValueArray); #undef REGISTER_ASYNC @@ -81,7 +80,9 @@ SysteminfoInstance::~SysteminfoInstance() { void SysteminfoInstance::GetCapabilities(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); - LoggerW("DEPRECATION WARNING: getCapabilities() is deprecated and will be removed from next release. Use getCapability() instead."); + LoggerW( + "DEPRECATION WARNING: getCapabilities() is deprecated and will be removed from next release. " + "Use getCapability() instead."); manager_.GetCapabilities(args, &out); } @@ -101,12 +102,14 @@ void SysteminfoInstance::GetPropertyValueArray(const picojson::value& args, pico manager_.GetPropertyValueArray(args, &out); } -void SysteminfoInstance::AddPropertyValueChangeListener(const picojson::value& args, picojson::object& out) { +void SysteminfoInstance::AddPropertyValueChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); manager_.AddPropertyValueChangeListener(args, &out); } -void SysteminfoInstance::RemovePropertyValueChangeListener(const picojson::value& args, picojson::object& out) { +void SysteminfoInstance::RemovePropertyValueChangeListener(const picojson::value& args, + picojson::object& out) { LoggerD("Enter"); manager_.RemovePropertyValueChangeListener(args, &out); } @@ -122,7 +125,6 @@ void SysteminfoInstance::GetAvailableMemory(const picojson::value& args, picojso } void SysteminfoInstance::GetCount(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); manager_.GetCount(args, &out); } @@ -182,5 +184,5 @@ void SysteminfoInstance::GetMaxBrightness(const picojson::value& args, picojson: ReportSuccess(picojson::value(std::to_string(brightness)), out); } -} // namespace systeminfo -} // namespace extension +} // namespace systeminfo +} // namespace extension diff --git a/src/systeminfo/systeminfo_instance.h b/src/systeminfo/systeminfo_instance.h index 1a29194..95e7550 100644 --- a/src/systeminfo/systeminfo_instance.h +++ b/src/systeminfo/systeminfo_instance.h @@ -23,12 +23,11 @@ namespace extension { namespace systeminfo { -class SysteminfoInstance - : public common::ParsedInstance -{ +class SysteminfoInstance : public common::ParsedInstance { public: SysteminfoInstance(); virtual ~SysteminfoInstance(); + private: void GetCapabilities(const picojson::value& args, picojson::object& out); void GetCapability(const picojson::value& args, picojson::object& out); @@ -46,7 +45,7 @@ class SysteminfoInstance SysteminfoManager manager_; }; -} // namespace systeminfo -} // namespace extension +} // namespace systeminfo +} // namespace extension -#endif // SYSTEMINFO_INSTANCE_H_ +#endif // SYSTEMINFO_INSTANCE_H_ diff --git a/src/systeminfo/systeminfo_manager.cc b/src/systeminfo/systeminfo_manager.cc index 817698e..d816bae 100644 --- a/src/systeminfo/systeminfo_manager.cc +++ b/src/systeminfo/systeminfo_manager.cc @@ -31,10 +31,10 @@ #include "common/task-queue.h" #include "common/tools.h" -#include "systeminfo/systeminfo_instance.h" +#include "systeminfo/systeminfo-utils.h" #include "systeminfo/systeminfo_device_capability.h" +#include "systeminfo/systeminfo_instance.h" #include "systeminfo/systeminfo_sim_details_manager.h" -#include "systeminfo/systeminfo-utils.h" using common::PlatformResult; using common::ErrorCode; @@ -72,56 +72,56 @@ const std::string kPropertyIdEthernetNetwork = "ETHERNET_NETWORK"; const std::string kPropertyIdCellularNetwork = "CELLULAR_NETWORK"; const std::string kPropertyIdSim = "SIM"; const std::string kPropertyIdPeripheral = "PERIPHERAL"; -const std::string kPropertyIdMemory= "MEMORY"; -const std::string kPropertyIdCameraFlash= "CAMERA_FLASH"; +const std::string kPropertyIdMemory = "MEMORY"; +const std::string kPropertyIdCameraFlash = "CAMERA_FLASH"; -#define CHECK_EXIST(args, name, out) \ - if (!args.contains(name)) {\ - LogAndReportError(TypeMismatchException(name" is required argument"), *out);\ - return;\ - } +#define CHECK_EXIST(args, name, out) \ + if (!args.contains(name)) { \ + LogAndReportError(TypeMismatchException(name " is required argument"), *out); \ + return; \ + } -#define DEFAULT_REPORT_BOOL_CAPABILITY(str_name, feature_name) \ +#define DEFAULT_REPORT_BOOL_CAPABILITY(str_name, feature_name) \ ret = SystemInfoDeviceCapability::GetValueBool(feature_name, &bool_value); \ - if (ret.IsError()) { \ - LogAndReportError(ret, out); \ - return; \ - } \ + if (ret.IsError()) { \ + LogAndReportError(ret, out); \ + return; \ + } \ result_obj.insert(std::make_pair(str_name, picojson::value(bool_value))); #define REPORT_BOOL_CAPABILITY(str_name, method) \ - ret = method(&bool_value); \ - if (ret.IsError()) { \ - LogAndReportError(ret, out); \ - return; \ - } \ + ret = method(&bool_value); \ + if (ret.IsError()) { \ + LogAndReportError(ret, out); \ + return; \ + } \ result_obj.insert(std::make_pair(str_name, picojson::value(bool_value))); -#define DEFAULT_REPORT_INT_CAPABILITY(str_name, feature_name) \ +#define DEFAULT_REPORT_INT_CAPABILITY(str_name, feature_name) \ ret = SystemInfoDeviceCapability::GetValueInt(feature_name, &int_value); \ - if (ret.IsError()) { \ - LogAndReportError(ret, out); \ - return; \ - } \ + if (ret.IsError()) { \ + LogAndReportError(ret, out); \ + return; \ + } \ result_obj.insert(std::make_pair(str_name, picojson::value(std::to_string(int_value)))); -#define DEFAULT_REPORT_STRING_CAPABILITY(str_name, feature_name) \ +#define DEFAULT_REPORT_STRING_CAPABILITY(str_name, feature_name) \ ret = SystemInfoDeviceCapability::GetValueString(feature_name, &str_value); \ - if (ret.IsError()) { \ - LogAndReportError(ret, out); \ - return; \ - } \ + if (ret.IsError()) { \ + LogAndReportError(ret, out); \ + return; \ + } \ result_obj.insert(std::make_pair(str_name, picojson::value(str_value))); #define REPORT_STRING_CAPABILITY(str_name, method) \ - ret = method(&str_value); \ - if (ret.IsError()) { \ - LogAndReportError(ret, out); \ - return; \ - } \ + ret = method(&str_value); \ + if (ret.IsError()) { \ + LogAndReportError(ret, out); \ + return; \ + } \ result_obj.insert(std::make_pair(str_name, picojson::value(str_value))); -//Callback static functions +// Callback static functions static void OnBatteryChangedCb(keynode_t* node, void* event_ptr) { LoggerD("Enter"); SysteminfoManager* manager = static_cast(event_ptr); @@ -161,13 +161,13 @@ static void OnDeviceAutoRotationChangedCb(keynode_t* node, void* event_ptr) { } static void OnDeviceOrientationChangedCb(sensor_t sensor, unsigned int event_type, - sensor_data_t *data, void *user_data) { + sensor_data_t* data, void* user_data) { LoggerD("Enter"); SysteminfoManager* manager = static_cast(user_data); manager->CallListenerCallback(kPropertyIdDeviceOrientation); } -static void OnLocaleChangedCb(keynode_t* node, void* event_ptr) { +static void OnLocaleChangedCb(keynode_t* node, void* event_ptr) { LoggerD("Enter"); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdLocale); @@ -179,8 +179,8 @@ static void OnNetworkChangedCb(connection_type_e type, void* event_ptr) { manager->CallListenerCallback(kPropertyIdNetwork); } -static void OnNetworkValueChangedCb(const char* ipv4_address, - const char* ipv6_address, void* event_ptr) { +static void OnNetworkValueChangedCb(const char* ipv4_address, const char* ipv6_address, + void* event_ptr) { LoggerD("Enter"); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdWifiNetwork); @@ -188,14 +188,14 @@ static void OnNetworkValueChangedCb(const char* ipv4_address, manager->CallListenerCallback(kPropertyIdCellularNetwork); } -static void OnCellularNetworkValueChangedCb(keynode_t *node, void *event_ptr) { +static void OnCellularNetworkValueChangedCb(keynode_t* node, void* event_ptr) { LoggerD("Enter"); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdCellularNetwork, kDefaultListenerIndex); } -static void OnTapiValueChangedCb(TapiHandle *handle, const char *noti_id, - void *data, void *user_data) { +static void OnTapiValueChangedCb(TapiHandle* handle, const char* noti_id, void* data, + void* user_data) { LoggerD("Enter"); LoggerD("Changed key: %s", noti_id); SysteminfoManager* manager = static_cast(user_data); @@ -224,14 +224,14 @@ static void OnBrightnessChangedCb(device_callback_e type, void* value, void* use } } -static void OnWifiLevelChangedCb (wifi_manager_rssi_level_e rssi_level, void *user_data) { +static void OnWifiLevelChangedCb(wifi_manager_rssi_level_e rssi_level, void* user_data) { LoggerD("Entered"); LoggerD("Level %d", rssi_level); SysteminfoManager* manager = static_cast(user_data); manager->SetWifiLevel(rssi_level); } -} //namespace +} // namespace class SysteminfoManager::TapiManager { public: @@ -286,8 +286,8 @@ class SysteminfoManager::TapiManager { for (const auto& h : handles_) { for (const auto& n : kNotifications) { - auto result = SysteminfoUtils::RegisterTapiChangeCallback( - h, n, OnTapiValueChangedCb, user_data); + auto result = + SysteminfoUtils::RegisterTapiChangeCallback(h, n, OnTapiValueChangedCb, user_data); if (!result) { return result; } @@ -328,9 +328,8 @@ class SysteminfoManager::TapiManager { return PlatformResult{ErrorCode::INDEX_SIZE_ERR}; } - if (TAPI_API_SUCCESS == tel_get_property_int(handles_[index], - TAPI_PROP_NETWORK_SERVICE_TYPE, - network_type)) { + if (TAPI_API_SUCCESS == + tel_get_property_int(handles_[index], TAPI_PROP_NETWORK_SERVICE_TYPE, network_type)) { return PlatformResult{ErrorCode::NO_ERROR}; } else { LoggerE("Failed to get network type of index: %zu", index); @@ -353,14 +352,10 @@ class SysteminfoManager::TapiManager { return sim_manager_.GatherSimInformation(handles_[index], out); } - PlatformResult FetchBasicSimProperties(std::size_t index, - unsigned short* result_mcc, - unsigned short* result_mnc, - unsigned short* result_cell_id, - unsigned short* result_lac, - bool* result_is_roaming, - bool* result_is_flight_mode, - std::string* result_imei) { + PlatformResult FetchBasicSimProperties(std::size_t index, unsigned short* result_mcc, + unsigned short* result_mnc, unsigned short* result_cell_id, + unsigned short* result_lac, bool* result_is_roaming, + bool* result_is_flight_mode, std::string* result_imei) { ScopeLogger(); Initialize(); @@ -372,14 +367,9 @@ class SysteminfoManager::TapiManager { return PlatformResult{ErrorCode::INDEX_SIZE_ERR}; } - return SimDetailsManager::FetchBasicSimProperties(handles_[index], - result_mcc, - result_mnc, - result_cell_id, - result_lac, - result_is_roaming, - result_is_flight_mode, - result_imei); + return SimDetailsManager::FetchBasicSimProperties(handles_[index], result_mcc, result_mnc, + result_cell_id, result_lac, result_is_roaming, + result_is_flight_mode, result_imei); } private: @@ -415,7 +405,8 @@ class SysteminfoManager::TapiManager { } } - const char* kNotifications[3] = { TAPI_PROP_NETWORK_CELLID, TAPI_PROP_NETWORK_LAC, TAPI_PROP_NETWORK_ROAMING_STATUS }; + const char* kNotifications[3] = {TAPI_PROP_NETWORK_CELLID, TAPI_PROP_NETWORK_LAC, + TAPI_PROP_NETWORK_ROAMING_STATUS}; bool initialized_; std::vector handles_; @@ -425,8 +416,7 @@ class SysteminfoManager::TapiManager { class SysteminfoManager::AsynchronousOperation { public: - AsynchronousOperation(int count_ = 0) - : count_(count_) { + AsynchronousOperation(int count_ = 0) : count_(count_) { } ~AsynchronousOperation() { @@ -472,43 +462,71 @@ SysteminfoManager::SysteminfoManager(SysteminfoInstance* instance) storage_event_id_(0), connection_handle_(nullptr), async_op_(new AsynchronousOperation()) { - LoggerD("Entered"); - - int error = wifi_manager_initialize(&wifi_manager_); - if (WIFI_MANAGER_ERROR_NONE != error) { - std::string log_msg = "Initialization failed: " + std::string(get_error_message(error)); - LoggerE("%s", log_msg.c_str()); - } else { - LoggerD("WIFI initialization succeed"); - } - error = wifi_manager_set_rssi_level_changed_cb(wifi_manager_, OnWifiLevelChangedCb, this); - if (WIFI_MANAGER_ERROR_NONE != error) { - std::string log_msg = "Setting wifi listener failed: " + - std::string(get_error_message(error)); - LoggerE("%s", log_msg.c_str()); - } else { - LoggerD("Setting wifi listener succeed"); - } - InitCameraTypes(); - } + LoggerD("Entered"); + + int error = wifi_manager_initialize(&wifi_manager_); + if (WIFI_MANAGER_ERROR_NONE != error) { + std::string log_msg = "Initialization failed: " + std::string(get_error_message(error)); + LoggerE("%s", log_msg.c_str()); + } else { + LoggerD("WIFI initialization succeed"); + } + error = wifi_manager_set_rssi_level_changed_cb(wifi_manager_, OnWifiLevelChangedCb, this); + if (WIFI_MANAGER_ERROR_NONE != error) { + std::string log_msg = "Setting wifi listener failed: " + std::string(get_error_message(error)); + LoggerE("%s", log_msg.c_str()); + } else { + LoggerD("Setting wifi listener succeed"); + } + InitCameraTypes(); +} SysteminfoManager::~SysteminfoManager() { LoggerD("Enter"); DisconnectSensor(sensor_handle_); - if (IsListenerRegistered(kPropertyIdBattery)) { UnregisterBatteryListener(); } - if (IsListenerRegistered(kPropertyIdCpu)) { UnregisterCpuListener(); } - if (IsListenerRegistered(kPropertyIdStorage)) { UnregisterStorageListener(); } - if (IsListenerRegistered(kPropertyIdDisplay)) { UnregisterDisplayListener(); } - if (IsListenerRegistered(kPropertyIdDeviceOrientation)) { UnregisterDeviceOrientationListener(); } - if (IsListenerRegistered(kPropertyIdLocale)) { UnregisterLocaleListener(); } - if (IsListenerRegistered(kPropertyIdNetwork)) { UnregisterNetworkListener(); } - if (IsListenerRegistered(kPropertyIdWifiNetwork)) { registered_listeners_.erase(kPropertyIdWifiNetwork)/*HACK*/; UnregisterWifiNetworkListener(); } - if (IsListenerRegistered(kPropertyIdEthernetNetwork)) { registered_listeners_.erase(kPropertyIdEthernetNetwork)/*HACK*/; UnregisterEthernetNetworkListener(); } - if (IsListenerRegistered(kPropertyIdCellularNetwork)) { registered_listeners_.erase(kPropertyIdCellularNetwork)/*HACK*/; UnregisterCellularNetworkListener(); } - if (IsListenerRegistered(kPropertyIdPeripheral)) { UnregisterPeripheralListener(); } - if (IsListenerRegistered(kPropertyIdMemory)) { UnregisterMemoryListener(); } - if (IsListenerRegistered(kPropertyIdCameraFlash)) { UnregisterCameraFlashListener(); } + if (IsListenerRegistered(kPropertyIdBattery)) { + UnregisterBatteryListener(); + } + if (IsListenerRegistered(kPropertyIdCpu)) { + UnregisterCpuListener(); + } + if (IsListenerRegistered(kPropertyIdStorage)) { + UnregisterStorageListener(); + } + if (IsListenerRegistered(kPropertyIdDisplay)) { + UnregisterDisplayListener(); + } + if (IsListenerRegistered(kPropertyIdDeviceOrientation)) { + UnregisterDeviceOrientationListener(); + } + if (IsListenerRegistered(kPropertyIdLocale)) { + UnregisterLocaleListener(); + } + if (IsListenerRegistered(kPropertyIdNetwork)) { + UnregisterNetworkListener(); + } + if (IsListenerRegistered(kPropertyIdWifiNetwork)) { + registered_listeners_.erase(kPropertyIdWifiNetwork) /*HACK*/; + UnregisterWifiNetworkListener(); + } + if (IsListenerRegistered(kPropertyIdEthernetNetwork)) { + registered_listeners_.erase(kPropertyIdEthernetNetwork) /*HACK*/; + UnregisterEthernetNetworkListener(); + } + if (IsListenerRegistered(kPropertyIdCellularNetwork)) { + registered_listeners_.erase(kPropertyIdCellularNetwork) /*HACK*/; + UnregisterCellularNetworkListener(); + } + if (IsListenerRegistered(kPropertyIdPeripheral)) { + UnregisterPeripheralListener(); + } + if (IsListenerRegistered(kPropertyIdMemory)) { + UnregisterMemoryListener(); + } + if (IsListenerRegistered(kPropertyIdCameraFlash)) { + UnregisterCameraFlashListener(); + } if (nullptr != connection_handle_) { connection_destroy(connection_handle_); @@ -534,7 +552,8 @@ void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::o DEFAULT_REPORT_BOOL_CAPABILITY("bluetooth", "tizen.org/feature/network.bluetooth") DEFAULT_REPORT_BOOL_CAPABILITY("nfc", "tizen.org/feature/network.nfc") DEFAULT_REPORT_BOOL_CAPABILITY("nfcReservedPush", "tizen.org/feature/network.nfc.reserved_push") - DEFAULT_REPORT_INT_CAPABILITY("multiTouchCount", "tizen.org/feature/multi_point_touch.point_count") + DEFAULT_REPORT_INT_CAPABILITY("multiTouchCount", + "tizen.org/feature/multi_point_touch.point_count") DEFAULT_REPORT_BOOL_CAPABILITY("inputKeyboard", "tizen.org/feature/input.keyboard") REPORT_BOOL_CAPABILITY("inputKeyboardLayout", SystemInfoDeviceCapability::IsInputKeyboardLayout) DEFAULT_REPORT_BOOL_CAPABILITY("wifi", "tizen.org/feature/network.wifi") @@ -551,7 +570,8 @@ void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::o DEFAULT_REPORT_BOOL_CAPABILITY("speechRecognition", "tizen.org/feature/speech.recognition") DEFAULT_REPORT_BOOL_CAPABILITY("speechSynthesis", "tizen.org/feature/speech.synthesis") DEFAULT_REPORT_BOOL_CAPABILITY("accelerometer", "tizen.org/feature/sensor.accelerometer") - DEFAULT_REPORT_BOOL_CAPABILITY("accelerometerWakeup", "tizen.org/feature/sensor.accelerometer.wakeup") + DEFAULT_REPORT_BOOL_CAPABILITY("accelerometerWakeup", + "tizen.org/feature/sensor.accelerometer.wakeup") DEFAULT_REPORT_BOOL_CAPABILITY("barometer", "tizen.org/feature/sensor.barometer") DEFAULT_REPORT_BOOL_CAPABILITY("barometerWakeup", "tizen.org/feature/sensor.barometer.wakeup") DEFAULT_REPORT_BOOL_CAPABILITY("gyroscope", "tizen.org/feature/sensor.gyroscope") @@ -574,13 +594,12 @@ void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::o DEFAULT_REPORT_BOOL_CAPABILITY("telephony", "tizen.org/feature/network.telephony") DEFAULT_REPORT_BOOL_CAPABILITY("telephonyMms", "tizen.org/feature/network.telephony.mms") DEFAULT_REPORT_BOOL_CAPABILITY("telephonySms", "tizen.org/feature/network.telephony.sms") - REPORT_STRING_CAPABILITY("platformCoreCpuArch", - SystemInfoDeviceCapability::GetPlatfomCoreCpuArch) - REPORT_STRING_CAPABILITY("platformCoreFpuArch", - SystemInfoDeviceCapability::GetPlatfomCoreFpuArch) + REPORT_STRING_CAPABILITY("platformCoreCpuArch", SystemInfoDeviceCapability::GetPlatfomCoreCpuArch) + REPORT_STRING_CAPABILITY("platformCoreFpuArch", SystemInfoDeviceCapability::GetPlatfomCoreFpuArch) DEFAULT_REPORT_BOOL_CAPABILITY("sipVoip", "tizen.org/feature/sip.voip") DEFAULT_REPORT_BOOL_CAPABILITY("magnetometer", "tizen.org/feature/sensor.magnetometer") - DEFAULT_REPORT_BOOL_CAPABILITY("magnetometerWakeup", "tizen.org/feature/sensor.magnetometer.wakeup") + DEFAULT_REPORT_BOOL_CAPABILITY("magnetometerWakeup", + "tizen.org/feature/sensor.magnetometer.wakeup") DEFAULT_REPORT_BOOL_CAPABILITY("photometer", "tizen.org/feature/sensor.photometer") DEFAULT_REPORT_BOOL_CAPABILITY("photometerWakeup", "tizen.org/feature/sensor.photometer.wakeup") DEFAULT_REPORT_BOOL_CAPABILITY("proximity", "tizen.org/feature/sensor.proximity") @@ -589,19 +608,27 @@ void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::o DEFAULT_REPORT_BOOL_CAPABILITY("tiltmeterWakeup", "tizen.org/feature/sensor.tiltmeter.wakeup") DEFAULT_REPORT_BOOL_CAPABILITY("dataEncryption", "tizen.org/feature/database.encryption") DEFAULT_REPORT_BOOL_CAPABILITY("autoRotation", "tizen.org/feature/screen.auto_rotation") - DEFAULT_REPORT_BOOL_CAPABILITY("visionImageRecognition", "tizen.org/feature/vision.image_recognition") - DEFAULT_REPORT_BOOL_CAPABILITY("visionQrcodeGeneration", "tizen.org/feature/vision.qrcode_generation") - DEFAULT_REPORT_BOOL_CAPABILITY("visionQrcodeRecognition", "tizen.org/feature/vision.qrcode_recognition") - DEFAULT_REPORT_BOOL_CAPABILITY("visionFaceRecognition", "tizen.org/feature/vision.face_recognition") + DEFAULT_REPORT_BOOL_CAPABILITY("visionImageRecognition", + "tizen.org/feature/vision.image_recognition") + DEFAULT_REPORT_BOOL_CAPABILITY("visionQrcodeGeneration", + "tizen.org/feature/vision.qrcode_generation") + DEFAULT_REPORT_BOOL_CAPABILITY("visionQrcodeRecognition", + "tizen.org/feature/vision.qrcode_recognition") + DEFAULT_REPORT_BOOL_CAPABILITY("visionFaceRecognition", + "tizen.org/feature/vision.face_recognition") DEFAULT_REPORT_BOOL_CAPABILITY("secureElement", "tizen.org/feature/network.secure_element") REPORT_STRING_CAPABILITY("profile", SystemInfoDeviceCapability::GetProfile) - DEFAULT_REPORT_STRING_CAPABILITY("nativeApiVersion", "tizen.org/feature/platform.native.api.version") + DEFAULT_REPORT_STRING_CAPABILITY("nativeApiVersion", + "tizen.org/feature/platform.native.api.version") DEFAULT_REPORT_STRING_CAPABILITY("duid", "tizen.org/system/tizenid") DEFAULT_REPORT_BOOL_CAPABILITY("screenSizeNormal", "tizen.org/feature/screen.size.normal") - DEFAULT_REPORT_BOOL_CAPABILITY("screenSize480_800", "tizen.org/feature/screen.size.normal.480.800") - DEFAULT_REPORT_BOOL_CAPABILITY("screenSize720_1280", "tizen.org/feature/screen.size.normal.720.1280") + DEFAULT_REPORT_BOOL_CAPABILITY("screenSize480_800", + "tizen.org/feature/screen.size.normal.480.800") + DEFAULT_REPORT_BOOL_CAPABILITY("screenSize720_1280", + "tizen.org/feature/screen.size.normal.720.1280") DEFAULT_REPORT_BOOL_CAPABILITY("shellAppWidget", "tizen.org/feature/shell.appwidget") - DEFAULT_REPORT_BOOL_CAPABILITY("nativeOspCompatible", "tizen.org/feature/platform.native.osp_compatible") + DEFAULT_REPORT_BOOL_CAPABILITY("nativeOspCompatible", + "tizen.org/feature/platform.native.osp_compatible") ReportSuccess(result, *out); LoggerD("Success"); @@ -631,19 +658,21 @@ void SysteminfoManager::GetPropertyValue(const picojson::value& args, picojson:: const std::string& prop_id = args.get("property").get(); LoggerD("Getting property with id: %s ", prop_id.c_str()); - auto get = [this, prop_id, callback_id](const std::shared_ptr& response) -> void { + auto get = [this, prop_id, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Getting"); picojson::value result = picojson::value(picojson::object()); PlatformResult ret = prop_manager_.GetPropertyValue(prop_id, false, &result); async_op_->finish(); if (ret.IsError()) { - LogAndReportError(ret,&(response->get())); + LogAndReportError(ret, &(response->get())); return; } ReportSuccess(result, response->get()); }; - auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto get_response = [this, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Getting response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value{static_cast(callback_id)})); @@ -666,22 +695,22 @@ void SysteminfoManager::GetPropertyValueArray(const picojson::value& args, picoj const std::string& prop_id = args.get("property").get(); LoggerD("Getting property arrray with id: %s ", prop_id.c_str()); - auto get = [this, prop_id, callback_id](const std::shared_ptr& response) -> void { + auto get = [this, prop_id, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Getting"); picojson::value result = picojson::value(picojson::object()); PlatformResult ret = prop_manager_.GetPropertyValue(prop_id, true, &result); async_op_->finish(); if (ret.IsError()) { - LogAndReportError( - ret, &(response->get()), - ("Failed: GetPropertyValue()")); + LogAndReportError(ret, &(response->get()), ("Failed: GetPropertyValue()")); return; } ReportSuccess(result, response->get()); }; - auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto get_response = [this, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Getting response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -706,8 +735,8 @@ void SysteminfoManager::GetTotalMemory(const picojson::value& args, picojson::ob LogAndReportError(ret, out); return; } - result_obj.insert(std::make_pair("totalMemory", - picojson::value(static_cast(return_value)))); + result_obj.insert( + std::make_pair("totalMemory", picojson::value(static_cast(return_value)))); ReportSuccess(result, *out); LoggerD("Success"); @@ -724,8 +753,8 @@ void SysteminfoManager::GetAvailableMemory(const picojson::value& args, picojson LogAndReportError(ret, out); return; } - result_obj.insert(std::make_pair("availableMemory", - picojson::value(static_cast(return_value)))); + result_obj.insert( + std::make_pair("availableMemory", picojson::value(static_cast(return_value)))); ReportSuccess(result, *out); LoggerD("Success"); @@ -742,8 +771,7 @@ void SysteminfoManager::GetCount(const picojson::value& args, picojson::object* unsigned long count = 0; PlatformResult ret = GetPropertyCount(property, &count); if (ret.IsError()) { - LogAndReportError(ret, out, - ("Failed: GetPropertyCount()")); + LogAndReportError(ret, out, ("Failed: GetPropertyCount()")); return; } result_obj.insert(std::make_pair("count", picojson::value(static_cast(count)))); @@ -760,7 +788,7 @@ void SysteminfoManager::AddPropertyValueChangeListener(const picojson::value& ar const std::string& property_name = args.get("property").get(); PlatformResult ret(ErrorCode::NO_ERROR); - if (!IsListenerRegistered(property_name)){ + if (!IsListenerRegistered(property_name)) { LoggerD("Adding listener for property with id: %s ", property_name.c_str()); if (property_name == kPropertyIdBattery) { ret = RegisterBatteryListener(); @@ -773,8 +801,9 @@ void SysteminfoManager::AddPropertyValueChangeListener(const picojson::value& ar } else if (property_name == kPropertyIdDeviceOrientation) { ret = RegisterDeviceOrientationListener(); } else if (property_name == kPropertyIdBuild) { - //should be accepted, but no registration is needed - ret = LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "BUILD property's value is a fixed value"); + // should be accepted, but no registration is needed + ret = LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "BUILD property's value is a fixed value"); } else if (property_name == kPropertyIdLocale) { ret = RegisterLocaleListener(); } else if (property_name == kPropertyIdNetwork) { @@ -786,7 +815,7 @@ void SysteminfoManager::AddPropertyValueChangeListener(const picojson::value& ar } else if (property_name == kPropertyIdCellularNetwork) { ret = RegisterCellularNetworkListener(); } else if (property_name == kPropertyIdSim) { - //SIM listeners are not supported by core API, so we just pass over + // SIM listeners are not supported by core API, so we just pass over LoggerW("SIM listener is not supported by Core API - ignoring"); } else if (property_name == kPropertyIdPeripheral) { ret = RegisterPeripheralListener(); @@ -821,7 +850,7 @@ void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& const std::string& property_name = args.get("property").get(); PlatformResult ret(ErrorCode::NO_ERROR); - if (IsListenerRegistered(property_name)){ + if (IsListenerRegistered(property_name)) { LoggerD("Removing listener for property with id: %s ", property_name.c_str()); registered_listeners_.erase(property_name); if (property_name == kPropertyIdBattery) { @@ -836,8 +865,9 @@ void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& ret = UnregisterDeviceOrientationListener(); } else if (property_name == kPropertyIdBuild) { LoggerW("BUILD property's value is a fixed value"); - //should be accepted, but no unregistration is needed - //ret = PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, "BUILD property's value is a fixed value"); + // should be accepted, but no unregistration is needed + // ret = PlatformResult(ErrorCode::NOT_SUPPORTED_ERR, "BUILD property's value is a fixed + // value"); } else if (property_name == kPropertyIdLocale) { ret = UnregisterLocaleListener(); } else if (property_name == kPropertyIdNetwork) { @@ -849,7 +879,7 @@ void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& } else if (property_name == kPropertyIdCellularNetwork) { ret = UnregisterCellularNetworkListener(); } else if (property_name == kPropertyIdSim) { - //SIM listeners are not supported by core API, so we just pass over + // SIM listeners are not supported by core API, so we just pass over LoggerW("SIM listener is not supported by Core API - ignoring"); } else if (property_name == kPropertyIdPeripheral) { ret = UnregisterPeripheralListener(); @@ -873,16 +903,16 @@ void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& } #define CHECK_LISTENER_ERROR(method) \ - ret = method; \ - if (ret.IsError()) { \ - return ret; \ + ret = method; \ + if (ret.IsError()) { \ + return ret; \ } bool SysteminfoManager::IsIpChangeCallbackNotRegistered() { LoggerD("Entered"); return !(IsListenerRegistered(kPropertyIdWifiNetwork) || - IsListenerRegistered(kPropertyIdEthernetNetwork) || - IsListenerRegistered(kPropertyIdCellularNetwork)); + IsListenerRegistered(kPropertyIdEthernetNetwork) || + IsListenerRegistered(kPropertyIdCellularNetwork)); } PlatformResult SysteminfoManager::RegisterIpChangeCallback() { @@ -890,14 +920,12 @@ PlatformResult SysteminfoManager::RegisterIpChangeCallback() { connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) - int error = connection_set_ip_address_changed_cb(handle, - OnNetworkValueChangedCb, + int error = connection_set_ip_address_changed_cb(handle, OnNetworkValueChangedCb, static_cast(this)); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot register ip change callback", - ("connection_set_ip_address_changed_cb error: %d (%s)", - error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot register ip change callback", + ("connection_set_ip_address_changed_cb error: %d (%s)", error, get_error_message(error))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -910,9 +938,8 @@ PlatformResult SysteminfoManager::UnregisterIpChangeCallback() { int error = connection_unset_ip_address_changed_cb(handle); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot unregister ip change callback", - ("connection_unset_ip_address_changed_cb error: %d (%s)", - error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot unregister ip change callback", + ("connection_unset_ip_address_changed_cb error: %d (%s)", error, get_error_message(error))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -920,32 +947,29 @@ PlatformResult SysteminfoManager::UnregisterIpChangeCallback() { PlatformResult SysteminfoManager::RegisterBatteryListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, - OnBatteryChangedCb, this)) - CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, - OnBatteryChangedCb, this)) - LoggerD("Added callback for BATTERY"); + CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, + OnBatteryChangedCb, this)) + CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, + OnBatteryChangedCb, this)) + LoggerD("Added callback for BATTERY"); return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult SysteminfoManager::UnregisterBatteryListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, - OnBatteryChangedCb)) - CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, - OnBatteryChangedCb)) - LoggerD("Removed callback for BATTERY"); + CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, + OnBatteryChangedCb)) + CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, + OnBatteryChangedCb)) + LoggerD("Removed callback for BATTERY"); return PlatformResult(ErrorCode::NO_ERROR); } PlatformResult SysteminfoManager::RegisterCpuListener() { LoggerD("Entered"); - cpu_event_id_ = g_timeout_add_seconds(kPropertyWatcherTime, OnCpuChangedCb, static_cast(this)); + cpu_event_id_ = + g_timeout_add_seconds(kPropertyWatcherTime, OnCpuChangedCb, static_cast(this)); LoggerD("Added callback for CPU"); return PlatformResult(ErrorCode::NO_ERROR); } @@ -962,11 +986,10 @@ PlatformResult SysteminfoManager::RegisterStorageListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_MMC_STATUS, - OnMmcChangedCb, this)) + SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_MMC_STATUS, OnMmcChangedCb, this)) - storage_event_id_ = g_timeout_add_seconds(kPropertyWatcherTime, - OnStorageChangedCb, static_cast(this)); + storage_event_id_ = + g_timeout_add_seconds(kPropertyWatcherTime, OnStorageChangedCb, static_cast(this)); LoggerD("Added callback for STORAGE"); return PlatformResult(ErrorCode::NO_ERROR); } @@ -986,9 +1009,8 @@ PlatformResult SysteminfoManager::UnregisterStorageListener() { PlatformResult SysteminfoManager::RegisterDisplayListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, - OnDisplayChangedCb, this)) + CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, + OnDisplayChangedCb, this)) LoggerD("Added callback for DISPLAY"); return PlatformResult(ErrorCode::NO_ERROR); } @@ -997,8 +1019,7 @@ PlatformResult SysteminfoManager::UnregisterDisplayListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, - OnDisplayChangedCb)) + SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, OnDisplayChangedCb)) LoggerD("Removed callback for DISPLAY"); return PlatformResult(ErrorCode::NO_ERROR); } @@ -1006,17 +1027,16 @@ PlatformResult SysteminfoManager::UnregisterDisplayListener() { PlatformResult SysteminfoManager::RegisterDeviceOrientationListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, - OnDeviceAutoRotationChangedCb, this)) + CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback( + VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OnDeviceAutoRotationChangedCb, this)) - bool sensor_ret = sensord_register_event(GetSensorHandle(), AUTO_ROTATION_EVENT_CHANGE_STATE, - BASE_GATHERING_INTERVAL, 0, - OnDeviceOrientationChangedCb, this); + bool sensor_ret = + sensord_register_event(GetSensorHandle(), AUTO_ROTATION_EVENT_CHANGE_STATE, + BASE_GATHERING_INTERVAL, 0, OnDeviceOrientationChangedCb, this); if (!sensor_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to register orientation change event listener", - ("sensord_register_event error: %d (%s)", sensor_ret, get_error_message(sensor_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to register orientation change event listener", + ("sensord_register_event error: %d (%s)", sensor_ret, get_error_message(sensor_ret))); } LoggerD("Added callback for DEVICE_ORIENTATION"); @@ -1026,14 +1046,13 @@ PlatformResult SysteminfoManager::RegisterDeviceOrientationListener() { PlatformResult SysteminfoManager::UnregisterDeviceOrientationListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, - OnDeviceAutoRotationChangedCb)) + CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback( + VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OnDeviceAutoRotationChangedCb)) bool sensor_ret = sensord_unregister_event(GetSensorHandle(), AUTO_ROTATION_EVENT_CHANGE_STATE); if (!sensor_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to unregister orientation change event listener", - ("sensord_unregister_event error: %d (%s)", sensor_ret, get_error_message(sensor_ret))); + ErrorCode::UNKNOWN_ERR, "Failed to unregister orientation change event listener", + ("sensord_unregister_event error: %d (%s)", sensor_ret, get_error_message(sensor_ret))); } LoggerD("Removed callback for DEVICE_ORIENTATION"); @@ -1044,11 +1063,9 @@ PlatformResult SysteminfoManager::RegisterLocaleListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_REGIONFORMAT, - OnLocaleChangedCb, this)) + SysteminfoUtils::RegisterVconfCallback(VCONFKEY_REGIONFORMAT, OnLocaleChangedCb, this)) CHECK_LISTENER_ERROR( - SysteminfoUtils::RegisterVconfCallback(VCONFKEY_LANGSET, - OnLocaleChangedCb, this)) + SysteminfoUtils::RegisterVconfCallback(VCONFKEY_LANGSET, OnLocaleChangedCb, this)) LoggerD("Added callback for LOCALE"); return PlatformResult(ErrorCode::NO_ERROR); } @@ -1057,11 +1074,9 @@ PlatformResult SysteminfoManager::UnregisterLocaleListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_REGIONFORMAT, - OnLocaleChangedCb)) + SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_REGIONFORMAT, OnLocaleChangedCb)) CHECK_LISTENER_ERROR( - SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_LANGSET, - OnLocaleChangedCb)) + SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_LANGSET, OnLocaleChangedCb)) LoggerD("Removed callback for LOCALE"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1072,11 +1087,12 @@ PlatformResult SysteminfoManager::RegisterNetworkListener() { connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) - int ntv_ret = connection_set_type_changed_cb(handle, OnNetworkChangedCb, static_cast(this)); + int ntv_ret = + connection_set_type_changed_cb(handle, OnNetworkChangedCb, static_cast(this)); if (CONNECTION_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Registration of listener failed", - ("connection_set_type_changed_cb error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Registration of listener failed", + ("connection_set_type_changed_cb error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } LoggerD("Added callback for NETWORK"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1090,8 +1106,8 @@ PlatformResult SysteminfoManager::UnregisterNetworkListener() { int ntv_ret = connection_unset_type_changed_cb(handle); if (CONNECTION_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Unregistration of listener failed", - ("connection_unset_type_changed_cb error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Unregistration of listener failed", + ("connection_unset_type_changed_cb error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } LoggerD("Removed callback for NETWORK"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1127,7 +1143,7 @@ PlatformResult SysteminfoManager::UnregisterWifiNetworkListener() { PlatformResult SysteminfoManager::RegisterEthernetNetworkListener() { LoggerD("Entered"); PlatformResult ret = SysteminfoUtils::CheckIfEthernetNetworkSupported(); - if (ret.IsError()){ + if (ret.IsError()) { return ret; } @@ -1160,7 +1176,7 @@ PlatformResult SysteminfoManager::RegisterCellularNetworkListener() { LoggerD("Entered"); PlatformResult ret = SysteminfoUtils::CheckTelephonySupport(); if (ret.IsError()) { - return ret; + return ret; } if (IsIpChangeCallbackNotRegistered()) { @@ -1187,8 +1203,8 @@ PlatformResult SysteminfoManager::UnregisterCellularNetworkListener() { // if there is no other ip-relateded listeners left, unregister if (!IsListenerRegistered(kPropertyIdCellularNetwork)) { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback( - VCONFKEY_TELEPHONY_FLIGHT_MODE, OnCellularNetworkValueChangedCb)) + CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_TELEPHONY_FLIGHT_MODE, + OnCellularNetworkValueChangedCb)) CHECK_LISTENER_ERROR(tapi_manager_->UnregisterCallbacks()); } @@ -1208,13 +1224,13 @@ PlatformResult SysteminfoManager::RegisterPeripheralListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; -/* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { - CHECK_LISTENER_ERROR(RegisterVconfCallback(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, - OnPeripheralChangedCb, instance)) - }*/ + /* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { + CHECK_LISTENER_ERROR(RegisterVconfCallback(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, + OnPeripheralChangedCb, instance)) + }*/ if (-1 != vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value)) { - CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_HDMI, - OnPeripheralChangedCb, this)) + CHECK_LISTENER_ERROR( + SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_HDMI, OnPeripheralChangedCb, this)) } LoggerD("Added callback for PERIPHERAL"); @@ -1225,13 +1241,13 @@ PlatformResult SysteminfoManager::UnregisterPeripheralListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; -/* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { - CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, - OnPeripheralChangedCb)) - }*/ + /* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { + CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, + OnPeripheralChangedCb)) + }*/ if (-1 != vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value)) { - CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_HDMI, - OnPeripheralChangedCb)) + CHECK_LISTENER_ERROR( + SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_HDMI, OnPeripheralChangedCb)) } LoggerD("Removed callback for PERIPHERAL"); @@ -1243,8 +1259,8 @@ PlatformResult SysteminfoManager::RegisterMemoryListener() { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; if (-1 != vconf_get_int(VCONFKEY_SYSMAN_LOW_MEMORY, &value)) { - CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_LOW_MEMORY, - OnMemoryChangedCb, this)) + CHECK_LISTENER_ERROR( + SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_LOW_MEMORY, OnMemoryChangedCb, this)) } LoggerD("Added callback for MEMORY"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1255,8 +1271,8 @@ PlatformResult SysteminfoManager::UnregisterMemoryListener() { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; if (-1 != vconf_get_int(VCONFKEY_SYSMAN_LOW_MEMORY, &value)) { - CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_LOW_MEMORY, - OnMemoryChangedCb)) + CHECK_LISTENER_ERROR( + SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_LOW_MEMORY, OnMemoryChangedCb)) } LoggerD("Removed callback for MEMORY"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1264,12 +1280,10 @@ PlatformResult SysteminfoManager::UnregisterMemoryListener() { PlatformResult SysteminfoManager::RegisterCameraFlashListener() { LoggerD("Entered"); - int ret = device_add_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, - OnBrightnessChangedCb, this); + int ret = device_add_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, OnBrightnessChangedCb, this); if (DEVICE_ERROR_NONE != ret) { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error occured", - ("device_add_callback error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error occured", + ("device_add_callback error: %d (%s)", ret, get_error_message(ret))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -1277,12 +1291,11 @@ PlatformResult SysteminfoManager::RegisterCameraFlashListener() { PlatformResult SysteminfoManager::UnregisterCameraFlashListener() { LoggerD("Entered"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); - int ntv_ret = device_remove_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, - OnBrightnessChangedCb); + int ntv_ret = device_remove_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, OnBrightnessChangedCb); if (DEVICE_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Error occured", - ("device_remove_callback error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Error occured", + ("device_remove_callback error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } LoggerD("Removed callback for camera_flash"); return PlatformResult(ErrorCode::NO_ERROR); @@ -1326,8 +1339,7 @@ void SysteminfoManager::GetMaxBrightness(const picojson::value& args, picojson:: if (result != DEVICE_ERROR_NONE) { LogAndReportError( PlatformResult(ErrorCode::UNKNOWN_ERR, "Not supported property"), out, - ("device_flash_get_max_brightness error: %d (%s)", - result, get_error_message(result))); + ("device_flash_get_max_brightness error: %d (%s)", result, get_error_message(result))); return; } ReportSuccess(picojson::value(std::to_string(brightness)), *out); @@ -1338,9 +1350,9 @@ PlatformResult SysteminfoManager::GetPropertyCount(const std::string& property, LoggerD("Enter"); if ("BATTERY" == property || "CPU" == property || "STORAGE" == property || - "DISPLAY" == property || "DEVICE_ORIENTATION" == property || - "BUILD" == property || "LOCALE" == property || "WIFI_NETWORK" == property || - "PERIPHERAL" == property || "MEMORY" == property || "NET_PROXY_NETWORK" == property) { + "DISPLAY" == property || "DEVICE_ORIENTATION" == property || "BUILD" == property || + "LOCALE" == property || "WIFI_NETWORK" == property || "PERIPHERAL" == property || + "MEMORY" == property || "NET_PROXY_NETWORK" == property) { *count = kDefaultPropertyCount; } else if ("CELLULAR_NETWORK" == property || "SIM" == property || "NETWORK" == property) { PlatformResult ret = SysteminfoUtils::CheckTelephonySupport(); @@ -1359,9 +1371,9 @@ PlatformResult SysteminfoManager::GetPropertyCount(const std::string& property, *count = kDefaultPropertyCount; } } else { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Property with given id is not supported", - ("Property %s with given id is not supported", property.c_str())); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Property with given id is not supported", + ("Property %s with given id is not supported", property.c_str())); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -1397,7 +1409,7 @@ PlatformResult SysteminfoManager::ConnectSensor(int* result) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg); } bool ret = sensord_start(handle_orientation, 0); - if(!ret) { + if (!ret) { sensord_disconnect(handle_orientation); std::string log_msg = "Failed to start auto rotation sensor"; return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg); @@ -1450,37 +1462,28 @@ PlatformResult SysteminfoManager::GatherSimInformation(std::size_t index, picojs return tapi_manager_->GatherSimInformation(index, out); } -PlatformResult SysteminfoManager::FetchBasicSimProperties(std::size_t index, - unsigned short* result_mcc, - unsigned short* result_mnc, - unsigned short* result_cell_id, - unsigned short* result_lac, - bool* result_is_roaming, - bool* result_is_flight_mode, - std::string* result_imei) { +PlatformResult SysteminfoManager::FetchBasicSimProperties( + std::size_t index, unsigned short* result_mcc, unsigned short* result_mnc, + unsigned short* result_cell_id, unsigned short* result_lac, bool* result_is_roaming, + bool* result_is_flight_mode, std::string* result_imei) { ScopeLogger(); - return tapi_manager_->FetchBasicSimProperties(index, - result_mcc, - result_mnc, - result_cell_id, - result_lac, - result_is_roaming, - result_is_flight_mode, - result_imei); + return tapi_manager_->FetchBasicSimProperties(index, result_mcc, result_mnc, result_cell_id, + result_lac, result_is_roaming, + result_is_flight_mode, result_imei); } void SysteminfoManager::InitCameraTypes() { LoggerD("Enter"); bool supported = false; - PlatformResult ret = SystemInfoDeviceCapability::GetValueBool( - "tizen.org/feature/camera.back.flash", &supported); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/camera.back.flash", &supported); if (ret.IsSuccess()) { if (supported) { camera_types_.push_back("BACK"); } } - ret = SystemInfoDeviceCapability::GetValueBool( - "tizen.org/feature/camera.front.flash", &supported); + ret = + SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/camera.front.flash", &supported); if (ret.IsSuccess()) { if (supported) { camera_types_.push_back("FRONT"); @@ -1508,8 +1511,8 @@ PlatformResult SysteminfoManager::GetConnectionHandle(connection_h& handle) { int error = connection_create(&connection_handle_); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot create connection", - ("connection_create error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot create connection", + ("connection_create error: %d (%s)", error, get_error_message(error))); } } handle = connection_handle_; @@ -1522,8 +1525,7 @@ bool SysteminfoManager::IsListenerRegistered(const std::string& property_id) { } void SysteminfoManager::PostListenerResponse(const std::string& property_id, - const picojson::value& result, - int property_index) { + const picojson::value& result, int property_index) { LoggerD("Entered"); const std::shared_ptr& response = std::shared_ptr(new picojson::value(picojson::object())); @@ -1533,20 +1535,17 @@ void SysteminfoManager::PostListenerResponse(const std::string& property_id, response->get()[kChangedPropertyIndexString] = picojson::value(static_cast(property_index)); - ReportSuccess(result,response->get()); + ReportSuccess(result, response->get()); Instance::PostMessage(instance_, response->serialize().c_str()); } - -void SysteminfoManager::CallListenerCallback(const std::string& property_id, - int property_index) { +void SysteminfoManager::CallListenerCallback(const std::string& property_id, int property_index) { LoggerD("Enter"); - if(IsListenerRegistered(property_id)) { + if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); picojson::value result = picojson::value(picojson::object()); - PlatformResult ret = GetPropertiesManager().GetPropertyValue( - property_id, true, &result); + PlatformResult ret = GetPropertiesManager().GetPropertyValue(property_id, true, &result); if (ret.IsSuccess()) { PostListenerResponse(property_id, result, property_index); } @@ -1558,11 +1557,10 @@ void SysteminfoManager::CallListenerCallback(const std::string& property_id, void SysteminfoManager::CallCpuListenerCallback() { LoggerD("Enter"); std::string property_id = kPropertyIdCpu; - if(IsListenerRegistered(property_id)) { + if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); picojson::value result = picojson::value(picojson::object()); - PlatformResult ret = GetPropertiesManager().GetPropertyValue( - property_id, true, &result); + PlatformResult ret = GetPropertiesManager().GetPropertyValue(property_id, true, &result); if (ret.IsSuccess()) { if (cpu_load_ == last_cpu_load_) { LoggerD("Cpu load didn't change, ignoring"); @@ -1579,12 +1577,11 @@ void SysteminfoManager::CallCpuListenerCallback() { void SysteminfoManager::CallStorageListenerCallback() { LoggerD("Enter"); std::string property_id = kPropertyIdStorage; - if(IsListenerRegistered(property_id)) { + if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); picojson::value result = picojson::value(picojson::object()); - PlatformResult ret = GetPropertiesManager().GetPropertyValue( - property_id, true, &result); + PlatformResult ret = GetPropertiesManager().GetPropertyValue(property_id, true, &result); if (ret.IsSuccess()) { // check if anything changed if (available_capacity_internal_ == last_available_capacity_internal_ && diff --git a/src/systeminfo/systeminfo_manager.h b/src/systeminfo/systeminfo_manager.h index f2f6e78..12bfff2 100644 --- a/src/systeminfo/systeminfo_manager.h +++ b/src/systeminfo/systeminfo_manager.h @@ -60,19 +60,19 @@ class SysteminfoManager { int GetChangedTapiIndex(TapiHandle* tapi); common::PlatformResult GetNetworkType(std::size_t index, int* network_type); common::PlatformResult GatherSimInformation(std::size_t index, picojson::object* out); - common::PlatformResult FetchBasicSimProperties(std::size_t index, - unsigned short* result_mcc, - unsigned short* result_mnc, - unsigned short* result_cell_id, - unsigned short* result_lac, - bool* result_is_roaming, - bool* result_is_flight_mode, - std::string* result_imei); + common::PlatformResult FetchBasicSimProperties( + std::size_t index, unsigned short* result_mcc, unsigned short* result_mnc, + unsigned short* result_cell_id, unsigned short* result_lac, bool* result_is_roaming, + bool* result_is_flight_mode, std::string* result_imei); common::PlatformResult GetConnectionHandle(connection_h& handle); - SysteminfoInstance* GetInstance() { return instance_;}; - SysteminfoPropertiesManager& GetPropertiesManager() { return prop_manager_;}; + SysteminfoInstance* GetInstance() { + return instance_; + }; + SysteminfoPropertiesManager& GetPropertiesManager() { + return prop_manager_; + }; void SetCpuInfoLoad(double load); void SetAvailableCapacityInternal(unsigned long long capacity); @@ -84,6 +84,7 @@ class SysteminfoManager { void CallListenerCallback(const std::string& property_id, int property_index = 0); void CallCpuListenerCallback(); void CallStorageListenerCallback(); + private: class TapiManager; class AsynchronousOperation; @@ -155,7 +156,7 @@ class SysteminfoManager { std::unique_ptr async_op_; }; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi -#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_MANAGER_H__ +#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_MANAGER_H__ diff --git a/src/systeminfo/systeminfo_properties_manager.cc b/src/systeminfo/systeminfo_properties_manager.cc index fc45f6a..ec0218a 100644 --- a/src/systeminfo/systeminfo_properties_manager.cc +++ b/src/systeminfo/systeminfo_properties_manager.cc @@ -18,21 +18,21 @@ #include -#include -#include -#include +#include #include +#include +#include #include -#include #include -#include +#include +#include -#include "systeminfo/systeminfo_manager.h" -#include "systeminfo/systeminfo_device_capability.h" +#include "common/GDBus/connection.h" +#include "common/filesystem/filesystem_provider.h" #include "common/scope_exit.h" #include "systeminfo/systeminfo-utils.h" -#include "common/filesystem/filesystem_provider.h" -#include "common/GDBus/connection.h" +#include "systeminfo/systeminfo_device_capability.h" +#include "systeminfo/systeminfo_manager.h" namespace extension { namespace systeminfo { @@ -44,24 +44,24 @@ namespace { const std::string kMemoryStateNormal = "NORMAL"; const std::string kMemoryStateWarinig = "WARNING"; const double kDisplayInchToMillimeter = 25.4; -//Battery +// Battery const double kRemainingBatteryChargeMax = 100.0; const int kVconfErrorNone = 0; -const char *kBatteryTarget = "org.tizen.resourced"; -const char *kBatteryObject = "/Org/Tizen/ResourceD/Logging"; -const char *kBatteryInterface = "org.tizen.resourced.logging"; -const char *kBatteryGetBatteryChargingTime = "GetBatteryChargingTime"; -const char *kBatteryGetBatteryRemainingTime = "GetBatteryRemainingTime"; -//Display +const char* kBatteryTarget = "org.tizen.resourced"; +const char* kBatteryObject = "/Org/Tizen/ResourceD/Logging"; +const char* kBatteryInterface = "org.tizen.resourced.logging"; +const char* kBatteryGetBatteryChargingTime = "GetBatteryChargingTime"; +const char* kBatteryGetBatteryRemainingTime = "GetBatteryRemainingTime"; +// Display const double kDisplayBrightnessDivideValue = 100; -//Device Orientation +// Device Orientation const std::string kOrientationPortraitPrimary = "PORTRAIT_PRIMARY"; const std::string kOrientationPortraitSecondary = "PORTRAIT_SECONDARY"; const std::string kOrientationLandscapePrimary = "LANDSCAPE_PRIMARY"; const std::string kOrientationLandscapeSecondary = "LANDSCAPE_SECONDARY"; -//Peripheral +// Peripheral const std::string kVideoOutputString = "isVideoOutputOn"; -//Storage +// Storage const std::string kStorageInternalPath = std::string(tzplatform_getenv(TZ_USER_CONTENT)); const std::string kStorageSdcardPath = std::string(tzplatform_getenv(TZ_SYS_MEDIA)) + "/sdcard"; const std::string kPropertyIdStorage = "STORAGE"; @@ -70,7 +70,7 @@ const std::string kTypeInternal = "INTERNAL"; const std::string kTypeUsbDevice = "USB_DEVICE"; const std::string kTypeUsbHost = "USB_HOST"; const std::string kTypeMmc = "MMC"; -//Network +// Network enum NetworkType { kNone, kType2G, @@ -92,11 +92,11 @@ const char* kNetworkTypeWifi = "WIFI"; const char* kNetworkTypeEthernet = "ETHERNET"; const char* kNetworkTypeProxy = "NET_PROXY"; const char* kNetworkTypeUnknown = "UNKNOWN"; -//Wifi Network +// Wifi Network const std::string kWifiStatusOn = "ON"; const std::string kWifiStatusOff = "OFF"; const int kWifiSignalStrengthDivideValue = 100; -//Cellular Network +// Cellular Network const char* kConnectionOff = "OFF"; const char* kConnectionOn = "ON"; } @@ -120,13 +120,13 @@ PlatformResult SysteminfoPropertiesManager::GetPropertyValue(const std::string& return ReportProperty(property, 0, &res_obj); } else { picojson::object& array_result_obj = res->get(); - picojson::array& array = array_result_obj.insert( - std::make_pair("array", picojson::value(picojson::array()))). - first->second.get(); + picojson::array& array = + array_result_obj.insert(std::make_pair("array", picojson::value(picojson::array()))) + .first->second.get(); unsigned long property_count = 0; PlatformResult ret = manager_.GetPropertyCount(property, &property_count); - if (ret.IsError()){ + if (ret.IsError()) { LoggerD("Property is not available"); return ret; } @@ -138,14 +138,14 @@ PlatformResult SysteminfoPropertiesManager::GetPropertyValue(const std::string& picojson::object& result_obj = result.get(); PlatformResult ret = ReportProperty(property, i, &result_obj); - if (ret.IsError()){ + if (ret.IsError()) { return ret; } array.push_back(result); } if (property_count == 0) { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Property with given id is not supported"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Property with given id is not supported"); } } @@ -153,9 +153,9 @@ PlatformResult SysteminfoPropertiesManager::GetPropertyValue(const std::string& } PlatformResult SysteminfoPropertiesManager::ReportProperty(const std::string& property, int index, - picojson::object* res_obj) { + picojson::object* res_obj) { LoggerD("Entered"); - if ("BATTERY" == property){ + if ("BATTERY" == property) { return ReportBattery(res_obj); } else if ("CPU" == property) { return ReportCpu(res_obj); @@ -190,8 +190,8 @@ PlatformResult SysteminfoPropertiesManager::ReportProperty(const std::string& pr } else if ("ADS" == property) { return ReportAds(res_obj); } - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Property with given id is not supported"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Property with given id is not supported"); } /// BATTERY @@ -201,19 +201,18 @@ PlatformResult SysteminfoPropertiesManager::ReportBattery(picojson::object* out) int ret = vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CAPACITY, &value); if (kVconfErrorNone != ret) { std::string log_msg = "Platform error while getting battery detail: "; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, (log_msg + std::to_string(ret)), - ("vconf_get_int error: %d (%s)", ret, get_error_message(ret))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, (log_msg + std::to_string(ret)), + ("vconf_get_int error: %d (%s)", ret, get_error_message(ret))); } - out->insert(std::make_pair("level", picojson::value(static_cast(value)/kRemainingBatteryChargeMax))); + out->insert(std::make_pair( + "level", picojson::value(static_cast(value) / kRemainingBatteryChargeMax))); value = 0; ret = vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, &value); if (kVconfErrorNone != ret) { - std::string log_msg = "Platform error while getting battery charging: "; - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, (log_msg + std::to_string(ret)), - ("vconf_get_int error: %d (%s)", ret, get_error_message(ret))); + std::string log_msg = "Platform error while getting battery charging: "; + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, (log_msg + std::to_string(ret)), + ("vconf_get_int error: %d (%s)", ret, get_error_message(ret))); } bool isCharging = (0 != value); out->insert(std::make_pair("isCharging", picojson::value(isCharging))); @@ -223,41 +222,30 @@ PlatformResult SysteminfoPropertiesManager::ReportBattery(picojson::object* out) } GError* error = nullptr; - GVariant *variant = nullptr; + GVariant* variant = nullptr; if (isCharging) { variant = g_dbus_connection_call_sync(common::dbus::Connection::getInstance().getDBus(), - kBatteryTarget, - kBatteryObject, - kBatteryInterface, - kBatteryGetBatteryChargingTime, - g_variant_new("()"), - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); + kBatteryTarget, kBatteryObject, kBatteryInterface, + kBatteryGetBatteryChargingTime, g_variant_new("()"), NULL, + G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); } else { variant = g_dbus_connection_call_sync(common::dbus::Connection::getInstance().getDBus(), - kBatteryTarget, - kBatteryObject, - kBatteryInterface, + kBatteryTarget, kBatteryObject, kBatteryInterface, kBatteryGetBatteryRemainingTime, - g_variant_new("(i)", 0), // 0 - POWER_NORMAL_MODE - NULL, // 1 - POWER_SAVING_MODE - G_DBUS_CALL_FLAGS_NONE, // 2 - ULTRA_SAVING_MODE - -1, // for now, only 0 is supported - NULL, - &error); + g_variant_new("(i)", 0), // 0 - POWER_NORMAL_MODE + NULL, // 1 - POWER_SAVING_MODE + G_DBUS_CALL_FLAGS_NONE, // 2 - ULTRA_SAVING_MODE + -1, // for now, only 0 is supported + NULL, &error); } if (!variant || error) { std::string message = error ? error->message : ""; g_error_free(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, - "DBus returned error", + ErrorCode::UNKNOWN_ERR, "DBus returned error", ("Failed to call %s method - %s", - isCharging ? "GetBatteryChargingTime" : "GetBatteryRemainingTime", message.c_str())); + isCharging ? "GetBatteryChargingTime" : "GetBatteryRemainingTime", message.c_str())); } else { int time = 0; g_variant_get(variant, "(i)", &time); @@ -278,7 +266,7 @@ PlatformResult SysteminfoPropertiesManager::ReportBattery(picojson::object* out) PlatformResult SysteminfoPropertiesManager::ReportCpu(picojson::object* out) { LoggerD("Entered"); static CpuInfo cpu_info; - FILE *fp = nullptr; + FILE* fp = nullptr; fp = fopen("/proc/stat", "r"); if (nullptr == fp) { std::string error_msg("Can not open /proc/stat for reading"); @@ -291,15 +279,15 @@ PlatformResult SysteminfoPropertiesManager::ReportCpu(picojson::object* out) { long long idle = 0; double load = 0; - int read_ret = fscanf( fp, "%*s %lld %lld %lld %lld", &usr, &system, &nice, &idle); + int read_ret = fscanf(fp, "%*s %lld %lld %lld %lld", &usr, &system, &nice, &idle); fclose(fp); if (4 == read_ret) { - long long total = usr + nice + system + idle - cpu_info.usr - cpu_info.nice - - cpu_info.system - cpu_info.idle; + long long total = + usr + nice + system + idle - cpu_info.usr - cpu_info.nice - cpu_info.system - cpu_info.idle; long long diff_idle = idle - cpu_info.idle; - if (( total > 0LL ) && ( diff_idle > 0LL )) { - load = static_cast< double >( diff_idle ) * 100LL / total; + if ((total > 0LL) && (diff_idle > 0LL)) { + load = static_cast(diff_idle) * 100LL / total; cpu_info.usr = usr; cpu_info.system = system; cpu_info.nice = nice; @@ -310,14 +298,14 @@ PlatformResult SysteminfoPropertiesManager::ReportCpu(picojson::object* out) { load = cpu_info.load; } } else { - std::string error_msg( "Could not read /proc/stat" ); + std::string error_msg("Could not read /proc/stat"); return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_msg); } manager_.SetCpuInfoLoad(cpu_info.load); load = 100 - load; - LoggerD("Cpu load : %f", load ); + LoggerD("Cpu load : %f", load); out->insert(std::make_pair("load", picojson::value(load / 100.0))); return PlatformResult(ErrorCode::NO_ERROR); } @@ -334,70 +322,68 @@ PlatformResult SysteminfoPropertiesManager::ReportDisplay(picojson::object* out) double scaledBrightness; // FETCH RESOLUTION - int ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.width", - &screenWidth); + int ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.width", &screenWidth); if (SYSTEM_INFO_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get value of screen width", - ("system_info_get_platform_int error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Cannot get value of screen width", + ("system_info_get_platform_int error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.height", - &screenHeight); + ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.height", &screenHeight); if (SYSTEM_INFO_ERROR_NONE != ntv_ret) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get value of screen height", - ("system_info_get_platform_int error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Cannot get value of screen height", + ("system_info_get_platform_int error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - //FETCH DOTS PER INCH - int dots_per_inch=0; - ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.dpi", - &dots_per_inch); + // FETCH DOTS PER INCH + int dots_per_inch = 0; + ntv_ret = system_info_get_platform_int("tizen.org/feature/screen.dpi", &dots_per_inch); if (SYSTEM_INFO_ERROR_NONE == ntv_ret) { dotsPerInchWidth = dots_per_inch; dotsPerInchHeight = dots_per_inch; } else { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get 'tizen.org/feature/screen.dpi' value", - ("system_info_get_platform_int error: %d (%s)", - ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Cannot get 'tizen.org/feature/screen.dpi' value", + ("system_info_get_platform_int error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } - //FETCH PHYSICAL WIDTH + // FETCH PHYSICAL WIDTH if (dotsPerInchWidth != 0 && screenWidth != 0) { - physicalWidth = (static_cast(screenWidth) / dotsPerInchWidth) * kDisplayInchToMillimeter; + physicalWidth = + (static_cast(screenWidth) / dotsPerInchWidth) * kDisplayInchToMillimeter; } else { std::string log_msg = "Failed to get physical screen width value"; - LoggerE("%s, screenWidth : %d, dotsPerInchWidth: %d", log_msg.c_str(), - screenWidth, dotsPerInchWidth); + LoggerE("%s, screenWidth : %d, dotsPerInchWidth: %d", log_msg.c_str(), screenWidth, + dotsPerInchWidth); } - //FETCH PHYSICAL HEIGHT + // FETCH PHYSICAL HEIGHT if (dotsPerInchHeight != 0 && screenHeight != 0) { - physicalHeight = (static_cast(screenHeight) / dotsPerInchHeight) * kDisplayInchToMillimeter; + physicalHeight = + (static_cast(screenHeight) / dotsPerInchHeight) * kDisplayInchToMillimeter; } else { std::string log_msg = "Failed to get physical screen height value"; - LoggerE("%s, screenHeight : %d, dotsPerInchHeight: %d", log_msg.c_str(), - screenHeight, dotsPerInchHeight); + LoggerE("%s, screenHeight : %d, dotsPerInchHeight: %d", log_msg.c_str(), screenHeight, + dotsPerInchHeight); } - //FETCH BRIGHTNESS + // FETCH BRIGHTNESS int brightness; ntv_ret = vconf_get_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, &brightness); if (kVconfErrorNone == ntv_ret) { - scaledBrightness = static_cast(brightness)/kDisplayBrightnessDivideValue; + scaledBrightness = static_cast(brightness) / kDisplayBrightnessDivideValue; } else { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get brightness value of display", - ("vconf_get_int error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); + ErrorCode::UNKNOWN_ERR, "Cannot get brightness value of display", + ("vconf_get_int error: %d (%s)", ntv_ret, get_error_message(ntv_ret))); } out->insert(std::make_pair("resolutionWidth", picojson::value(std::to_string(screenWidth)))); out->insert(std::make_pair("resolutionHeight", picojson::value(std::to_string(screenHeight)))); - out->insert(std::make_pair("dotsPerInchWidth", picojson::value(std::to_string(dotsPerInchWidth)))); - out->insert(std::make_pair("dotsPerInchHeight", picojson::value(std::to_string(dotsPerInchHeight)))); + out->insert( + std::make_pair("dotsPerInchWidth", picojson::value(std::to_string(dotsPerInchWidth)))); + out->insert( + std::make_pair("dotsPerInchHeight", picojson::value(std::to_string(dotsPerInchHeight)))); out->insert(std::make_pair("physicalWidth", picojson::value(std::to_string(physicalWidth)))); out->insert(std::make_pair("physicalHeight", picojson::value(std::to_string(physicalHeight)))); out->insert(std::make_pair("brightness", picojson::value(scaledBrightness))); @@ -409,16 +395,14 @@ PlatformResult SysteminfoPropertiesManager::FetchIsAutoRotation(bool* result) { LoggerD("Entered"); int is_auto_rotation = 0; - if ( 0 == vconf_get_bool( - VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, &is_auto_rotation)) { + if (0 == vconf_get_bool(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, &is_auto_rotation)) { if (is_auto_rotation) { *result = true; } else { *result = false; } return PlatformResult(ErrorCode::NO_ERROR); - } - else { + } else { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL check failed"); } @@ -430,11 +414,10 @@ PlatformResult SysteminfoPropertiesManager::FetchStatus(std::string* result) { std::string status = kOrientationPortraitPrimary; sensor_data_t data; - bool ret = sensord_get_data(manager_.GetSensorHandle(), - AUTO_ROTATION_BASE_DATA_SET, &data); + bool ret = sensord_get_data(manager_.GetSensorHandle(), AUTO_ROTATION_BASE_DATA_SET, &data); if (ret) { LoggerD("size of the data value array:%d", data.value_count); - if (data.value_count > 0 ) { + if (data.value_count > 0) { rotation = data.values[0]; LoggerD("rotation is: %d", rotation); } else { @@ -444,7 +427,6 @@ PlatformResult SysteminfoPropertiesManager::FetchStatus(std::string* result) { LoggerE("Failed to get data(sensord_get_data). Default rotation would be returned."); } - switch (rotation) { case AUTO_ROTATION_DEGREE_UNKNOWN: case AUTO_ROTATION_DEGREE_0: @@ -464,9 +446,8 @@ PlatformResult SysteminfoPropertiesManager::FetchStatus(std::string* result) { status = kOrientationLandscapeSecondary; break; default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Received unexpected data", - ("Received unexpected data: %u", rotation)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Received unexpected data", + ("Received unexpected data: %u", rotation)); } *result = status; return PlatformResult(ErrorCode::NO_ERROR); @@ -492,20 +473,18 @@ PlatformResult SysteminfoPropertiesManager::ReportDeviceOrientation(picojson::ob PlatformResult SysteminfoPropertiesManager::ReportBuild(picojson::object* out) { LoggerD("Entered"); std::string model = ""; - PlatformResult ret = SystemInfoDeviceCapability::GetValueString( - "tizen.org/system/model_name", &model); + PlatformResult ret = + SystemInfoDeviceCapability::GetValueString("tizen.org/system/model_name", &model); if (ret.IsError()) { return ret; } std::string manufacturer = ""; - ret = SystemInfoDeviceCapability::GetValueString( - "tizen.org/system/manufacturer", &manufacturer); + ret = SystemInfoDeviceCapability::GetValueString("tizen.org/system/manufacturer", &manufacturer); if (ret.IsError()) { return ret; } std::string buildVersion = ""; - ret = SystemInfoDeviceCapability::GetValueString( - "tizen.org/system/build.string", &buildVersion); + ret = SystemInfoDeviceCapability::GetValueString("tizen.org/system/build.string", &buildVersion); if (ret.IsError()) { return ret; } @@ -520,8 +499,8 @@ PlatformResult SysteminfoPropertiesManager::ReportBuild(picojson::object* out) { PlatformResult SysteminfoPropertiesManager::ReportLocale(picojson::object* out) { LoggerD("Entered"); std::string str_language = ""; - PlatformResult ret = SysteminfoUtils::GetRuntimeInfoString( - SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &str_language); + PlatformResult ret = + SysteminfoUtils::GetRuntimeInfoString(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &str_language); if (ret.IsError()) { return ret; } @@ -569,80 +548,78 @@ static PlatformResult GetNetworkTypeString(NetworkType type, std::string& type_s type_string = kNetworkTypeUnknown; break; default: - return LogAndCreateResult( - ErrorCode::TYPE_MISMATCH_ERR, "Incorrect type", - ("Incorrect type: %d", type)); + return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Incorrect type", + ("Incorrect type: %d", type)); } return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SysteminfoPropertiesManager::ReportNetwork(picojson::object* out, unsigned long count) { +PlatformResult SysteminfoPropertiesManager::ReportNetwork(picojson::object* out, + unsigned long count) { LoggerD("Entered with index property %d", count); connection_h connection_handle = nullptr; connection_type_e connection_type = CONNECTION_TYPE_DISCONNECTED; int networkType = 0; NetworkType type = kNone; - //connection must be created in every call, in other case error occurs + // connection must be created in every call, in other case error occurs int error = connection_create(&connection_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot create connection: " + std::to_string(error); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_create error: %d (%s)", error, get_error_message(error))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg, ("connection_create error: %d (%s)", + error, get_error_message(error))); } - std::unique_ptr::type, int(*)(connection_h)> - connection_handle_ptr(connection_handle, &connection_destroy); + std::unique_ptr::type, int (*)(connection_h)> + connection_handle_ptr(connection_handle, &connection_destroy); // automatically release the memory error = connection_get_type(connection_handle, &connection_type); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot get connection type: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_type error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_type error: %d (%s)", error, get_error_message(error))); } switch (connection_type) { - case CONNECTION_TYPE_DISCONNECTED : + case CONNECTION_TYPE_DISCONNECTED: type = kNone; break; - case CONNECTION_TYPE_WIFI : - type = kWifi; + case CONNECTION_TYPE_WIFI: + type = kWifi; break; - case CONNECTION_TYPE_CELLULAR : + case CONNECTION_TYPE_CELLULAR: if (manager_.GetNetworkType(count, &networkType)) { if (networkType < TAPI_NETWORK_SERVICE_TYPE_2G) { - type = kNone; + type = kNone; } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_2G) { - type = kType2G; - } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_2_5G - || networkType == TAPI_NETWORK_SERVICE_TYPE_2_5G_EDGE) { - type = kType2_5G; - } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_3G - || networkType == TAPI_NETWORK_SERVICE_TYPE_HSDPA) { - type = kType3G; + type = kType2G; + } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_2_5G || + networkType == TAPI_NETWORK_SERVICE_TYPE_2_5G_EDGE) { + type = kType2_5G; + } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_3G || + networkType == TAPI_NETWORK_SERVICE_TYPE_HSDPA) { + type = kType3G; } else if (networkType == TAPI_NETWORK_SERVICE_TYPE_LTE) { - type = kType4G; + type = kType4G; } else { - type = kNone; + type = kNone; } } break; - case CONNECTION_TYPE_ETHERNET : - type = kEthernet; + case CONNECTION_TYPE_ETHERNET: + type = kEthernet; break; - case CONNECTION_TYPE_NET_PROXY : - type = kProxy; + case CONNECTION_TYPE_NET_PROXY: + type = kProxy; break; default: - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Incorrect type", - ("Incorrect type: %d", connection_type)); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Incorrect type", + ("Incorrect type: %d", connection_type)); } std::string type_str = ""; PlatformResult ret = GetNetworkTypeString(type, type_str); - if(ret.IsError()) { + if (ret.IsError()) { return ret; } out->insert(std::make_pair("networkType", picojson::value(type_str))); @@ -651,30 +628,28 @@ PlatformResult SysteminfoPropertiesManager::ReportNetwork(picojson::object* out, /// WIFI_NETWORK static PlatformResult GetIpsWifi(wifi_manager_ap_h wifi_ap_handle, std::string* ip_addr_str, - std::string* ipv6_addr_str) { + std::string* ipv6_addr_str) { LoggerD("Entered"); - //getting ipv4 address + // getting ipv4 address char* ip_addr = nullptr; - int error = wifi_manager_ap_get_ip_address(wifi_ap_handle, - WIFI_MANAGER_ADDRESS_FAMILY_IPV4, - &ip_addr); + int error = + wifi_manager_ap_get_ip_address(wifi_ap_handle, WIFI_MANAGER_ADDRESS_FAMILY_IPV4, &ip_addr); if (WIFI_MANAGER_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get ip address", - ("wifi_manager_ap_get_ip_address error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get ip address", + ("wifi_manager_ap_get_ip_address error: %d (%s)", error, get_error_message(error))); } *ip_addr_str = ip_addr; free(ip_addr); - //getting ipv6 address + // getting ipv6 address ip_addr = nullptr; - error = wifi_manager_ap_get_ip_address(wifi_ap_handle, - WIFI_MANAGER_ADDRESS_FAMILY_IPV6, - &ip_addr); + error = + wifi_manager_ap_get_ip_address(wifi_ap_handle, WIFI_MANAGER_ADDRESS_FAMILY_IPV6, &ip_addr); if (WIFI_MANAGER_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get ipv6 address", - ("Failed to get ipv6 address: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get ipv6 address", + ("Failed to get ipv6 address: %d (%s)", error, get_error_message(error))); } *ipv6_addr_str = ip_addr; free(ip_addr); @@ -682,35 +657,33 @@ static PlatformResult GetIpsWifi(wifi_manager_ap_h wifi_ap_handle, std::string* } /// CELLULAR_NETWORK and ETHERNET_NETWORK -static PlatformResult GetIpsFromProfile(connection_profile_h profile_handle, std::string* ip_addr_str, - std::string* ipv6_addr_str){ +static PlatformResult GetIpsFromProfile(connection_profile_h profile_handle, + std::string* ip_addr_str, std::string* ipv6_addr_str) { LoggerD("Entered"); - //getting ipv4 address + // getting ipv4 address char* ip_addr = nullptr; - int error = connection_profile_get_ip_address(profile_handle, - CONNECTION_ADDRESS_FAMILY_IPV4, - &ip_addr); + int error = + connection_profile_get_ip_address(profile_handle, CONNECTION_ADDRESS_FAMILY_IPV4, &ip_addr); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get ip address", - ("Failed to get ip address: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get ip address", + ("Failed to get ip address: %d (%s)", error, get_error_message(error))); } *ip_addr_str = ip_addr; free(ip_addr); - //getting ipv6 address + // getting ipv6 address ip_addr = nullptr; - error = connection_profile_get_ip_address(profile_handle, - CONNECTION_ADDRESS_FAMILY_IPV6, - &ip_addr); + error = + connection_profile_get_ip_address(profile_handle, CONNECTION_ADDRESS_FAMILY_IPV6, &ip_addr); if (CONNECTION_ERROR_NONE == error) { *ipv6_addr_str = ip_addr; free(ip_addr); } else if (CONNECTION_ERROR_ADDRESS_FAMILY_NOT_SUPPORTED != error) { - //core api returns error -97 = CONNECTION_ERROR_ADDRESS_FAMILY_NOT_SUPPORTED - //it will be supported in the future. For now let's ignore this error + // core api returns error -97 = CONNECTION_ERROR_ADDRESS_FAMILY_NOT_SUPPORTED + // it will be supported in the future. For now let's ignore this error return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get ipv6 address", - ("Failed to get ipv6 address: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get ipv6 address", + ("Failed to get ipv6 address: %d (%s)", error, get_error_message(error))); } return PlatformResult(ErrorCode::NO_ERROR); } @@ -731,8 +704,8 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* if (WIFI_MANAGER_ERROR_NONE != error) { std::string log_msg = "Initialization failed: " + std::string(get_error_message(error)); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("wifi_manager_initialize error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("wifi_manager_initialize error: %d (%s)", error, get_error_message(error))); } else { LoggerD("WIFI initialization succeed"); } @@ -744,14 +717,14 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* // check if wifi is activated error = wifi_manager_is_activated(wifi_manager, &result_status); if (WIFI_MANAGER_ERROR_NONE != error) { - std::string log_msg = "Checking if wifi is activated failed: " + - std::string(get_error_message(error)); + std::string log_msg = + "Checking if wifi is activated failed: " + std::string(get_error_message(error)); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("wifi_manager_is_activated error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("wifi_manager_is_activated error: %d (%s)", error, get_error_message(error))); } - //gathering mac address + // gathering mac address char* mac = nullptr; error = wifi_manager_get_mac_address(wifi_manager, &mac); if (WIFI_MANAGER_ERROR_NONE == error && nullptr != mac) { @@ -761,8 +734,8 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* } else { std::string log_msg = "Failed to get mac address: " + std::string(get_error_message(error)); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("wifi_manager_get_mac_address error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("wifi_manager_get_mac_address error: %d (%s)", error, get_error_message(error))); } wifi_manager_ap_h wifi_ap_handle = nullptr; @@ -771,48 +744,49 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* error = wifi_manager_get_connected_ap(wifi_manager, &wifi_ap_handle); if (WIFI_MANAGER_ERROR_NONE != error && WIFI_MANAGER_ERROR_NO_CONNECTION != error) { LoggerD("Error while wifi_get_connnected_ap: %s", get_error_message(error)); - std::string log_msg = "Cannot get connected access point handle: " + - std::string(get_error_message(error)); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("wifi_manager_get_connected_ap error: %d (%s)", error, get_error_message(error))); - } + std::string log_msg = + "Cannot get connected access point handle: " + std::string(get_error_message(error)); + return LogAndCreateResult( + ErrorCode::UNKNOWN_ERR, log_msg, + ("wifi_manager_get_connected_ap error: %d (%s)", error, get_error_message(error))); + } - std::unique_ptr::type, int(*)(wifi_manager_ap_h)> - wifi_ap_handle_ptr(wifi_ap_handle, &wifi_manager_ap_destroy); + std::unique_ptr::type, int (*)(wifi_manager_ap_h)> + wifi_ap_handle_ptr(wifi_ap_handle, &wifi_manager_ap_destroy); // automatically release the memory if (WIFI_MANAGER_ERROR_NO_CONNECTION != error) { - //refreshing access point information + // refreshing access point information error = wifi_manager_ap_refresh(wifi_ap_handle); if (WIFI_MANAGER_ERROR_NONE != error) { - std::string log_msg = "Failed to refresh access point information: " + - std::string(get_error_message(error)); + std::string log_msg = + "Failed to refresh access point information: " + std::string(get_error_message(error)); return LogAndCreateResult( ErrorCode::UNKNOWN_ERR, log_msg, ("wifi_manager_ap_refresh error: %d (%s)", error, get_error_message(error))); } - //gathering ssid + // gathering ssid char* essid = nullptr; error = wifi_manager_ap_get_essid(wifi_ap_handle, &essid); if (WIFI_MANAGER_ERROR_NONE == error) { result_ssid = essid; free(essid); } else { - std::string log_msg = "Failed to get network ssid: " + std::string(get_error_message(error)); + std::string log_msg = + "Failed to get network ssid: " + std::string(get_error_message(error)); return LogAndCreateResult( ErrorCode::UNKNOWN_ERR, log_msg, ("wifi_manager_ap_get_essid error: %d (%s)", error, get_error_message(error))); } - //gathering ips + // gathering ips PlatformResult ret = GetIpsWifi(wifi_ap_handle, &result_ip_address, &result_ipv6_address); if (ret.IsError()) { return ret; } - //gathering strength + // gathering strength wifi_manager_rssi_level_e rssi_level = manager_.GetWifiLevel(); // this mean that level was not initialized or wifi not connected if (WIFI_MANAGER_RSSI_LEVEL_0 == rssi_level) { @@ -820,27 +794,29 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* int rssi = 0; error = wifi_manager_ap_get_rssi(wifi_ap_handle, &rssi); if (WIFI_MANAGER_ERROR_NONE == error) { - result_signal_strength = ((double) abs(rssi))/kWifiSignalStrengthDivideValue; + result_signal_strength = ((double)abs(rssi)) / kWifiSignalStrengthDivideValue; } else { - std::string log_msg = "Failed to get signal strength: " + - std::string(get_error_message(error)); + std::string log_msg = + "Failed to get signal strength: " + std::string(get_error_message(error)); return LogAndCreateResult( ErrorCode::UNKNOWN_ERR, log_msg, ("wifi_manager_ap_get_rssi error: %d (%s)", error, get_error_message(error))); } } else { - result_signal_strength = ((double) rssi_level)/WIFI_MANAGER_RSSI_LEVEL_4; + result_signal_strength = ((double)rssi_level) / WIFI_MANAGER_RSSI_LEVEL_4; } } } - //building result object - out->insert(std::make_pair("status", picojson::value(result_status ? kWifiStatusOn : kWifiStatusOff))); + // building result object + out->insert( + std::make_pair("status", picojson::value(result_status ? kWifiStatusOn : kWifiStatusOff))); out->insert(std::make_pair("ssid", picojson::value(result_ssid))); out->insert(std::make_pair("ipAddress", picojson::value(result_ip_address))); out->insert(std::make_pair("ipv6Address", picojson::value(result_ipv6_address))); out->insert(std::make_pair("macAddress", picojson::value(result_mac_address))); - out->insert(std::make_pair("signalStrength", picojson::value(std::to_string(result_signal_strength)))); + out->insert( + std::make_pair("signalStrength", picojson::value(std::to_string(result_signal_strength)))); return PlatformResult(ErrorCode::NO_ERROR); } @@ -864,25 +840,25 @@ PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::obje int error = connection_create(&connection_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot create connection: " + std::to_string(error); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_create error: %d (%s)", error, get_error_message(error))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg, ("connection_create error: %d (%s)", + error, get_error_message(error))); } - std::unique_ptr::type, int (*)(connection_h)> connection_handle_ptr( - connection_handle, &connection_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(connection_h)> + connection_handle_ptr(connection_handle, + &connection_destroy); // automatically release the memory error = connection_get_ethernet_state(connection_handle, &connection_state); if (CONNECTION_ERROR_NONE != error) { if (CONNECTION_ERROR_NOT_SUPPORTED == error) { std::string log_msg = "Cannot get ethernet connection state: Not supported"; return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, log_msg, - ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); + ErrorCode::NOT_SUPPORTED_ERR, log_msg, + ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); } std::string log_msg = "Cannot get ethernet connection state: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_ethernet_state error: %d (%s)", error, get_error_message(error))); } switch (connection_state) { @@ -908,9 +884,8 @@ PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::obje if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot get ethernet cable state: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_ethernet_cable_state error: %d (%s)", - error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_ethernet_cable_state error: %d (%s)", error, get_error_message(error))); } switch (cable_state) { @@ -936,34 +911,34 @@ PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::obje } else { std::string log_msg = "Failed to get mac address: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_mac_address error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_mac_address error: %d (%s)", error, get_error_message(error))); } error = connection_get_type(connection_handle, &connection_type); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot get connection type: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_type error: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_type error: %d (%s)", error, get_error_message(error))); } if (CONNECTION_TYPE_ETHERNET == connection_type) { - //gathering profile + // gathering profile error = connection_get_current_profile(connection_handle, &profile_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot get connection profile: " + std::to_string(error); return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_get_current_profile %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, log_msg, + ("connection_get_current_profile %d (%s)", error, get_error_message(error))); } - std::unique_ptr::type, - int (*)(connection_profile_h)> profile_handle_ptr( - profile_handle, &connection_profile_destroy); // automatically release the memory + std::unique_ptr::type, int (*)(connection_profile_h)> + profile_handle_ptr(profile_handle, + &connection_profile_destroy); // automatically release the memory - //gathering ips - PlatformResult ret = GetIpsFromProfile(profile_handle, &result_ip_address, - &result_ipv6_address); + // gathering ips + PlatformResult ret = + GetIpsFromProfile(profile_handle, &result_ip_address, &result_ipv6_address); if (ret.IsError()) { return ret; } @@ -980,8 +955,7 @@ PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::obje return PlatformResult(ErrorCode::NO_ERROR); } -static PlatformResult FetchConnection(std::string* result_status, - std::string* result_apn, +static PlatformResult FetchConnection(std::string* result_status, std::string* result_apn, std::string* result_ip_address, std::string* result_ipv6_address) { LoggerD("Entered"); @@ -989,67 +963,60 @@ static PlatformResult FetchConnection(std::string* result_status, connection_profile_h profile_handle = nullptr; connection_h connection_handle = nullptr; - //connection must be created in every call, in other case error occurs + // connection must be created in every call, in other case error occurs int error = connection_create(&connection_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot create connection: " + std::to_string(error); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_create error: %d (%s)", error, get_error_message(error))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg, ("connection_create error: %d (%s)", + error, get_error_message(error))); } - std::unique_ptr::type, int(*)(connection_h)> - connection_handle_ptr(connection_handle, &connection_destroy); + std::unique_ptr::type, int (*)(connection_h)> + connection_handle_ptr(connection_handle, &connection_destroy); // automatically release the memory error = connection_get_type(connection_handle, &connection_type); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get connection type", - ("Failed to get connection type: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get connection type", + ("Failed to get connection type: %d (%s)", error, get_error_message(error))); } char* apn = nullptr; if (CONNECTION_TYPE_CELLULAR == connection_type) { *result_status = kConnectionOn; - error = connection_get_current_profile(connection_handle, - &profile_handle); - std::unique_ptr - ::type, int(*)(connection_profile_h)> - profile_handle_ptr(profile_handle, &connection_profile_destroy); + error = connection_get_current_profile(connection_handle, &profile_handle); + std::unique_ptr::type, int (*)(connection_profile_h)> + profile_handle_ptr(profile_handle, &connection_profile_destroy); // automatically release the memory if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get profile", - ("Failed to get profile: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get profile", + ("Failed to get profile: %d (%s)", error, get_error_message(error))); } error = connection_profile_get_cellular_apn(profile_handle, &apn); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get apn name", - ("Failed to get apn name: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get apn name", + ("Failed to get apn name: %d (%s)", error, get_error_message(error))); } *result_apn = apn; free(apn); - PlatformResult ret = GetIpsFromProfile(profile_handle, result_ip_address, - result_ipv6_address); + PlatformResult ret = GetIpsFromProfile(profile_handle, result_ip_address, result_ipv6_address); if (ret.IsError()) { return ret; } } else { *result_status = kConnectionOff; - //According to previous implementation in case of error - //don't throw exception here + // According to previous implementation in case of error + // don't throw exception here error = connection_get_default_cellular_service_profile( - connection_handle, - CONNECTION_CELLULAR_SERVICE_TYPE_INTERNET, - &profile_handle); - std::unique_ptr - ::type, int(*)(connection_profile_h)> - profile_handle_ptr(profile_handle, &connection_profile_destroy); + connection_handle, CONNECTION_CELLULAR_SERVICE_TYPE_INTERNET, &profile_handle); + std::unique_ptr::type, int (*)(connection_profile_h)> + profile_handle_ptr(profile_handle, &connection_profile_destroy); // automatically release the memory if (CONNECTION_ERROR_NONE == error) { error = connection_profile_get_cellular_apn(profile_handle, &apn); @@ -1057,12 +1024,10 @@ static PlatformResult FetchConnection(std::string* result_status, *result_apn = apn; free(apn); } else { - LoggerE("Failed to get default apn name: %d. Failing silently", - error); + LoggerE("Failed to get default apn name: %d. Failing silently", error); } } else { - LoggerE("Failed to get default profile: %d. Failing silently", - error); + LoggerE("Failed to get default profile: %d. Failing silently", error); } } @@ -1088,15 +1053,14 @@ PlatformResult SysteminfoPropertiesManager::ReportCellularNetwork(picojson::obje bool result_is_flight_mode; std::string result_imei; - //gathering vconf-based values - ret = manager_.FetchBasicSimProperties(count, &result_mcc, - &result_mnc, &result_cell_id, &result_lac, - &result_is_roaming, &result_is_flight_mode, - &result_imei); + // gathering vconf-based values + ret = manager_.FetchBasicSimProperties(count, &result_mcc, &result_mnc, &result_cell_id, + &result_lac, &result_is_roaming, &result_is_flight_mode, + &result_imei); if (ret.IsError()) { return ret; } - //gathering connection informations + // gathering connection informations ret = FetchConnection(&result_status, &result_apn, &result_ip_address, &result_ipv6_address); if (ret.IsError()) { return ret; @@ -1123,23 +1087,22 @@ PlatformResult SysteminfoPropertiesManager::ReportNetProxyNetwork(picojson::obje connection_h connection_handle = nullptr; std::string result_status; - //connection must be created in every call, in other case error occurs + // connection must be created in every call, in other case error occurs int error = connection_create(&connection_handle); if (CONNECTION_ERROR_NONE != error) { std::string log_msg = "Cannot create connection: " + std::to_string(error); - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, log_msg, - ("connection_create error: %d (%s)", error, get_error_message(error))); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, log_msg, ("connection_create error: %d (%s)", + error, get_error_message(error))); } - std::unique_ptr::type, int(*)(connection_h)> - connection_handle_ptr(connection_handle, &connection_destroy); + std::unique_ptr::type, int (*)(connection_h)> + connection_handle_ptr(connection_handle, &connection_destroy); // automatically release the memory error = connection_get_type(connection_handle, &connection_type); if (CONNECTION_ERROR_NONE != error) { return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Cannot get connection type", - ("Failed to get connection type: %d (%s)", error, get_error_message(error))); + ErrorCode::UNKNOWN_ERR, "Cannot get connection type", + ("Failed to get connection type: %d (%s)", error, get_error_message(error))); } if (CONNECTION_TYPE_NET_PROXY == connection_type) { @@ -1166,14 +1129,14 @@ PlatformResult SysteminfoPropertiesManager::ReportSim(picojson::object* out, uns /// PERIPHERAL PlatformResult SysteminfoPropertiesManager::ReportPeripheral(picojson::object* out) { LoggerD("Entered"); -/* int wireless_display_status = 0; - PlatformResult ret = GetVconfInt(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &wireless_display_status); - if (ret.IsSuccess()) { - if (VCONFKEY_MIRACAST_WFD_SOURCE_ON == wireless_display_status) { - out.insert(std::make_pair(kVideoOutputString, picojson::value(true))); - return PlatformResult(ErrorCode::NO_ERROR); - } - }*/ + /* int wireless_display_status = 0; + PlatformResult ret = GetVconfInt(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &wireless_display_status); + if (ret.IsSuccess()) { + if (VCONFKEY_MIRACAST_WFD_SOURCE_ON == wireless_display_status) { + out.insert(std::make_pair(kVideoOutputString, picojson::value(true))); + return PlatformResult(ErrorCode::NO_ERROR); + } + }*/ int hdmi_status = 0; PlatformResult ret = SysteminfoUtils::GetVconfInt(VCONFKEY_SYSMAN_HDMI, &hdmi_status); if (ret.IsSuccess()) { @@ -1212,18 +1175,19 @@ PlatformResult SysteminfoPropertiesManager::ReportMemory(picojson::object* out) static void CreateStorageInfo(const std::string& type, struct statvfs& fs, picojson::object* out) { LoggerD("Entered"); out->insert(std::make_pair("type", picojson::value(type))); - out->insert(std::make_pair("capacity", picojson::value(std::to_string( - static_cast(fs.f_frsize) * - static_cast(fs.f_blocks))))); - out->insert(std::make_pair("availableCapacity", picojson::value(std::to_string( - static_cast(fs.f_bsize) * - static_cast(fs.f_bavail))))); + out->insert(std::make_pair( + "capacity", picojson::value(std::to_string(static_cast(fs.f_frsize) * + static_cast(fs.f_blocks))))); + out->insert(std::make_pair( + "availableCapacity", + picojson::value(std::to_string(static_cast(fs.f_bsize) * + static_cast(fs.f_bavail))))); bool isRemovable = (type == kTypeInternal) ? false : true; out->insert(std::make_pair("isRemovable", picojson::value(isRemovable))); } static std::string FromStorageTypeToStringType(common::StorageType type) { - switch(type) { + switch (type) { case common::StorageType::kInternal: return kTypeInternal; case common::StorageType::kUsbDevice: @@ -1250,7 +1214,7 @@ PlatformResult SysteminfoPropertiesManager::ReportStorage(picojson::object* out) LoggerD("Storages found %d", storages.size()); for (auto storage : storages) { if (storage->state() == common::StorageState::kMounted) { - //TODO change implementation to support all types of storages and not limited number + // TODO change implementation to support all types of storages and not limited number if (common::StorageType::kInternal == storage->type()) { if (storage_get_internal_memory_size(&fs) < 0) { LoggerE("Storage unit %s not detected", storage->name().c_str()); @@ -1268,7 +1232,6 @@ PlatformResult SysteminfoPropertiesManager::ReportStorage(picojson::object* out) array.push_back(picojson::value(picojson::object())); picojson::object& external_obj = array.back().get(); CreateStorageInfo(FromStorageTypeToStringType(storage->type()), fs, &external_obj); - } } @@ -1276,7 +1239,6 @@ PlatformResult SysteminfoPropertiesManager::ReportStorage(picojson::object* out) return PlatformResult(ErrorCode::NO_ERROR); } - PlatformResult SysteminfoPropertiesManager::ReportCameraFlash(picojson::object* out, unsigned long index) { LoggerD("Entered"); @@ -1284,8 +1246,8 @@ PlatformResult SysteminfoPropertiesManager::ReportCameraFlash(picojson::object* std::string camera = manager_.GetCameraTypes(index); out->insert(std::make_pair("camera", picojson::value(camera))); } else { - return LogAndCreateResult( - ErrorCode::NOT_SUPPORTED_ERR, "Camera is not supported on this device"); + return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, + "Camera is not supported on this device"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -1295,8 +1257,7 @@ PlatformResult SysteminfoPropertiesManager::ReportCameraFlash(picojson::object* PlatformResult SysteminfoPropertiesManager::ReportAds(picojson::object* out) { LoggerD("Entered"); std::string ads_id = ""; - PlatformResult ret = SysteminfoUtils::GetRuntimeInfoString( - SYSTEM_SETTINGS_KEY_ADS_ID, &ads_id); + PlatformResult ret = SysteminfoUtils::GetRuntimeInfoString(SYSTEM_SETTINGS_KEY_ADS_ID, &ads_id); if (ret.IsError()) { return ret; } @@ -1305,5 +1266,5 @@ PlatformResult SysteminfoPropertiesManager::ReportAds(picojson::object* out) { return PlatformResult(ErrorCode::NO_ERROR); } -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi diff --git a/src/systeminfo/systeminfo_properties_manager.h b/src/systeminfo/systeminfo_properties_manager.h index d16116f..2637d1a 100644 --- a/src/systeminfo/systeminfo_properties_manager.h +++ b/src/systeminfo/systeminfo_properties_manager.h @@ -31,12 +31,12 @@ class SysteminfoPropertiesManager { SysteminfoPropertiesManager(SysteminfoManager& manager); ~SysteminfoPropertiesManager(); - common::PlatformResult GetPropertyValue( - const std::string& prop, bool is_array_type, picojson::value* res); + common::PlatformResult GetPropertyValue(const std::string& prop, bool is_array_type, + picojson::value* res); private: common::PlatformResult ReportProperty(const std::string& property, int index, - picojson::object* res_obj); + picojson::object* res_obj); common::PlatformResult ReportBattery(picojson::object* out); common::PlatformResult ReportCpu(picojson::object* out); common::PlatformResult ReportDisplay(picojson::object* out); @@ -61,7 +61,7 @@ class SysteminfoPropertiesManager { SysteminfoManager& manager_; }; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi -#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_PROPERTIES_MANAGER_H__ +#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_PROPERTIES_MANAGER_H__ diff --git a/src/systeminfo/systeminfo_sim_details_manager.cc b/src/systeminfo/systeminfo_sim_details_manager.cc index dd6ddc3..0ad13fc 100644 --- a/src/systeminfo/systeminfo_sim_details_manager.cc +++ b/src/systeminfo/systeminfo_sim_details_manager.cc @@ -24,7 +24,7 @@ namespace extension { namespace systeminfo { namespace { -//Sim +// Sim const char* kSimStatusAbsent = "ABSENT"; const char* kSimStatusInitializing = "INITIALIZING"; const char* kSimStatusReady = "READY"; @@ -34,11 +34,11 @@ const char* kSimStatusSimLocked = "SIM_LOCKED"; const char* kSimStatusNetworkLocked = "NETWORK_LOCKED"; const char* kSimStatusUnknown = "UNKNOWN"; -void SimCphsValueCallback(TapiHandle */*handle*/, int result, void *data, void *user_data) { +void SimCphsValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { LoggerD("Entered"); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); - TelSimCphsNetName_t *cphs_info = static_cast(data); + TelSimCphsNetName_t* cphs_info = static_cast(data); std::string result_operator; if (TAPI_SIM_ACCESS_SUCCESS == access_rt) { @@ -55,11 +55,11 @@ void SimCphsValueCallback(TapiHandle */*handle*/, int result, void *data, void * sim_mgr->TryReturn(); } -void SimMsisdnValueCallback(TapiHandle */*handle*/, int result, void *data, void *user_data) { +void SimMsisdnValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { LoggerD("Entered"); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); - TelSimMsisdnList_t *msisdn_info = static_cast(data); + TelSimMsisdnList_t* msisdn_info = static_cast(data); std::string result_msisdn; if (TAPI_SIM_ACCESS_SUCCESS == access_rt) { @@ -80,15 +80,15 @@ void SimMsisdnValueCallback(TapiHandle */*handle*/, int result, void *data, void sim_mgr->TryReturn(); } -void SimSpnValueCallback(TapiHandle */*handle*/, int result, void *data, void *user_data) { +void SimSpnValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { LoggerD("Entered"); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); - TelSimSpn_t *spn_info = static_cast(data); + TelSimSpn_t* spn_info = static_cast(data); std::string result_spn; if (TAPI_SIM_ACCESS_SUCCESS == access_rt) { - result_spn = (char *)spn_info->spn; + result_spn = (char*)spn_info->spn; } else { LoggerW("Failed to retrieve spn_: %d", access_rt); } @@ -97,15 +97,15 @@ void SimSpnValueCallback(TapiHandle */*handle*/, int result, void *data, void *u sim_mgr->TryReturn(); } -void SimIccidValueCallback(TapiHandle */*handle*/, int result, void *data, void *user_data) { +void SimIccidValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { LoggerD("Entered"); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); - TelSimIccIdInfo_t *iccid_info = static_cast(data); + TelSimIccIdInfo_t* iccid_info = static_cast(data); std::string result_iccid; if (TAPI_SIM_ACCESS_SUCCESS == access_rt) { - result_iccid = (char *)iccid_info->icc_num; + result_iccid = (char*)iccid_info->icc_num; } else { LoggerW("Failed to retrieve iccid_: %d", access_rt); } @@ -116,23 +116,22 @@ void SimIccidValueCallback(TapiHandle */*handle*/, int result, void *data, void const unsigned short kMccDivider = 100; -} //namespace +} // namespace using common::PlatformResult; using common::ErrorCode; -SimDetailsManager::SimDetailsManager(): - mcc_(0), - mnc_(0), - operator_name_(""), - msin_(""), - state_(""), - msisdn_(""), - iccid_(""), - spn_(""), - sim_result_obj_(nullptr), - to_process_(0) -{ +SimDetailsManager::SimDetailsManager() + : mcc_(0), + mnc_(0), + operator_name_(""), + msin_(""), + state_(""), + msisdn_(""), + iccid_(""), + spn_(""), + sim_result_obj_(nullptr), + to_process_(0) { } PlatformResult SimDetailsManager::GatherSimInformation(TapiHandle* handle, picojson::object* out) { @@ -147,9 +146,9 @@ PlatformResult SimDetailsManager::GatherSimInformation(TapiHandle* handle, picoj return ret; } { - //All props should be fetched synchronously, but sync function does not work + // All props should be fetched synchronously, but sync function does not work std::lock_guard lock_to_process(sim_to_process_mutex_); - //would be deleted on } ending bracket + // would be deleted on } ending bracket int result = tel_get_sim_cphs_netname(handle, SimCphsValueCallback, this); if (TAPI_API_SUCCESS == result) { ++to_process_; @@ -178,24 +177,20 @@ PlatformResult SimDetailsManager::GatherSimInformation(TapiHandle* handle, picoj LoggerE("Failed getting iccid: %d", result); } } - //prevent returning not filled result + // prevent returning not filled result std::lock_guard lock_sim(sim_info_mutex_); - //result will come from callbacks + // result will come from callbacks return PlatformResult(ErrorCode::NO_ERROR); } - //if sim state is not READY return default values and don't wait for callbacks + // if sim state is not READY return default values and don't wait for callbacks TryReturn(); return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult SimDetailsManager::FetchBasicSimProperties(TapiHandle* tapi_handle, - unsigned short* result_mcc, - unsigned short* result_mnc, - unsigned short* result_cell_id, - unsigned short* result_lac, - bool* result_is_roaming, - bool* result_is_flight_mode, - std::string* result_imei) { +PlatformResult SimDetailsManager::FetchBasicSimProperties( + TapiHandle* tapi_handle, unsigned short* result_mcc, unsigned short* result_mnc, + unsigned short* result_cell_id, unsigned short* result_lac, bool* result_is_roaming, + bool* result_is_flight_mode, std::string* result_imei) { ScopeLogger(); int result_value = 0; @@ -247,7 +242,7 @@ PlatformResult SimDetailsManager::FetchBasicSimProperties(TapiHandle* tapi_handl return PlatformResult(ErrorCode::NO_ERROR); } -void SimDetailsManager::FetchSimState(TapiHandle *tapi_handle) { +void SimDetailsManager::FetchSimState(TapiHandle* tapi_handle) { LoggerD("Entered"); if (nullptr == tapi_handle) { LoggerE("Tapi handle is null"); @@ -290,7 +285,7 @@ void SimDetailsManager::FetchSimState(TapiHandle *tapi_handle) { } } -PlatformResult SimDetailsManager::FetchSimSyncProps(TapiHandle *tapi_handle) { +PlatformResult SimDetailsManager::FetchSimSyncProps(TapiHandle* tapi_handle) { LoggerD("Entered"); TelSimImsiInfo_t imsi; int error = tel_get_sim_imsi(tapi_handle, &imsi); @@ -299,11 +294,9 @@ PlatformResult SimDetailsManager::FetchSimSyncProps(TapiHandle *tapi_handle) { mcc_ = std::stoul(imsi.szMcc); mnc_ = std::stoul(imsi.szMnc); msin_ = imsi.szMsin; - } - else { - return LogAndCreateResult( - ErrorCode::UNKNOWN_ERR, "Failed to get sim imsi", - ("Failed to get sim imsi: %d (%s)", error, get_error_message(error))); + } else { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get sim imsi", + ("Failed to get sim imsi: %d (%s)", error, get_error_message(error))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -334,7 +327,7 @@ void SimDetailsManager::ReturnSimToJS() { sim_result_obj_->insert(std::make_pair("mnc", picojson::value(std::to_string(mnc_)))); sim_result_obj_->insert(std::make_pair("msin", picojson::value(msin_))); sim_result_obj_->insert(std::make_pair("spn", picojson::value(spn_))); - //everything returned, clear pointer + // everything returned, clear pointer sim_result_obj_ = nullptr; } else { LoggerE("No sim returned JSON object pointer is null"); @@ -343,7 +336,7 @@ void SimDetailsManager::ReturnSimToJS() { void SimDetailsManager::TryReturn() { LoggerD("Entered"); - if (0 == to_process_){ + if (0 == to_process_) { LoggerD("Returning property to JS"); ReturnSimToJS(); sim_info_mutex_.unlock(); @@ -384,5 +377,5 @@ void SimDetailsManager::set_iccid(const std::string& iccid) { LoggerD("ICCID value: %s", this->iccid_.c_str()); }; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi diff --git a/src/systeminfo/systeminfo_sim_details_manager.h b/src/systeminfo/systeminfo_sim_details_manager.h index 1553aa8..a555df1 100644 --- a/src/systeminfo/systeminfo_sim_details_manager.h +++ b/src/systeminfo/systeminfo_sim_details_manager.h @@ -17,8 +17,8 @@ #ifndef WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_SIM_DETAILS_MANAGER_H__ #define WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_SIM_DETAILS_MANAGER_H__ -#include #include +#include #include #include @@ -34,14 +34,10 @@ class SimDetailsManager { SimDetailsManager(); common::PlatformResult GatherSimInformation(TapiHandle* handle, picojson::object* out); - static common::PlatformResult FetchBasicSimProperties(TapiHandle* tapi_handle, - unsigned short* result_mcc, - unsigned short* result_mnc, - unsigned short* result_cell_id, - unsigned short* result_lac, - bool* result_is_roaming, - bool* result_is_flight_mode, - std::string* result_imei); + static common::PlatformResult FetchBasicSimProperties( + TapiHandle* tapi_handle, unsigned short* result_mcc, unsigned short* result_mnc, + unsigned short* result_cell_id, unsigned short* result_lac, bool* result_is_roaming, + bool* result_is_flight_mode, std::string* result_imei); void TryReturn(); @@ -52,8 +48,8 @@ class SimDetailsManager { private: void ResetSimHolder(picojson::object* out); - void FetchSimState(TapiHandle *tapi_handle); - common::PlatformResult FetchSimSyncProps(TapiHandle *tapi_handle); + void FetchSimState(TapiHandle* tapi_handle); + common::PlatformResult FetchSimSyncProps(TapiHandle* tapi_handle); void ReturnSimToJS(); unsigned short mcc_; @@ -71,7 +67,7 @@ class SimDetailsManager { std::mutex sim_info_mutex_; }; -} // namespace systeminfo -} // namespace webapi +} // namespace systeminfo +} // namespace webapi -#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_SIM_DETAILS_MANAGER_H__ +#endif // WEBAPI_PLUGINS_SYSTEMINFO_SYSTEMINFO_SIM_DETAILS_MANAGER_H__ diff --git a/src/systemsetting/systemsetting_extension.cc b/src/systemsetting/systemsetting_extension.cc index d6c9008..f541823 100644 --- a/src/systemsetting/systemsetting_extension.cc +++ b/src/systemsetting/systemsetting_extension.cc @@ -30,7 +30,8 @@ SystemSettingExtension::SystemSettingExtension() { SetJavaScriptAPI(kSource_systemsetting_api); } -SystemSettingExtension::~SystemSettingExtension() {} +SystemSettingExtension::~SystemSettingExtension() { +} common::Instance* SystemSettingExtension::CreateInstance() { return new extension::systemsetting::SystemSettingInstance; diff --git a/src/systemsetting/systemsetting_extension.h b/src/systemsetting/systemsetting_extension.h index a193b78..3a44167 100644 --- a/src/systemsetting/systemsetting_extension.h +++ b/src/systemsetting/systemsetting_extension.h @@ -28,5 +28,4 @@ class SystemSettingExtension : public common::Extension { virtual common::Instance* CreateInstance(); }; -#endif // SYSTEMSETTING_SYSTEMSETTING_EXTENSION_H_ - +#endif // SYSTEMSETTING_SYSTEMSETTING_EXTENSION_H_ diff --git a/src/systemsetting/systemsetting_instance.cc b/src/systemsetting/systemsetting_instance.cc index 55d6891..64fb7d3 100644 --- a/src/systemsetting/systemsetting_instance.cc +++ b/src/systemsetting/systemsetting_instance.cc @@ -18,15 +18,14 @@ #include +#include "common/filesystem/filesystem_provider.h" #include "common/logger.h" #include "common/picojson.h" #include "common/task-queue.h" -#include "common/filesystem/filesystem_provider.h" #include "common/tools.h" #include - namespace extension { namespace systemsetting { @@ -42,14 +41,12 @@ const std::string kPrivilegeSetting = "http://tizen.org/privilege/setting"; using namespace common; using namespace extension::systemsetting; -SystemSettingInstance::SystemSettingInstance() -{ +SystemSettingInstance::SystemSettingInstance() { LoggerD("Enter"); using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER(c,x) \ - RegisterSyncHandler(c, std::bind(&SystemSettingInstance::x, this, _1, _2)); +#define REGISTER(c, x) RegisterSyncHandler(c, std::bind(&SystemSettingInstance::x, this, _1, _2)); REGISTER("SystemSettingManager_getProperty", getProperty); REGISTER("SystemSettingManager_setProperty", setProperty); @@ -57,13 +54,11 @@ SystemSettingInstance::SystemSettingInstance() #undef REGISTER } -SystemSettingInstance::~SystemSettingInstance() -{ +SystemSettingInstance::~SystemSettingInstance() { LoggerD("Enter"); } -void SystemSettingInstance::getProperty(const picojson::value& args, picojson::object& out) -{ +void SystemSettingInstance::getProperty(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); const double callback_id = args.get("callbackId").get(); @@ -74,14 +69,16 @@ void SystemSettingInstance::getProperty(const picojson::value& args, picojson::o LoggerD("Getting platform value"); picojson::value result = picojson::value(picojson::object()); PlatformResult status = getPlatformPropertyValue(type, &result); - if(status.IsSuccess()) { + if (status.IsSuccess()) { ReportSuccess(result, response->get()); } else { - LogAndReportError(status, &response->get(), ("Failed: getPlatformPropertyValue()")); + LogAndReportError(status, &response->get(), + ("Failed: getPlatformPropertyValue()")); } }; - auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { + auto get_response = [this, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Getting response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); @@ -93,29 +90,21 @@ void SystemSettingInstance::getProperty(const picojson::value& args, picojson::o TaskQueue::GetInstance().Queue(get, get_response, data); } -PlatformResult SystemSettingInstance::getPlatformPropertyValue( - const std::string& settingType, - picojson::value* out) { +PlatformResult SystemSettingInstance::getPlatformPropertyValue(const std::string& settingType, + picojson::value* out) { LoggerD("Enter"); picojson::object& result_obj = out->get(); int ret = SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER; - char *value = NULL; + char* value = NULL; if (settingType == SETTING_HOME_SCREEN) { - ret = system_settings_get_value_string( - SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, &value); - } - else if (settingType == SETTING_LOCK_SCREEN) { - ret = system_settings_get_value_string( - SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, &value); - } - else if (settingType == SETTING_INCOMING_CALL) { - ret = system_settings_get_value_string( - SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, &value); - } - else if (settingType == SETTING_NOTIFICATION_EMAIL) { - ret = system_settings_get_value_string( - SYSTEM_SETTINGS_KEY_EMAIL_ALERT_RINGTONE, &value); + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, &value); + } else if (settingType == SETTING_LOCK_SCREEN) { + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, &value); + } else if (settingType == SETTING_INCOMING_CALL) { + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, &value); + } else if (settingType == SETTING_NOTIFICATION_EMAIL) { + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_EMAIL_ALERT_RINGTONE, &value); } // other values (not specified in the documentation) are handled in JS @@ -126,18 +115,16 @@ PlatformResult SystemSettingInstance::getPlatformPropertyValue( free(value); return PlatformResult(ErrorCode::NO_ERROR); case SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "This property is not supported.", - ("SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: %s", get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::NOT_SUPPORTED_ERR, "This property is not supported.", + ("SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: %s", get_error_message(ret))); default: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("error: %d, message: %s", ret, get_error_message(ret))); } } -void SystemSettingInstance::setProperty(const picojson::value& args, picojson::object& out) -{ +void SystemSettingInstance::setProperty(const picojson::value& args, picojson::object& out) { LoggerD("Enter"); CHECK_PRIVILEGE_ACCESS(kPrivilegeSetting, &out); @@ -150,7 +137,8 @@ void SystemSettingInstance::setProperty(const picojson::value& args, picojson::o const std::string& value = args.get("value").get(); LoggerD("Value to set: %s ", value.c_str()); - auto get = [this, type, value, callback_id](const std::shared_ptr& response) -> void { + auto get = [this, type, value, + callback_id](const std::shared_ptr& response) -> void { LoggerD("Setting platform value"); std::string real_path = common::FilesystemProvider::Create().GetRealPath(value); PlatformResult status = setPlatformPropertyValue(type, real_path); @@ -169,26 +157,22 @@ void SystemSettingInstance::setProperty(const picojson::value& args, picojson::o TaskQueue::GetInstance().Async(get, data); } -PlatformResult SystemSettingInstance::setPlatformPropertyValue( - const std::string& settingType, - const std::string& settingValue) { +PlatformResult SystemSettingInstance::setPlatformPropertyValue(const std::string& settingType, + const std::string& settingValue) { LoggerD("Enter"); int ret = SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER; if (settingType == SETTING_HOME_SCREEN) { - ret = system_settings_set_value_string( - SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, settingValue.c_str()); - } - else if (settingType == SETTING_LOCK_SCREEN) { - ret = system_settings_set_value_string( - SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, settingValue.c_str()); - } - else if (settingType == SETTING_INCOMING_CALL) { - ret = system_settings_set_value_string( - SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, settingValue.c_str()); - } - else if (settingType == SETTING_NOTIFICATION_EMAIL) { - ret = system_settings_set_value_string( - SYSTEM_SETTINGS_KEY_EMAIL_ALERT_RINGTONE, settingValue.c_str()); + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, + settingValue.c_str()); + } else if (settingType == SETTING_LOCK_SCREEN) { + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, + settingValue.c_str()); + } else if (settingType == SETTING_INCOMING_CALL) { + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, + settingValue.c_str()); + } else if (settingType == SETTING_NOTIFICATION_EMAIL) { + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_EMAIL_ALERT_RINGTONE, + settingValue.c_str()); } // other values (not specified in the documentation) are handled in JS @@ -197,20 +181,18 @@ PlatformResult SystemSettingInstance::setPlatformPropertyValue( LoggerD("ret == SYSTEM_SETTINGS_ERROR_NONE"); return PlatformResult(ErrorCode::NO_ERROR); case SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: - return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, - "This property is not supported.", - ("SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: %s", get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::NOT_SUPPORTED_ERR, "This property is not supported.", + ("SYSTEM_SETTINGS_ERROR_NOT_SUPPORTED: %s", get_error_message(ret))); case SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER: - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid parameter passed.", - ("SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER: %s", get_error_message(ret))); + return LogAndCreateResult( + ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed.", + ("SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER: %s", get_error_message(ret))); default: - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Unknown error", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error", ("error: %d, message: %s", ret, get_error_message(ret))); } } -} // namespace systemsetting -} // namespace extension - +} // namespace systemsetting +} // namespace extension diff --git a/src/systemsetting/systemsetting_instance.h b/src/systemsetting/systemsetting_instance.h index a6dd039..799d3ca 100644 --- a/src/systemsetting/systemsetting_instance.h +++ b/src/systemsetting/systemsetting_instance.h @@ -23,25 +23,22 @@ namespace extension { namespace systemsetting { -class SystemSettingInstance : public common::ParsedInstance -{ +class SystemSettingInstance : public common::ParsedInstance { public: SystemSettingInstance(); virtual ~SystemSettingInstance(); private: void getProperty(const picojson::value& args, picojson::object& out); - common::PlatformResult getPlatformPropertyValue( - const std::string& valueType, - picojson::value* out); + common::PlatformResult getPlatformPropertyValue(const std::string& valueType, + picojson::value* out); void setProperty(const picojson::value& args, picojson::object& out); - common::PlatformResult setPlatformPropertyValue( - const std::string& settingType, - const std::string& settingValue); + common::PlatformResult setPlatformPropertyValue(const std::string& settingType, + const std::string& settingValue); }; -} // namespace systemsetting -} // namespace extension +} // namespace systemsetting +} // namespace extension -#endif // SYSTEMSETTING_SYSTEMSETTING_INSTANCE_H_ +#endif // SYSTEMSETTING_SYSTEMSETTING_INSTANCE_H_ diff --git a/src/time/time_extension.cc b/src/time/time_extension.cc index de63827..769a6f4 100644 --- a/src/time/time_extension.cc +++ b/src/time/time_extension.cc @@ -3,8 +3,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include #include "time/time_extension.h" +#include #include "time/time_instance.h" common::Extension* CreateExtension() { @@ -20,11 +20,7 @@ TimeExtension::TimeExtension() { SetExtensionName("tizen.time"); SetJavaScriptAPI(kSource_time_api); - const char* entry_points[] = { - "tizen.TZDate", - "tizen.TimeDuration", - NULL - }; + const char* entry_points[] = {"tizen.TZDate", "tizen.TimeDuration", NULL}; SetExtraJSEntryPoints(entry_points); } diff --git a/src/time/time_instance.cc b/src/time/time_instance.cc index 1e63ece..5fc4db0 100644 --- a/src/time/time_instance.cc +++ b/src/time/time_instance.cc @@ -13,16 +13,14 @@ namespace time { using namespace common; -TimeInstance::TimeInstance() : manager_(this) { +TimeInstance::TimeInstance() : manager_(this) { using std::placeholders::_1; using std::placeholders::_2; LoggerD("Entered"); -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); -#define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); REGISTER_SYNC("TimeUtil_getAvailableTimezones", TimeUtil_getAvailableTimezones); REGISTER_SYNC("TimeUtil_getDateFormat", TimeUtil_getDateFormat); @@ -58,10 +56,10 @@ void TimeInstance::TimeUtil_getAvailableTimezones(const picojson::value& /*args* picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - auto array = result_obj.insert(std::make_pair("availableTimezones", - picojson::value(picojson::array()))); - PlatformResult res = TimeUtilTools::GetAvailableTimezones( - &array.first->second.get()); + auto array = + result_obj.insert(std::make_pair("availableTimezones", picojson::value(picojson::array()))); + PlatformResult res = + TimeUtilTools::GetAvailableTimezones(&array.first->second.get()); if (res.IsError()) { LogAndReportError(res, &out, ("Failed to get available timezones")); return; @@ -72,8 +70,8 @@ void TimeInstance::TimeUtil_getAvailableTimezones(const picojson::value& /*args* void TimeInstance::TimeUtil_getDateFormat(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); if (!args.contains("shortformat")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameter \"shortformat\" is missing")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameter \"shortformat\" is missing")); return; } @@ -161,12 +159,11 @@ void TimeInstance::TZDate_getLocalTimezone(const picojson::value& /*args*/, pico ReportSuccess(result, out); } -void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, - picojson::object& out) { +void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); @@ -176,13 +173,12 @@ void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, std::string offset; std::string modifier; - PlatformResult res = manager_.GetTimezoneOffset(timezone_id, timestamp_str, - &offset, &modifier); + PlatformResult res = manager_.GetTimezoneOffset(timezone_id, timestamp_str, &offset, &modifier); if (res.IsSuccess()) { picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); result_obj.insert(std::make_pair("offset", picojson::value(offset))); - //this value is to correct 'missing' hour also in JS + // this value is to correct 'missing' hour also in JS result_obj.insert(std::make_pair("modifier", picojson::value(modifier))); ReportSuccess(result, out); } else { @@ -190,26 +186,24 @@ void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, } } -void TimeInstance::ToStringTemplate(const picojson::value& args, - bool use_locale_fmt, - TimeUtilTools::DateTimeFormatType type, - picojson::object* out) { +void TimeInstance::ToStringTemplate(const picojson::value& args, bool use_locale_fmt, + TimeUtilTools::DateTimeFormatType type, picojson::object* out) { LoggerD("Entered"); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); - std::shared_ptr unicode_id (new UnicodeString(timezone_id.c_str())); + std::shared_ptr unicode_id(new UnicodeString(timezone_id.c_str())); LoggerD("Getting timezone details for id: %s ", timezone_id.c_str()); const std::string& timestamp_str = args.get("timestamp").get(); UDate date = std::stod(timestamp_str); std::string result_string; - PlatformResult res = TimeUtilTools::ToStringHelper(date, unicode_id, use_locale_fmt, - type, &result_string); + PlatformResult res = + TimeUtilTools::ToStringHelper(date, unicode_id, use_locale_fmt, type, &result_string); if (res.IsError()) { LogAndReportError(res, out, ("Failed to convert to string.")); return; @@ -217,8 +211,7 @@ void TimeInstance::ToStringTemplate(const picojson::value& args, picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - result_obj.insert( - std::make_pair("string", picojson::value(result_string))); + result_obj.insert(std::make_pair("string", picojson::value(result_string))); ReportSuccess(result, *out); } @@ -256,15 +249,17 @@ void TimeInstance::TZDate_toString(const picojson::value& args, picojson::object void TimeInstance::TZDate_getTimezoneAbbreviation(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); - LoggerW("DEPRECATION WARNING: getTimezoneAbbreviation() is deprecated and will be removed from next release."); + LoggerW( + "DEPRECATION WARNING: getTimezoneAbbreviation() is deprecated and will be removed from next " + "release."); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); - std::shared_ptr unicode_id (new UnicodeString(timezone_id.c_str())); + std::shared_ptr unicode_id(new UnicodeString(timezone_id.c_str())); const std::string& timestamp_str = args.get("timestamp").get(); UDate date = std::stod(timestamp_str); @@ -286,12 +281,12 @@ void TimeInstance::TZDate_getTimezoneAbbreviation(const picojson::value& args, void TimeInstance::TZDate_isDST(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); - std::shared_ptr unicode_id (new UnicodeString(timezone_id.c_str())); + std::shared_ptr unicode_id(new UnicodeString(timezone_id.c_str())); const std::string& timestamp_str = args.get("timestamp").get(); UDate date = std::stod(timestamp_str); @@ -304,8 +299,7 @@ void TimeInstance::TZDate_isDST(const picojson::value& args, picojson::object& o } picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - result_obj.insert( - std::make_pair("isDST", picojson::value(is_dst))); + result_obj.insert(std::make_pair("isDST", picojson::value(is_dst))); ReportSuccess(result, out); } @@ -313,20 +307,20 @@ void TimeInstance::TZDate_getPreviousDSTTransition(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); - std::shared_ptr unicode_id (new UnicodeString(timezone_id.c_str())); + std::shared_ptr unicode_id(new UnicodeString(timezone_id.c_str())); const std::string& timestamp_str = args.get("timestamp").get(); UDate date = std::stod(timestamp_str); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - UDate prev_dst = TimeUtilTools::GetDSTTransition(date, unicode_id, - TimeUtilTools::DSTTransition::kPreviousDST); + UDate prev_dst = + TimeUtilTools::GetDSTTransition(date, unicode_id, TimeUtilTools::DSTTransition::kPreviousDST); result_obj.insert(std::make_pair("prevDSTDate", picojson::value(prev_dst))); ReportSuccess(result, out); @@ -335,20 +329,20 @@ void TimeInstance::TZDate_getPreviousDSTTransition(const picojson::value& args, void TimeInstance::TZDate_getNextDSTTransition(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); if (!args.contains("timezone") || !args.contains("timestamp")) { - LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, - ("Required parameters are missing: \"timezone\", \"timestamp\"")); + LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), + &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); return; } const std::string& timezone_id = args.get("timezone").get(); - std::shared_ptr unicode_id (new UnicodeString(timezone_id.c_str())); + std::shared_ptr unicode_id(new UnicodeString(timezone_id.c_str())); const std::string& timestamp_str = args.get("timestamp").get(); UDate date = std::stod(timestamp_str); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); - UDate next_dst = TimeUtilTools::GetDSTTransition(date, unicode_id, - TimeUtilTools::DSTTransition::kNextDST); + UDate next_dst = + TimeUtilTools::GetDSTTransition(date, unicode_id, TimeUtilTools::DSTTransition::kNextDST); result_obj.insert(std::make_pair("nextDSTDate", picojson::value(next_dst))); ReportSuccess(result, out); diff --git a/src/time/time_instance.h b/src/time/time_instance.h index 6f4643c..adcf08a 100644 --- a/src/time/time_instance.h +++ b/src/time/time_instance.h @@ -8,9 +8,9 @@ #include "common/extension.h" #include "common/picojson.h" -#include "unicode/unistr.h" #include "time/time_manager.h" #include "time/time_utils.h" +#include "unicode/unistr.h" #include diff --git a/src/time/time_manager.cc b/src/time/time_manager.cc index 3d2274f..1c38da6 100644 --- a/src/time/time_manager.cc +++ b/src/time/time_manager.cc @@ -16,8 +16,8 @@ #include "time/time_manager.h" -#include #include +#include #include #include "common/logger.h" @@ -31,10 +31,10 @@ namespace extension { namespace time { TimeManager::TimeManager(TimeInstance* instance) - : instance_(instance), - current_timezone_(GetDefaultTimezone()), - is_time_listener_registered_(false), - is_timezone_listener_registered_(false) { + : instance_(instance), + current_timezone_(GetDefaultTimezone()), + is_time_listener_registered_(false), + is_timezone_listener_registered_(false) { LoggerD("Entered"); } @@ -49,16 +49,14 @@ TimeManager::~TimeManager() { } PlatformResult TimeManager::GetTimezoneOffset(const std::string& timezone_id, - const std::string& timestamp_str, - std::string* offset, + const std::string& timestamp_str, std::string* offset, std::string* modifier) { LoggerD("Entered"); - std::unique_ptr unicode_id (new UnicodeString(timezone_id.c_str())); - std::unique_ptr tz (TimeZone::createTimeZone(*unicode_id)); + std::unique_ptr unicode_id(new UnicodeString(timezone_id.c_str())); + std::unique_ptr tz(TimeZone::createTimeZone(*unicode_id)); if (TimeZone::getUnknown() == *tz) { - return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, - "Invalid parameter passed.", + return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed.", ("Unknown timezone")); } @@ -67,24 +65,23 @@ PlatformResult TimeManager::GetTimezoneOffset(const std::string& timezone_id, int32_t stdOffset = 0; int32_t dstOffset = 0; UErrorCode ec = U_ZERO_ERROR; - //offset is get for target LOCAL date timestamp, but it should be UTC timestamp, - //so it has to be checked below against DST edge condition + // offset is get for target LOCAL date timestamp, but it should be UTC timestamp, + // so it has to be checked below against DST edge condition tz->getOffset(date, false, stdOffset, dstOffset, ec); LoggerD("stdOffset: %d, dstOffset: %d", stdOffset, dstOffset); - //this section checks if date is not in DST transition point - //check if date shifted to UTC timestamp is still with the same offset + // this section checks if date is not in DST transition point + // check if date shifted to UTC timestamp is still with the same offset int32_t dstOffsetBefore = 0; tz->getOffset(date - stdOffset - dstOffset, false, stdOffset, dstOffsetBefore, ec); LoggerD("stdOffset: %d, dstOffsetBefore: %d", stdOffset, dstOffsetBefore); - //it has to be checked if it is 'missing' hour case + // it has to be checked if it is 'missing' hour case int32_t dstOffsetAfterBefore = 0; - tz->getOffset(date - stdOffset - dstOffset + oneHour, - false, stdOffset, dstOffsetAfterBefore, ec); + tz->getOffset(date - stdOffset - dstOffset + oneHour, false, stdOffset, dstOffsetAfterBefore, ec); LoggerD("stdOffset: %d, dstOffsetAfterBefore: %d", stdOffset, dstOffsetAfterBefore); - //offset would be minimum of local and utc timestamp offsets + // offset would be minimum of local and utc timestamp offsets //(to work correctly even if DST transtion is 'now') dstOffset = std::min(dstOffset, dstOffsetBefore); @@ -95,25 +92,24 @@ PlatformResult TimeManager::GetTimezoneOffset(const std::string& timezone_id, PlatformResult TimeManager::RegisterVconfCallback(ListenerType type) { LoggerD("Entered"); - if (!is_time_listener_registered_ && !is_timezone_listener_registered_){ + if (!is_time_listener_registered_ && !is_timezone_listener_registered_) { LoggerD("registering listener on platform"); - if (0 != vconf_notify_key_changed( - VCONFKEY_SYSTEM_TIME_CHANGED, OnTimeChangedCallback, this)) { + if (0 != vconf_notify_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, OnTimeChangedCallback, this)) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register vconf callback"); } } else { LoggerD("not registering listener on platform - already registered"); } switch (type) { - case kTimeChange : + case kTimeChange: is_time_listener_registered_ = true; LoggerD("time change listener registered"); break; - case kTimezoneChange : + case kTimezoneChange: is_timezone_listener_registered_ = true; LoggerD("time zone change listener registered"); break; - default : + default: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown type of listener"); } return PlatformResult(ErrorCode::NO_ERROR); @@ -122,15 +118,15 @@ PlatformResult TimeManager::RegisterVconfCallback(ListenerType type) { PlatformResult TimeManager::UnregisterVconfCallback(ListenerType type) { LoggerD("Entered"); switch (type) { - case kTimeChange : + case kTimeChange: is_time_listener_registered_ = false; LoggerD("time change listener unregistered"); break; - case kTimezoneChange : + case kTimezoneChange: is_timezone_listener_registered_ = false; LoggerD("time zone change listener unregistered"); break; - default : + default: return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown type of listener"); } if (!is_time_listener_registered_ && !is_timezone_listener_registered_) { @@ -138,7 +134,7 @@ PlatformResult TimeManager::UnregisterVconfCallback(ListenerType type) { if (0 != vconf_ignore_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, OnTimeChangedCallback)) { LOGE("Failed to unregister vconf callback"); // silent fail - //return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister vconf callback"); + // return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister vconf callback"); } } return PlatformResult(ErrorCode::NO_ERROR); @@ -152,7 +148,7 @@ void TimeManager::OnTimeChangedCallback(keynode_t* /*node*/, void* event_ptr) { if (manager->GetCurrentTimezone() != defaultTimezone) { manager->SetCurrentTimezone(defaultTimezone); - //call timezone callback + // call timezone callback const std::shared_ptr& response = std::shared_ptr(new picojson::value(picojson::object())); @@ -160,7 +156,7 @@ void TimeManager::OnTimeChangedCallback(keynode_t* /*node*/, void* event_ptr) { // ReportSuccess(result,response->get()); Instance::PostMessage(instance, response->serialize().c_str()); } - //call date time callback + // call date time callback const std::shared_ptr& response = std::shared_ptr(new picojson::value(picojson::object())); response->get()["listenerId"] = picojson::value("DateTimeChangeListener"); @@ -189,12 +185,12 @@ std::string TimeManager::GetDefaultTimezone() { } } -std::string TimeManager::GetCurrentTimezone(){ +std::string TimeManager::GetCurrentTimezone() { LoggerD("Entered"); return current_timezone_; } -void TimeManager::SetCurrentTimezone(const std::string& new_timezone){ +void TimeManager::SetCurrentTimezone(const std::string& new_timezone) { LoggerD("Entered"); current_timezone_ = new_timezone; } @@ -204,5 +200,5 @@ TimeInstance* TimeManager::GetTimeInstance() { return instance_; } -} // time -} // extension +} // time +} // extension diff --git a/src/time/time_manager.h b/src/time/time_manager.h index 02f95e9..5745438 100644 --- a/src/time/time_manager.h +++ b/src/time/time_manager.h @@ -17,30 +17,25 @@ #ifndef TIME_TIME_MANAGER_H_ #define TIME_TIME_MANAGER_H_ -#include #include +#include #include "common/picojson.h" #include "common/platform_result.h" namespace extension { namespace time { -enum ListenerType { - kTimeChange, - kTimezoneChange -}; +enum ListenerType { kTimeChange, kTimezoneChange }; class TimeInstance; -class TimeManager -{ +class TimeManager { public: TimeManager(TimeInstance* instance); ~TimeManager(); common::PlatformResult GetTimezoneOffset(const std::string& timezone_id, - const std::string& timestamp_str, - std::string* offset, + const std::string& timestamp_str, std::string* offset, std::string* modifier); common::PlatformResult RegisterVconfCallback(ListenerType type); common::PlatformResult UnregisterVconfCallback(ListenerType type); @@ -49,14 +44,14 @@ class TimeManager void SetCurrentTimezone(const std::string& new_timezone); TimeInstance* GetTimeInstance(); static std::string GetDefaultTimezone(); + private: TimeInstance* instance_; std::string current_timezone_; bool is_time_listener_registered_; bool is_timezone_listener_registered_; }; - } } -#endif // TIME_TIME_MANAGER_H_ +#endif // TIME_TIME_MANAGER_H_ diff --git a/src/time/time_utils.cc b/src/time/time_utils.cc index c1cc057..3f1d446 100644 --- a/src/time/time_utils.cc +++ b/src/time/time_utils.cc @@ -63,39 +63,35 @@ PlatformResult TimeUtilTools::IsDST(UDate timestamp, bool* result_bool) { LoggerD("Entered"); UErrorCode ec = U_ZERO_ERROR; - std::unique_ptr tz (TimeZone::createTimeZone(*timezone_id)); - std::unique_ptr calendar (Calendar::createInstance(*tz, ec)); + std::unique_ptr tz(TimeZone::createTimeZone(*timezone_id)); + std::unique_ptr calendar(Calendar::createInstance(*tz, ec)); - if (U_FAILURE(ec)){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to create calendar instance", + if (U_FAILURE(ec)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to create calendar instance", ("Failed to create calendar instance: %d", ec)); } calendar->setTime(timestamp, ec); - if (U_FAILURE(ec)){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to set calendar date", + if (U_FAILURE(ec)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set calendar date", ("Failed to set calendar date: %d", ec)); } bool result = static_cast(calendar->inDaylightTime(ec)); - if (U_FAILURE(ec)){ - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "Failed to get day light boolean", + if (U_FAILURE(ec)) { + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get day light boolean", ("Failed to get day light boolean: %d", ec)); } *result_bool = result; return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult TimeUtilTools::GetTimezoneAbbreviation(UDate date, - const std::shared_ptr& timezone_id, - std::string* result_string) { +PlatformResult TimeUtilTools::GetTimezoneAbbreviation( + UDate date, const std::shared_ptr& timezone_id, std::string* result_string) { LoggerD("Entered"); UErrorCode ec = U_ZERO_ERROR; UnicodeString str; - std::unique_ptr fmt(new SimpleDateFormat(UnicodeString("z"), - Locale::getEnglish(), ec)); + std::unique_ptr fmt( + new SimpleDateFormat(UnicodeString("z"), Locale::getEnglish(), ec)); if (U_SUCCESS(ec)) { std::unique_ptr tz(TimeZone::createTimeZone(*timezone_id)); fmt->setTimeZone(*tz); @@ -103,8 +99,8 @@ PlatformResult TimeUtilTools::GetTimezoneAbbreviation(UDate date, if ((str.length() > 3) && (str.compare(0, 3, "GMT") == 0)) { str.remove(); - std::unique_ptr gmt(new SimpleDateFormat(UnicodeString("OOOO"), - Locale::getEnglish(), ec)); + std::unique_ptr gmt( + new SimpleDateFormat(UnicodeString("OOOO"), Locale::getEnglish(), ec)); gmt->setTimeZone(*tz); gmt->format(date, str); } @@ -126,11 +122,10 @@ PlatformResult TimeUtilTools::ToStringHelper(UDate date, UnicodeString str; std::unique_ptr default_locale(TimeUtilTools::GetDefaultLocale()); - std::unique_ptr fmt( - new SimpleDateFormat( - TimeUtilTools::GetDateTimeFormat(type, use_locale_fmt), - ((use_locale_fmt && default_locale != nullptr) ? *default_locale : Locale::getEnglish()), - ec)); + std::unique_ptr fmt(new SimpleDateFormat( + TimeUtilTools::GetDateTimeFormat(type, use_locale_fmt), + ((use_locale_fmt && default_locale != nullptr) ? *default_locale : Locale::getEnglish()), + ec)); if (U_SUCCESS(ec)) { std::unique_ptr tz(TimeZone::createTimeZone(*timezone_id)); @@ -141,7 +136,8 @@ PlatformResult TimeUtilTools::ToStringHelper(UDate date, return TimeUtilTools::ToUTF8String(str, result_string); } - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Can't make SimpleDateFormat or can't get time"); + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, + "Can't make SimpleDateFormat or can't get time"); } PlatformResult TimeUtilTools::ToUTF8String(const UnicodeString& uni_str, @@ -149,8 +145,8 @@ PlatformResult TimeUtilTools::ToUTF8String(const UnicodeString& uni_str, LoggerD("Entered"); int buffer_len = sizeof(UChar) * static_cast(uni_str.length()) + 1; - std::unique_ptr result_buffer(static_cast(malloc(buffer_len)), - &std::free); + std::unique_ptr result_buffer(static_cast(malloc(buffer_len)), + &std::free); if (!result_buffer) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); @@ -180,7 +176,7 @@ PlatformResult TimeUtilTools::GetLocalTimeZone(std::string* result_string) { zone->getID(id); PlatformResult res = ToUTF8String(id, result_string); - if(res.IsError()) { + if (res.IsError()) { return res; } LoggerD("local timezone: %s", result_string->c_str()); @@ -191,7 +187,7 @@ Locale* TimeUtilTools::GetDefaultLocale() { LoggerD("Entered"); char* tempstr = vconf_get_str(VCONFKEY_REGIONFORMAT); - if (nullptr == tempstr){ + if (nullptr == tempstr) { return nullptr; } @@ -201,7 +197,7 @@ Locale* TimeUtilTools::GetDefaultLocale() { int len = strlen(tempstr) - (p != nullptr ? strlen(p) : 0); if (len > 0) { - char* str_region = strndup(tempstr, len); //.UTF8 => 5 + char* str_region = strndup(tempstr, len); //.UTF8 => 5 default_locale = new Locale(str_region); free(str_region); } @@ -223,8 +219,7 @@ UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use std::unique_ptr date_time_pattern( DateTimePatternGenerator::createInstance( - ((use_locale_fmt && default_locale) ? *default_locale : Locale::getEnglish()), - ec)); + ((use_locale_fmt && default_locale) ? *default_locale : Locale::getEnglish()), ec)); delete default_locale; if (U_SUCCESS(ec)) { @@ -239,8 +234,7 @@ UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use pattern = date_time_pattern->getBestPattern(UDAT_YEAR_NUM_MONTH_DAY, ec); break; - default: - { + default: { int ret = 0; int value = 0; ret = vconf_get_int(VCONFKEY_REGIONFORMAT_TIME1224, &value); @@ -266,8 +260,7 @@ UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use if (!use_locale_fmt) { pattern += " 'GMT'Z v'"; } - } - break; + } break; } return pattern; @@ -278,16 +271,12 @@ UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use PlatformResult TimeUtilTools::GetDateFormat(bool shortformat, std::string* result_string) { LoggerD("Entered"); - UnicodeString time_format = - TimeUtilTools::GetDateTimeFormat( - (shortformat ? - DateTimeFormatType::kDateShortFormat: - DateTimeFormatType::kDateFormat), - true); + UnicodeString time_format = TimeUtilTools::GetDateTimeFormat( + (shortformat ? DateTimeFormatType::kDateShortFormat : DateTimeFormatType::kDateFormat), true); time_format = time_format.findAndReplace("E", "D"); if (time_format.indexOf("MMM") > 0) { - if (time_format.indexOf("MMMM") > 0){ + if (time_format.indexOf("MMMM") > 0) { time_format = time_format.findAndReplace("MMMM", "M"); } else { time_format = time_format.findAndReplace("MMM", "M"); @@ -307,7 +296,7 @@ PlatformResult TimeUtilTools::GetDateFormat(bool shortformat, std::string* resul } PlatformResult res = ToUTF8String(time_format, result_string); - if(res.IsError()) { + if (res.IsError()) { return res; } return PlatformResult(ErrorCode::NO_ERROR); @@ -315,8 +304,8 @@ PlatformResult TimeUtilTools::GetDateFormat(bool shortformat, std::string* resul PlatformResult TimeUtilTools::GetTimeFormat(std::string* result_string) { LoggerD("Entered"); - UnicodeString time_format = TimeUtilTools::GetDateTimeFormat( - DateTimeFormatType::kTimeFormat, true); + UnicodeString time_format = + TimeUtilTools::GetDateTimeFormat(DateTimeFormatType::kTimeFormat, true); time_format = time_format.findAndReplace("H", "h"); time_format = time_format.findAndReplace("K", "h"); time_format = time_format.findAndReplace("k", "h"); @@ -332,7 +321,7 @@ PlatformResult TimeUtilTools::GetTimeFormat(std::string* result_string) { } } PlatformResult res = ToUTF8String(time_format, result_string); - if(res.IsError()) { + if (res.IsError()) { return res; } return PlatformResult(ErrorCode::NO_ERROR); @@ -354,17 +343,15 @@ PlatformResult TimeUtilTools::GetAvailableTimezones(picojson::array* available_t available_timezones->push_back(picojson::value(str)); ++i; } else { - return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, - "An error occurred", + return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "An error occurred", ("An error occurred: %d", ec)); } } while ((str != nullptr) && (i < count)); - } - else { + } else { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Can't get timezones list"); } return PlatformResult(ErrorCode::NO_ERROR); } -} // time +} // time } diff --git a/src/time/time_utils.h b/src/time/time_utils.h index 93e8e84..848e228 100644 --- a/src/time/time_utils.h +++ b/src/time/time_utils.h @@ -17,39 +17,31 @@ #ifndef TIME_TIME_UTILS_H_ #define TIME_TIME_UTILS_H_ -#include #include +#include #include "common/picojson.h" #include "common/platform_result.h" namespace extension { namespace time { -class TimeUtilTools -{ +class TimeUtilTools { public: - enum class DateTimeFormatType { - kTimeFormat, - kDateFormat, - kDateShortFormat, - kDateTimeFormat - }; - enum class DSTTransition { - kPreviousDST, - kNextDST - }; + enum class DateTimeFormatType { kTimeFormat, kDateFormat, kDateShortFormat, kDateTimeFormat }; + enum class DSTTransition { kPreviousDST, kNextDST }; static UDate GetDSTTransition(UDate dstTransitionDate, const std::shared_ptr& timezone_id, DSTTransition tr_type); static common::PlatformResult IsDST(UDate dstTransitionDate, - const std::shared_ptr& timezone_id, bool* result_bool); - static common::PlatformResult GetTimezoneAbbreviation(UDate date, - const std::shared_ptr& timezone_id, - std::string* result_string); - static common::PlatformResult ToStringHelper( - UDate date, std::shared_ptr& timezone_id, bool use_locale_fmt, - TimeUtilTools::DateTimeFormatType type, - std::string* result_string); + const std::shared_ptr& timezone_id, + bool* result_bool); + static common::PlatformResult GetTimezoneAbbreviation( + UDate date, const std::shared_ptr& timezone_id, std::string* result_string); + static common::PlatformResult ToStringHelper(UDate date, + std::shared_ptr& timezone_id, + bool use_locale_fmt, + TimeUtilTools::DateTimeFormatType type, + std::string* result_string); static common::PlatformResult ToUTF8String(const UnicodeString& uniStr, std::string* result_string); static UnicodeString* ToUnicodeString(const std::string& str); @@ -60,8 +52,7 @@ class TimeUtilTools static common::PlatformResult GetTimeFormat(std::string* result_string); static common::PlatformResult GetAvailableTimezones(picojson::array* available_timezones); }; - } } -#endif // TIME_TIME_UTILS_H_ +#endif // TIME_TIME_UTILS_H_ diff --git a/src/tizen/tizen.h b/src/tizen/tizen.h index 5b600f1..bdced23 100644 --- a/src/tizen/tizen.h +++ b/src/tizen/tizen.h @@ -6,17 +6,17 @@ #ifndef TIZEN_TIZEN_H_ #define TIZEN_TIZEN_H_ -#define STR_MATCH_EXACTLY "EXACTLY" -#define STR_MATCH_FULLSTRING "FULLSTRING" -#define STR_MATCH_CONTAINS "CONTAINS" -#define STR_MATCH_STARTSWITH "STARTSWITH" -#define STR_MATCH_ENDSWITH "ENDSWITH" -#define STR_MATCH_EXISTS "EXISTS" +#define STR_MATCH_EXACTLY "EXACTLY" +#define STR_MATCH_FULLSTRING "FULLSTRING" +#define STR_MATCH_CONTAINS "CONTAINS" +#define STR_MATCH_STARTSWITH "STARTSWITH" +#define STR_MATCH_ENDSWITH "ENDSWITH" +#define STR_MATCH_EXISTS "EXISTS" -#define STR_SORT_ASC "ASC" -#define STR_SORT_DESC "DESC" +#define STR_SORT_ASC "ASC" +#define STR_SORT_DESC "DESC" -#define STR_FILTEROP_OR "UNION" -#define STR_FILTEROP_AND "INTERSECTION" +#define STR_FILTEROP_OR "UNION" +#define STR_FILTEROP_AND "INTERSECTION" #endif // TIZEN_TIZEN_H_ diff --git a/src/tizen/tizen_extension.cc b/src/tizen/tizen_extension.cc index 1769984..7a0309d 100644 --- a/src/tizen/tizen_extension.cc +++ b/src/tizen/tizen_extension.cc @@ -17,4 +17,5 @@ TizenExtension::TizenExtension() { SetJavaScriptAPI(kSource_tizen_api); } -TizenExtension::~TizenExtension() {} +TizenExtension::~TizenExtension() { +} diff --git a/src/tool/desc_gentool.cc b/src/tool/desc_gentool.cc index 0583aa7..7c4185c 100644 --- a/src/tool/desc_gentool.cc +++ b/src/tool/desc_gentool.cc @@ -1,14 +1,14 @@ +#include #include +#include #include #include -#include -#include -#include #include -#include -#include +#include #include +#include +#include #include @@ -16,7 +16,7 @@ static std::string prefix_ = "libtizen"; static std::string postfix_ = ".so"; static std::vector apinamespaces = {"tizen", "xwalk"}; -typedef common::Extension *(*CreateExtensionFunc)(void); +typedef common::Extension* (*CreateExtensionFunc)(void); struct module_description { std::string name; @@ -24,27 +24,24 @@ struct module_description { std::vector entries; }; - static XW_Extension ext = 0; static std::map descriptions; #ifndef JSON_MINIFY - #define PRINT_TAB() std::cout << "\t" +#define PRINT_TAB() std::cout << "\t" #else - #define PRINT_TAB() -#endif +#define PRINT_TAB() +#endif void print_json() { std::cout << "[" << std::endl; for (const auto& kv : descriptions) { - const module_description &desc = kv.second; + const module_description& desc = kv.second; std::string::size_type n = desc.name.find('.'); - std::string ns = - n == std::string::npos ? desc.name : desc.name.substr(0, n); + std::string ns = n == std::string::npos ? desc.name : desc.name.substr(0, n); - if (std::find(apinamespaces.begin(), apinamespaces.end(), ns) == - apinamespaces.end()) { + if (std::find(apinamespaces.begin(), apinamespaces.end(), ns) == apinamespaces.end()) { continue; } @@ -59,7 +56,7 @@ void print_json() { PRINT_TAB(); PRINT_TAB(); std::cout << "\"entry_points\": ["; - for (std::vector::size_type i=0; i::size_type i = 0; i < desc.entries.size(); i++) { if (i != 0) { std::cout << ","; } @@ -79,69 +76,54 @@ void print_json() { const void* get_interface(const char* name) { if (!strcmp(name, XW_CORE_INTERFACE_1)) { static const XW_CoreInterface coreInterface1 = { - [](XW_Extension extension, const char* name) { - module_description *desc = &descriptions[extension]; - desc->name = name; - }, - [](XW_Extension extension, const char* api) {}, - [](XW_Extension extension, XW_CreatedInstanceCallback created, - XW_DestroyedInstanceCallback destroyed) {}, - [](XW_Extension extension, XW_ShutdownCallback shutdown_callback) {}, - [](XW_Instance instance, void* data) {}, - [](XW_Instance instance) -> void* { return nullptr; } - }; + [](XW_Extension extension, const char* name) { + module_description* desc = &descriptions[extension]; + desc->name = name; + }, + [](XW_Extension extension, const char* api) {}, + [](XW_Extension extension, XW_CreatedInstanceCallback created, + XW_DestroyedInstanceCallback destroyed) {}, + [](XW_Extension extension, XW_ShutdownCallback shutdown_callback) {}, + [](XW_Instance instance, void* data) {}, + [](XW_Instance instance) -> void* { return nullptr; }}; return &coreInterface1; } if (!strcmp(name, XW_INTERNAL_ENTRY_POINTS_INTERFACE_1)) { static const XW_Internal_EntryPointsInterface entryPointsInterface1 = { - [](XW_Extension extension, const char** entries) { - module_description *desc = &descriptions[extension]; - for (int i=0; entries[i]; i++) { - desc->entries.push_back(std::string(entries[i])); - } - } - }; + [](XW_Extension extension, const char** entries) { + module_description* desc = &descriptions[extension]; + for (int i = 0; entries[i]; i++) { + desc->entries.push_back(std::string(entries[i])); + } + }}; return &entryPointsInterface1; } - + if (!strcmp(name, XW_MESSAGING_INTERFACE_1)) { static const XW_MessagingInterface_1 messagingInterface1 = { - [](XW_Extension extension, XW_HandleMessageCallback handle_message) { - }, - [](XW_Instance instance, const char* message) { - } - }; + [](XW_Extension extension, XW_HandleMessageCallback handle_message) {}, + [](XW_Instance instance, const char* message) {}}; return &messagingInterface1; } if (!strcmp(name, XW_INTERNAL_SYNC_MESSAGING_INTERFACE_1)) { static const XW_Internal_SyncMessagingInterface syncMessagingInterface1 = { - [](XW_Extension extension, XW_HandleSyncMessageCallback handle_sync_msg) { - }, - [](XW_Instance instance, const char* reply){ - } - }; + [](XW_Extension extension, XW_HandleSyncMessageCallback handle_sync_msg) {}, + [](XW_Instance instance, const char* reply) {}}; return &syncMessagingInterface1; } if (!strcmp(name, XW_INTERNAL_RUNTIME_INTERFACE_1)) { static const XW_Internal_RuntimeInterface_1 runtimeInterface1 = { - [](XW_Extension extension, const char* key, char* value, size_t vlen) { - } - }; + [](XW_Extension extension, const char* key, char* value, size_t vlen) {}}; return &runtimeInterface1; } if (!strcmp(name, XW_INTERNAL_PERMISSIONS_INTERFACE_1)) { static const XW_Internal_PermissionsInterface_1 permissionsInterface1 = { - [](XW_Extension extension, const char* api_name) -> int { - return XW_ERROR; - }, - [](XW_Extension extension, const char* perm_table) -> int { - return XW_ERROR; - } - }; + [](XW_Extension extension, const char* api_name) -> int { return XW_ERROR; }, + [](XW_Extension extension, const char* perm_table) -> int { return XW_ERROR; }}; return &permissionsInterface1; } @@ -167,16 +149,15 @@ int main(int argc, char* argv[]) { struct dirent** namelist; int num_entries = scandir(tec_path.c_str(), &namelist, NULL, alphasort); - if( num_entries >= 0 ) { - for( int i = 0; i < num_entries; ++i ) { + if (num_entries >= 0) { + for (int i = 0; i < num_entries; ++i) { std::string fname = namelist[i]->d_name; if (fname.size() >= prefix_.size() + postfix_.size() && !fname.compare(0, prefix_.size(), prefix_) && - !fname.compare(fname.size() - postfix_.size(), postfix_.size(), - postfix_)) { + !fname.compare(fname.size() - postfix_.size(), postfix_.size(), postfix_)) { std::string so_path = tec_path + "/" + fname; - void *handle = dlopen(so_path.c_str(), RTLD_LAZY); + void* handle = dlopen(so_path.c_str(), RTLD_LAZY); if (handle == NULL) { std::cerr << "cannot open " << so_path << std::endl; char* error = dlerror(); @@ -184,8 +165,8 @@ int main(int argc, char* argv[]) { return -1; } - XW_Initialize_Func initialize = reinterpret_cast( - dlsym(handle, "XW_Initialize")); + XW_Initialize_Func initialize = + reinterpret_cast(dlsym(handle, "XW_Initialize")); if (!initialize) { std::cerr << "Can not loading extension " << fname << std::endl; @@ -213,8 +194,7 @@ int main(int argc, char* argv[]) { print_json(); } else { perror("scandir"); - if( errno == ENOENT ) - std::cerr << "path not exist : " << tec_path << std::endl; + if (errno == ENOENT) std::cerr << "path not exist : " << tec_path << std::endl; return -1; } diff --git a/src/tvinputdevice/tvinputdevice_extension.cc b/src/tvinputdevice/tvinputdevice_extension.cc index e007872..9bde8d1 100644 --- a/src/tvinputdevice/tvinputdevice_extension.cc +++ b/src/tvinputdevice/tvinputdevice_extension.cc @@ -12,19 +12,20 @@ namespace extension { namespace tvinputdevice { TVInputDeviceExtension::TVInputDeviceExtension() { - SetExtensionName("tizen.tvinputdevice"); - SetJavaScriptAPI(kSource_tvinputdevice_api); + SetExtensionName("tizen.tvinputdevice"); + SetJavaScriptAPI(kSource_tvinputdevice_api); } -TVInputDeviceExtension::~TVInputDeviceExtension() {} +TVInputDeviceExtension::~TVInputDeviceExtension() { +} common::Instance* TVInputDeviceExtension::CreateInstance() { - return new TVInputDeviceInstance; + return new TVInputDeviceInstance; } } // namespace tvinputdevice } // namespace extension common::Extension* CreateExtension() { - return new extension::tvinputdevice::TVInputDeviceExtension; + return new extension::tvinputdevice::TVInputDeviceExtension; } diff --git a/src/tvinputdevice/tvinputdevice_extension.h b/src/tvinputdevice/tvinputdevice_extension.h index 8a633f1..b9336c2 100644 --- a/src/tvinputdevice/tvinputdevice_extension.h +++ b/src/tvinputdevice/tvinputdevice_extension.h @@ -12,15 +12,14 @@ namespace tvinputdevice { class TVInputDeviceExtension : public common::Extension { public: - TVInputDeviceExtension(); - virtual ~TVInputDeviceExtension(); + TVInputDeviceExtension(); + virtual ~TVInputDeviceExtension(); private: - virtual common::Instance* CreateInstance(); + virtual common::Instance* CreateInstance(); }; } // namespace tvinputdevice } // namespace extension #endif // SRC_TVINPUTDEVICE_TVINPUTDEVICE_EXTENSION_H_ - diff --git a/src/tvinputdevice/tvinputdevice_instance.cc b/src/tvinputdevice/tvinputdevice_instance.cc index 67212b5..068a9de 100644 --- a/src/tvinputdevice/tvinputdevice_instance.cc +++ b/src/tvinputdevice/tvinputdevice_instance.cc @@ -13,21 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "../tvinputdevice/tvinputdevice_instance.h" #include "common/logger.h" - namespace extension { namespace tvinputdevice { TVInputDeviceInstance::TVInputDeviceInstance() { - LoggerD("Enter"); + LoggerD("Enter"); } TVInputDeviceInstance::~TVInputDeviceInstance() { - LoggerD("Enter"); + LoggerD("Enter"); } } // namespace tvinputdevice diff --git a/src/tvinputdevice/tvinputdevice_instance.h b/src/tvinputdevice/tvinputdevice_instance.h index d48248e..f02ce65 100644 --- a/src/tvinputdevice/tvinputdevice_instance.h +++ b/src/tvinputdevice/tvinputdevice_instance.h @@ -17,17 +17,16 @@ #ifndef SRC_TVINPUTDEVICE_TVINPUTDEVICE_INSTANCE_H_ #define SRC_TVINPUTDEVICE_TVINPUTDEVICE_INSTANCE_H_ -#include "common/picojson.h" #include "common/extension.h" - +#include "common/picojson.h" namespace extension { namespace tvinputdevice { class TVInputDeviceInstance : public common::ParsedInstance { public: - TVInputDeviceInstance(); - virtual ~TVInputDeviceInstance(); + TVInputDeviceInstance(); + virtual ~TVInputDeviceInstance(); private: }; diff --git a/src/utils/utils_extension.cc b/src/utils/utils_extension.cc index f422638..7840e5a 100644 --- a/src/utils/utils_extension.cc +++ b/src/utils/utils_extension.cc @@ -3,8 +3,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "common/logger.h" #include "utils/utils_extension.h" +#include "common/logger.h" #include "utils/utils_instance.h" // This will be generated from tizen_api.js. diff --git a/src/utils/utils_instance.cc b/src/utils/utils_instance.cc index be751ee..5f0eaee 100644 --- a/src/utils/utils_instance.cc +++ b/src/utils/utils_instance.cc @@ -4,8 +4,8 @@ // found in the LICENSE file. #include -#include #include +#include #include "common/logger.h" #include "common/scope_exit.h" @@ -24,14 +24,13 @@ UtilsInstance::UtilsInstance() { using std::placeholders::_2; LoggerD("Entered"); -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); -#define REGISTER_ASYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); REGISTER_SYNC("Utils_getPkgApiVersion", GetPkgApiVersion); REGISTER_SYNC("Utils_checkPrivilegeAccess", CheckPrivilegeAccess); - REGISTER_SYNC("Utils_checkBackwardCompabilityPrivilegeAccess", CheckBackwardCompabilityPrivilegeAccess); + REGISTER_SYNC("Utils_checkBackwardCompabilityPrivilegeAccess", + CheckBackwardCompabilityPrivilegeAccess); REGISTER_SYNC("Utils_toLongLong", ToLongLong); REGISTER_SYNC("Utils_toUnsignedLongLong", ToUnsignedLongLong); @@ -69,8 +68,9 @@ void UtilsInstance::CheckBackwardCompabilityPrivilegeAccess(const picojson::valu namespace { -template int sgn(T val) { - return (T(0) < val) - (val < T(0)); +template +int sgn(T val) { + return (T(0) < val) - (val < T(0)); } const double kTwoPow63 = 9223372036854775808.0; @@ -78,8 +78,7 @@ const double kTwoPow64 = 18446744073709551616.0; } // namespace -void UtilsInstance::ToLongLong(const picojson::value& args, - picojson::object& out) { +void UtilsInstance::ToLongLong(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); const auto& n = args.get("n"); @@ -98,8 +97,7 @@ void UtilsInstance::ToLongLong(const picojson::value& args, ReportSuccess(picojson::value(static_cast(output)), out); } -void UtilsInstance::ToUnsignedLongLong(const picojson::value& args, - picojson::object& out) { +void UtilsInstance::ToUnsignedLongLong(const picojson::value& args, picojson::object& out) { LoggerD("Entered"); const auto& n = args.get("n"); diff --git a/src/utils/utils_instance.h b/src/utils/utils_instance.h index 5c5e1d3..fee0d41 100644 --- a/src/utils/utils_instance.h +++ b/src/utils/utils_instance.h @@ -14,7 +14,8 @@ namespace utils { class UtilsInstance : public common::ParsedInstance { public: UtilsInstance(); - virtual ~UtilsInstance() {} + virtual ~UtilsInstance() { + } private: void GetPkgApiVersion(const picojson::value& args, picojson::object& out); diff --git a/src/websetting/websetting_extension.cc b/src/websetting/websetting_extension.cc index a80bb84..c84f7a0 100644 --- a/src/websetting/websetting_extension.cc +++ b/src/websetting/websetting_extension.cc @@ -14,8 +14,8 @@ * limitations under the License. */ -#include "common/logger.h" #include "websetting/websetting_extension.h" +#include "common/logger.h" extern const char kSource_websetting_api[]; diff --git a/src/widgetservice/widgetservice_extension.cc b/src/widgetservice/widgetservice_extension.cc old mode 100755 new mode 100644 index 9bdbfca..4f89ec6 --- a/src/widgetservice/widgetservice_extension.cc +++ b/src/widgetservice/widgetservice_extension.cc @@ -30,7 +30,8 @@ WidgetExtension::WidgetExtension() { SetJavaScriptAPI(kSource_widgetservice_api); } -WidgetExtension::~WidgetExtension() {} +WidgetExtension::~WidgetExtension() { +} common::Instance* WidgetExtension::CreateInstance() { return new extension::widgetservice::WidgetServiceInstance(); diff --git a/src/widgetservice/widgetservice_instance.cc b/src/widgetservice/widgetservice_instance.cc index eb8070d..eb1232d 100644 --- a/src/widgetservice/widgetservice_instance.cc +++ b/src/widgetservice/widgetservice_instance.cc @@ -18,14 +18,14 @@ #include -#include -#include #include #include +#include +#include -#include "widgetservice/widgetservice_utils.h" #include "common/scope_exit.h" #include "common/tools.h" +#include "widgetservice/widgetservice_utils.h" namespace extension { namespace widgetservice { @@ -50,7 +50,7 @@ const std::string kEvent = "event"; int WidgetListCb(const char* pkgid, const char* widget_id, int is_primary, void* data) { ScopeLogger(); - //is_primary is not supported by native api + // is_primary is not supported by native api picojson::array* array = static_cast(data); if (!array) { @@ -71,7 +71,7 @@ int WidgetListCb(const char* pkgid, const char* widget_id, int is_primary, void* int WidgetListByPkgIdCb(const char* widget_id, int is_primary, void* data) { ScopeLogger(); - //is_primary is not supported by native api + // is_primary is not supported by native api picojson::array* array = static_cast(data); if (!array) { @@ -110,8 +110,9 @@ int WidgetLifecycleCb(const char* widget_id, widget_lifecycle_event_e lifecycle_ const char* widget_instance_id, void* data) { ScopeLogger(); - //WIDGET_LIFE_CYCLE_EVENT_MAX event is not supported - if (WIDGET_LIFE_CYCLE_EVENT_RESUME < lifecycle_event || WIDGET_LIFE_CYCLE_EVENT_APP_DEAD == lifecycle_event) { + // WIDGET_LIFE_CYCLE_EVENT_MAX event is not supported + if (WIDGET_LIFE_CYCLE_EVENT_RESUME < lifecycle_event || + WIDGET_LIFE_CYCLE_EVENT_APP_DEAD == lifecycle_event) { LoggerW("Unknown event type"); return WIDGET_ERROR_NONE; } @@ -138,7 +139,8 @@ int WidgetLifecycleCb(const char* widget_id, widget_lifecycle_event_e lifecycle_ obj.insert(std::make_pair(kId, picojson::value(""))); } - obj.insert(std::make_pair(kEvent, picojson::value(WidgetServiceUtils::FromEventType(lifecycle_event)))); + obj.insert( + std::make_pair(kEvent, picojson::value(WidgetServiceUtils::FromEventType(lifecycle_event)))); if (nullptr != widget_id) { instance->CallWidgetLifecycleListener(widget_id, response); @@ -147,10 +149,10 @@ int WidgetLifecycleCb(const char* widget_id, widget_lifecycle_event_e lifecycle_ return WIDGET_ERROR_NONE; } -void bundleIterator(const char *key, const char *val, void *data) { - LOGD("Entered, adding key-pair value: (%s) - (%s)", key, val); - auto obj = static_cast(data); - obj->insert(std::make_pair(key, picojson::value(val))); +void bundleIterator(const char* key, const char* val, void* data) { + LOGD("Entered, adding key-pair value: (%s) - (%s)", key, val); + auto obj = static_cast(data); + obj->insert(std::make_pair(key, picojson::value(val))); } } // namespace @@ -160,8 +162,7 @@ WidgetServiceInstance::WidgetServiceInstance() { using std::placeholders::_1; using std::placeholders::_2; -#define REGISTER_SYNC(c, x) \ - RegisterSyncHandler(c, std::bind(&WidgetServiceInstance::x, this, _1)); +#define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&WidgetServiceInstance::x, this, _1)); REGISTER_SYNC("WidgetServiceManager_getWidget", GetWidget); REGISTER_SYNC("WidgetServiceManager_getPrimaryWidgetId", GetPrimaryWidgetId); @@ -175,8 +176,7 @@ WidgetServiceInstance::WidgetServiceInstance() { #undef REGISTER_SYNC -#define REGISTER_ASYNC(c, x) \ - RegisterHandler(c, std::bind(&WidgetServiceInstance::x, this, _1, _2)); +#define REGISTER_ASYNC(c, x) RegisterHandler(c, std::bind(&WidgetServiceInstance::x, this, _1, _2)); REGISTER_ASYNC("WidgetServiceManager_getWidgets", GetWidgets); REGISTER_ASYNC("Widget_getInstances", GetInstances); @@ -208,7 +208,7 @@ TizenResult WidgetServiceInstance::GetWidget(const picojson::object& args) { const auto& widget_id = args.find(kWidgetId)->second.get(); - picojson::value value {picojson::object{}}; + picojson::value value{picojson::object{}}; auto* obj = &value.get(); auto result = WidgetServiceUtils::WidgetToJson(widget_id.c_str(), obj); @@ -220,7 +220,7 @@ TizenResult WidgetServiceInstance::GetWidget(const picojson::object& args) { } TizenResult WidgetServiceInstance::GetWidgets(const picojson::object& args, - const common::AsyncToken& token) { + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeWidgetService); @@ -272,8 +272,8 @@ TizenResult WidgetServiceInstance::GetPrimaryWidgetId(const picojson::object& ar char* widget_id = widget_service_get_widget_id(id.c_str()); if (!widget_id) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(get_last_result()), ("widget_service_get_widget_id() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(get_last_result()), + ("widget_service_get_widget_id() failed")); } SCOPE_EXIT { @@ -288,7 +288,8 @@ TizenResult WidgetServiceInstance::GetSize(const picojson::object& args) { CHECK_EXIST(args, kSizeType, out) - widget_size_type_e type = WidgetServiceUtils::ToSizeType(args.find(kSizeType)->second.get()); + widget_size_type_e type = + WidgetServiceUtils::ToSizeType(args.find(kSizeType)->second.get()); if (WIDGET_SIZE_TYPE_UNKNOWN == type) { LogAndReturnTizenError(common::InvalidValuesError(), ("incorrect size type")); } @@ -321,8 +322,8 @@ TizenResult WidgetServiceInstance::GetName(picojson::object const& args) { char* name = widget_service_get_name(widget_id.c_str(), locale); if (!name) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(get_last_result()), ("widget_service_get_name() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(get_last_result()), + ("widget_service_get_name() failed")); } SCOPE_EXIT { @@ -332,7 +333,8 @@ TizenResult WidgetServiceInstance::GetName(picojson::object const& args) { return TizenSuccess(picojson::value(name)); } -TizenResult WidgetServiceInstance::GetInstances(picojson::object const& args, const common::AsyncToken& token) { +TizenResult WidgetServiceInstance::GetInstances(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_EXIST(args, kWidgetId, out) @@ -389,13 +391,14 @@ TizenResult WidgetServiceInstance::GetVariant(picojson::object const& args) { LogAndReturnTizenError(result, ("GetVariant() failed")); } - //sizeType + // sizeType obj->insert(std::make_pair(kSizeType, picojson::value(type))); return TizenSuccess(value); } -TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, const common::AsyncToken& token) { +TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_PRIVILEGE(kPrivilegeWidgetService); @@ -415,9 +418,9 @@ TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, con return; } - //it is not mentioned in header file if array should be freed by caller - //but in widget_service_get_supported_size_types definition it is allocated - //so it should be released when it is not needed anymore + // it is not mentioned in header file if array should be freed by caller + // but in widget_service_get_supported_size_types definition it is allocated + // so it should be released when it is not needed anymore SCOPE_EXIT { free(type_array); }; @@ -441,7 +444,8 @@ TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, con break; } - obj->insert(std::make_pair(kSizeType, picojson::value(WidgetServiceUtils::FromSizeType(size_type)))); + obj->insert( + std::make_pair(kSizeType, picojson::value(WidgetServiceUtils::FromSizeType(size_type)))); array.push_back(val); } @@ -458,7 +462,7 @@ TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, con } void WidgetServiceInstance::CallWidgetLifecycleListener(const std::string& widget_id, - const picojson::value& response) { + const picojson::value& response) { ScopeLogger(); std::lock_guard lock(listener_mutex_); @@ -487,10 +491,10 @@ TizenResult WidgetServiceInstance::AddStateChangeListener(picojson::object const return TizenSuccess(); } - int ret = widget_service_set_lifecycle_event_cb(widget_id.c_str(), WidgetLifecycleCb , this); + int ret = widget_service_set_lifecycle_event_cb(widget_id.c_str(), WidgetLifecycleCb, this); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(ret), ("widget_service_set_lifecycle_event_cb() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(ret), + ("widget_service_set_lifecycle_event_cb() failed")); } listener_map_[widget_id]++; @@ -515,8 +519,8 @@ TizenResult WidgetServiceInstance::RemoveStateChangeListener(picojson::object co if (!(--it->second)) { int ret = widget_service_unset_lifecycle_event_cb(widget_id.c_str(), nullptr); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(ret), ("widget_service_unset_lifecycle_event_cb() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(ret), + ("widget_service_unset_lifecycle_event_cb() failed")); } listener_map_.erase(it); } @@ -535,16 +539,17 @@ TizenResult WidgetServiceInstance::ChangeUpdatePeriod(picojson::object const& ar const auto& instance_id = args.find(kInstanceId)->second.get(); const double seconds = args.find(kSeconds)->second.get(); - if(seconds <= 0){ - int err = WIDGET_ERROR_INVALID_PARAMETER; - LogAndReturnTizenError(common::InvalidValuesError(err), ("period second should be greater than zero")); + if (seconds <= 0) { + int err = WIDGET_ERROR_INVALID_PARAMETER; + LogAndReturnTizenError(common::InvalidValuesError(err), + ("period second should be greater than zero")); } int ret = widget_service_change_period(widget_id.c_str(), instance_id.c_str(), seconds); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(ret), ("widget_service_change_period() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(ret), + ("widget_service_change_period() failed")); } return TizenSuccess(); @@ -580,14 +585,15 @@ TizenResult WidgetServiceInstance::SendContent(picojson::object const& args) { ret = widget_service_trigger_update(widget_id.c_str(), instance_id.c_str(), data, force); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - WidgetServiceUtils::ConvertErrorCode(ret), ("widget_service_trigger_update() failed")); + LogAndReturnTizenError(WidgetServiceUtils::ConvertErrorCode(ret), + ("widget_service_trigger_update() failed")); } return TizenSuccess(); } -TizenResult WidgetServiceInstance::GetContent(picojson::object const& args, const common::AsyncToken& token) { +TizenResult WidgetServiceInstance::GetContent(picojson::object const& args, + const common::AsyncToken& token) { ScopeLogger(); CHECK_EXIST(args, kWidgetId, out) @@ -610,8 +616,8 @@ TizenResult WidgetServiceInstance::GetContent(picojson::object const& args, cons bundle_free(bundle_data); }; - ret = widget_service_get_content_of_widget_instance(widget_id.c_str(), - instance_id.c_str(), &bundle_data); + ret = widget_service_get_content_of_widget_instance(widget_id.c_str(), instance_id.c_str(), + &bundle_data); if (WIDGET_ERROR_NONE != ret) { LoggerE("widget_service_get_content_of_widget_instance() failed"); this->Post(token, WidgetServiceUtils::ConvertErrorCode(ret)); @@ -637,5 +643,5 @@ TizenResult WidgetServiceInstance::GetContent(picojson::object const& args, cons return TizenSuccess(); } -} // namespace widgetservice -} // namespace extension +} // namespace widgetservice +} // namespace extension diff --git a/src/widgetservice/widgetservice_instance.h b/src/widgetservice/widgetservice_instance.h old mode 100755 new mode 100644 index 747f100..b9b80f2 --- a/src/widgetservice/widgetservice_instance.h +++ b/src/widgetservice/widgetservice_instance.h @@ -17,8 +17,8 @@ #ifndef WIDGETSERVICE_WIDGET_INSTANCE_H_ #define WIDGETSERVICE_WIDGET_INSTANCE_H_ -#include #include +#include #include "common/tizen_instance.h" @@ -30,20 +30,21 @@ class WidgetServiceInstance : public common::TizenInstance { WidgetServiceInstance(); virtual ~WidgetServiceInstance(); void CallWidgetLifecycleListener(const std::string& widget_id, const picojson::value& response); + private: - //WidgetManager + // WidgetManager common::TizenResult GetWidget(picojson::object const& args); common::TizenResult GetWidgets(picojson::object const& args, const common::AsyncToken& token); common::TizenResult GetPrimaryWidgetId(picojson::object const& args); common::TizenResult GetSize(picojson::object const& args); - //Widget + // Widget common::TizenResult GetName(picojson::object const& args); common::TizenResult GetInstances(picojson::object const& args, const common::AsyncToken& token); common::TizenResult GetVariant(picojson::object const& args); common::TizenResult GetVariants(picojson::object const& args, const common::AsyncToken& token); common::TizenResult AddStateChangeListener(picojson::object const& args); common::TizenResult RemoveStateChangeListener(picojson::object const& args); - //WidgetInstance + // WidgetInstance common::TizenResult ChangeUpdatePeriod(picojson::object const& args); common::TizenResult SendContent(picojson::object const& args); common::TizenResult GetContent(picojson::object const& args, const common::AsyncToken& token); @@ -52,7 +53,7 @@ class WidgetServiceInstance : public common::TizenInstance { std::map listener_map_; }; -} // namespace widgetservice -} // namespace extension +} // namespace widgetservice +} // namespace extension -#endif // WIDGETSERVICE_WIDGET_INSTANCE_H_ +#endif // WIDGETSERVICE_WIDGET_INSTANCE_H_ diff --git a/src/widgetservice/widgetservice_utils.cc b/src/widgetservice/widgetservice_utils.cc index 142cbbb..6736d81 100644 --- a/src/widgetservice/widgetservice_utils.cc +++ b/src/widgetservice/widgetservice_utils.cc @@ -23,30 +23,30 @@ namespace widgetservice { namespace { -#define WIDGET_SIZE_TYPE_E \ - X(WIDGET_SIZE_TYPE_1x1, "1x1") \ - X(WIDGET_SIZE_TYPE_2x1, "2x1") \ - X(WIDGET_SIZE_TYPE_2x2, "2x2") \ - X(WIDGET_SIZE_TYPE_4x1, "4x1") \ - X(WIDGET_SIZE_TYPE_4x2, "4x2") \ - X(WIDGET_SIZE_TYPE_4x3, "4x3") \ - X(WIDGET_SIZE_TYPE_4x4, "4x4") \ - X(WIDGET_SIZE_TYPE_4x5, "4x5") \ - X(WIDGET_SIZE_TYPE_4x6, "4x6") \ +#define WIDGET_SIZE_TYPE_E \ + X(WIDGET_SIZE_TYPE_1x1, "1x1") \ + X(WIDGET_SIZE_TYPE_2x1, "2x1") \ + X(WIDGET_SIZE_TYPE_2x2, "2x2") \ + X(WIDGET_SIZE_TYPE_4x1, "4x1") \ + X(WIDGET_SIZE_TYPE_4x2, "4x2") \ + X(WIDGET_SIZE_TYPE_4x3, "4x3") \ + X(WIDGET_SIZE_TYPE_4x4, "4x4") \ + X(WIDGET_SIZE_TYPE_4x5, "4x5") \ + X(WIDGET_SIZE_TYPE_4x6, "4x6") \ X(WIDGET_SIZE_TYPE_EASY_1x1, "EASY_1x1") \ X(WIDGET_SIZE_TYPE_EASY_3x1, "EASY_3x1") \ X(WIDGET_SIZE_TYPE_EASY_3x3, "EASY_3x3") \ - X(WIDGET_SIZE_TYPE_FULL, "FULL") \ + X(WIDGET_SIZE_TYPE_FULL, "FULL") \ XD(WIDGET_SIZE_TYPE_UNKNOWN, "unknown") -#define WIDGET_LIFECYCLE_EVENT_E \ - X(WIDGET_LIFE_CYCLE_EVENT_CREATE, "CREATE") \ +#define WIDGET_LIFECYCLE_EVENT_E \ + X(WIDGET_LIFE_CYCLE_EVENT_CREATE, "CREATE") \ X(WIDGET_LIFE_CYCLE_EVENT_DESTROY, "DESTROY") \ - X(WIDGET_LIFE_CYCLE_EVENT_PAUSE, "PAUSE") \ - X(WIDGET_LIFE_CYCLE_EVENT_RESUME, "RESUME") \ + X(WIDGET_LIFE_CYCLE_EVENT_PAUSE, "PAUSE") \ + X(WIDGET_LIFE_CYCLE_EVENT_RESUME, "RESUME") \ XD(WIDGET_LIFE_CYCLE_EVENT_MAX, "unknown") -} // namespace +} // namespace const std::string kWidgetId = "widgetId"; const std::string kPackageId = "packageId"; @@ -96,50 +96,51 @@ TizenResult WidgetServiceUtils::ConvertErrorCode(int error) { } } -TizenResult WidgetServiceUtils::WidgetToJson(const char* id, picojson::object* out, const char* pkgid) { +TizenResult WidgetServiceUtils::WidgetToJson(const char* id, picojson::object* out, + const char* pkgid) { ScopeLogger(); - //applicationId + // applicationId char* tmp_str = widget_service_get_main_app_id(id); if (!tmp_str) { - LogAndReturnTizenError( - ConvertErrorCode(get_last_result()), ("widget_service_get_main_app_id() failed")); + LogAndReturnTizenError(ConvertErrorCode(get_last_result()), + ("widget_service_get_main_app_id() failed")); } out->insert(std::make_pair(kApplicationId, picojson::value(tmp_str))); free(tmp_str); - //setupApplicationId + // setupApplicationId tmp_str = widget_service_get_app_id_of_setup_app(id); if (!tmp_str) { if (WIDGET_ERROR_NONE != get_last_result()) { - LogAndReturnTizenError( - ConvertErrorCode(get_last_result()), ("widget_service_get_app_id_of_setup_app() failed")); + LogAndReturnTizenError(ConvertErrorCode(get_last_result()), + ("widget_service_get_app_id_of_setup_app() failed")); } } else { out->insert(std::make_pair(kSetupApplicationId, picojson::value(tmp_str))); free(tmp_str); } - //packageId + // packageId if (!pkgid) { tmp_str = widget_service_get_package_id(id); if (!tmp_str) { - LogAndReturnTizenError( - ConvertErrorCode(get_last_result()), ("widget_service_get_package_id() failed")); + LogAndReturnTizenError(ConvertErrorCode(get_last_result()), + ("widget_service_get_package_id() failed")); } out->insert(std::make_pair(kPackageId, picojson::value(tmp_str))); free(tmp_str); } - //noDisplay + // noDisplay bool tmp_bool = widget_service_get_nodisplay(id); if (WIDGET_ERROR_NONE != get_last_result()) { - LogAndReturnTizenError( - ConvertErrorCode(get_last_result()), ("widget_service_get_nodisplay() failed")); + LogAndReturnTizenError(ConvertErrorCode(get_last_result()), + ("widget_service_get_nodisplay() failed")); } out->insert(std::make_pair(kNoDisplay, picojson::value(tmp_bool))); - //id + // id out->insert(std::make_pair(kId, picojson::value(id))); return TizenSuccess(); @@ -162,41 +163,40 @@ TizenResult WidgetServiceUtils::SizeToJson(widget_size_type_e type, picojson::ob return TizenSuccess(); } -TizenResult WidgetServiceUtils::WidgetVariantToJson( - const char* id, widget_size_type_e type, picojson::object* out) { +TizenResult WidgetServiceUtils::WidgetVariantToJson(const char* id, widget_size_type_e type, + picojson::object* out) { ScopeLogger(); bool tmp = false; - //needsMouseEvents + // needsMouseEvents int ret = widget_service_get_need_of_mouse_event(id, type, &tmp); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - ConvertErrorCode(ret), ("widget_service_get_need_of_mouse_event() failed")); + LogAndReturnTizenError(ConvertErrorCode(ret), + ("widget_service_get_need_of_mouse_event() failed")); } out->insert(std::make_pair(kNeedsMouseEvents, picojson::value(tmp))); - //needsTouchEffect + // needsTouchEffect ret = widget_service_get_need_of_touch_effect(id, type, &tmp); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - ConvertErrorCode(ret), ("widget_service_get_need_of_touch_effect() failed")); + LogAndReturnTizenError(ConvertErrorCode(ret), + ("widget_service_get_need_of_touch_effect() failed")); } out->insert(std::make_pair(kNeedsTouchEffect, picojson::value(tmp))); - //needsFrame + // needsFrame ret = widget_service_get_need_of_frame(id, type, &tmp); if (WIDGET_ERROR_NONE != ret) { - LogAndReturnTizenError( - ConvertErrorCode(ret), ("widget_service_get_need_of_frame() failed")); + LogAndReturnTizenError(ConvertErrorCode(ret), ("widget_service_get_need_of_frame() failed")); } out->insert(std::make_pair(kNeedsFrame, picojson::value(tmp))); - //previewImagePath + // previewImagePath char* path = widget_service_get_preview_image_path(id, type); if (!path) { - LogAndReturnTizenError( - ConvertErrorCode(get_last_result()), ("widget_service_get_preview_image_path() failed")); + LogAndReturnTizenError(ConvertErrorCode(get_last_result()), + ("widget_service_get_preview_image_path() failed")); } out->insert(std::make_pair(kPreviewImagePath, picojson::value(path))); free(path); @@ -204,33 +204,32 @@ TizenResult WidgetServiceUtils::WidgetVariantToJson( return TizenSuccess(); } -#define X(v, s) case v: return s; -#define XD(v, s) \ - default: \ +#define X(v, s) \ + case v: \ + return s; +#define XD(v, s) \ + default: \ LoggerE("Unknown value: %d, returning default: %s", e, s); \ return s; std::string WidgetServiceUtils::FromSizeType(widget_size_type_e e) { ScopeLogger(); - switch (e) { - WIDGET_SIZE_TYPE_E - } + switch (e) { WIDGET_SIZE_TYPE_E } } std::string WidgetServiceUtils::FromEventType(widget_lifecycle_event_e e) { ScopeLogger(); - switch (e) { - WIDGET_LIFECYCLE_EVENT_E - } + switch (e) { WIDGET_LIFECYCLE_EVENT_E } } #undef X #undef XD -#define X(v, s) if (e == s) return v; -#define XD(v, s) \ +#define X(v, s) \ + if (e == s) return v; +#define XD(v, s) \ LoggerE("Unknown value: %s, returning default: %d", e.c_str(), v); \ return v; @@ -243,5 +242,5 @@ widget_size_type_e WidgetServiceUtils::ToSizeType(const std::string& e) { #undef X #undef XD -} // widgetservice -} // extension +} // widgetservice +} // extension diff --git a/src/widgetservice/widgetservice_utils.h b/src/widgetservice/widgetservice_utils.h index 5f6a264..cf240ae 100644 --- a/src/widgetservice/widgetservice_utils.h +++ b/src/widgetservice/widgetservice_utils.h @@ -26,8 +26,8 @@ namespace extension { namespace widgetservice { -#define CHECK_EXIST(args, name, out) \ - if (args.end() == args.find(name)) { \ +#define CHECK_EXIST(args, name, out) \ + if (args.end() == args.find(name)) { \ return common::TypeMismatchError(std::string(name) + " is required argument"); \ } @@ -44,13 +44,14 @@ class WidgetServiceUtils { static std::string FromSizeType(widget_size_type_e e); static std::string FromEventType(widget_lifecycle_event_e e); static common::TizenResult ConvertErrorCode(int error); - static common::TizenResult WidgetToJson(const char* id, picojson::object* out, const char* pkgid = nullptr); + static common::TizenResult WidgetToJson(const char* id, picojson::object* out, + const char* pkgid = nullptr); static common::TizenResult SizeToJson(widget_size_type_e type, picojson::object* out); - static common::TizenResult WidgetVariantToJson(const char* id, widget_size_type_e type, picojson::object* out); - + static common::TizenResult WidgetVariantToJson(const char* id, widget_size_type_e type, + picojson::object* out); }; -} // widgetservice -} // extension +} // widgetservice +} // extension -#endif // WEBAPI_PLUGINS_WIDGETSERVICE_WIDGET_UTILS_H__ +#endif // WEBAPI_PLUGINS_WIDGETSERVICE_WIDGET_UTILS_H__ -- 2.7.4