content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.brewerylookup.data import com.example.brewerylookup.model.BreweryList import com.example.brewerylookup.model.Directions import com.example.brewerylookup.network.NetworkDataSource import javax.inject.Inject class BreweryLookupRepository @Inject constructor( private val dataSource: NetworkDataSource ) { suspend fun searchAllBreweries( pageNumber: Int, amountPerPage: Int? ): Result<List<BreweryList>> { return dataSource.searchAllBreweries(pageNumber, amountPerPage) .map { BreweryList.fromNetwork(it) } } suspend fun searchByFilter( breweryType: String?, state: String?, postalCode: String?, city: String?, breweryName: String? ): Result<List<BreweryList>> { return dataSource.searchByFilter(breweryType, state, postalCode, city, breweryName) .map { BreweryList.fromNetwork(it) } } suspend fun getDirections( startingAddress: String, destinationAddress: String, apiKey: String ): Result<Directions?> { return dataSource.getDirections(startingAddress, destinationAddress, apiKey) .map { Directions.fromNetwork(it) } } }
brewery-lookup-app/app/src/main/java/com/example/brewerylookup/data/BreweryLookupRepository.kt
1742491004
class AppUpdateCheckForegroundService : Service() { private var job: Job? = null val imageRepo = ImageRepo() inner class LocalBinder : Binder() { fun getService(): AppUpdateCheckForegroundService = this@AppUpdateCheckForegroundService } // Create the instance on the service. private val binder = LocalBinder() override fun onCreate() { super.onCreate() /*createNotificationChannel() val notificationIntent = Intent(this, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0) val notification = NotificationCompat.Builder(this, channelId) .setContentTitle(getString(R.string.checking_for_updates)) .setPriority(NotificationCompat.PRIORITY_LOW) .setContentText(getString(R.string.fetching_data)) .setSmallIcon(getNotificationIcon()) .setStyle( NotificationCompat.BigTextStyle().bigText(getString(R.string.fetching_data)) ) .setContentIntent(pendingIntent) .build()*/ //startForeground(onGoingNotificationID, notification) /*try { if (NetworkUtil.isNetworkConnected(this)) { /* createNotificationChannel() val notificationIntent = Intent(this, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0) val notification = NotificationCompat.Builder(this, channelId) .setContentTitle(getString(R.string.checking_for_updates)) .setPriority(NotificationCompat.PRIORITY_LOW) .setContentText(getString(R.string.fetching_data)) .setSmallIcon(getNotificationIcon()) .setStyle( NotificationCompat.BigTextStyle().bigText(getString(R.string.fetching_data)) ) .setContentIntent(pendingIntent) .build() startForeground(onGoingNotificationID, notification)*/ job = GlobalScope.launch(Dispatchers.IO) { imageRepo.readFileWithoutDownload().collect { it?.let { checkForUpdate(it) AppState.config.prefForceUdpatedStatus = true } ?: kotlin.run { AppState.config.prefForceUdpatedStatus = false } stopForeground(true) stopSelf() AppConstant.isAppUpdateCheckServiceRunning = false } } } else { AppState.config.prefForceUdpatedStatus = false stopForeground(true) stopSelf() AppConstant.isAppUpdateCheckServiceRunning = false } }catch (e:java.lang.Exception){ AppState.config.prefForceUdpatedStatus = false AppConstant.isAppUpdateCheckServiceRunning = false }*/ } override fun onBind(intent: Intent): IBinder { return binder } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { /*if (NetworkUtil.isNetworkConnected(this)) { createNotificationChannel() val notificationIntent = Intent(this, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0) val notification = NotificationCompat.Builder(this, channelId) .setContentTitle(getString(R.string.checking_for_updates)) .setPriority(NotificationCompat.PRIORITY_LOW) .setContentText(getString(R.string.fetching_data)) .setSmallIcon(getNotificationIcon()) .setStyle( NotificationCompat.BigTextStyle().bigText(getString(R.string.fetching_data)) ) .setContentIntent(pendingIntent) .build() startForeground(onGoingNotificationID, notification) } else { AppState.config.prefForceUdpatedStatus = false }*/ AppConstant.isAppUpdateCheckServiceRunning = true try { if (NetworkUtil.isNetworkConnected(this)) { /* createNotificationChannel() val notificationIntent = Intent(this, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0) val notification = NotificationCompat.Builder(this, channelId) .setContentTitle(getString(R.string.checking_for_updates)) .setPriority(NotificationCompat.PRIORITY_LOW) .setContentText(getString(R.string.fetching_data)) .setSmallIcon(getNotificationIcon()) .setStyle( NotificationCompat.BigTextStyle().bigText(getString(R.string.fetching_data)) ) .setContentIntent(pendingIntent) .build() startForeground(onGoingNotificationID, notification)*/ job = GlobalScope.launch(Dispatchers.IO) { imageRepo.readFileWithoutDownload().collect { it?.let { checkForUpdate(it) AppState.config.prefForceUdpatedStatus = true } ?: kotlin.run { AppState.config.prefForceUdpatedStatus = false } AppState.config.lastUpdateCheckTimeStamp= Calendar.getInstance().timeInMillis stopForeground(true) stopSelf() AppConstant.isAppUpdateCheckServiceRunning = false } } } else { AppState.config.prefForceUdpatedStatus = false stopForeground(true) stopSelf() AppConstant.isAppUpdateCheckServiceRunning = false } }catch (e:java.lang.Exception){ AppState.config.prefForceUdpatedStatus = false AppConstant.isAppUpdateCheckServiceRunning = false AppState.config.lastUpdateCheckTimeStamp= Calendar.getInstance().timeInMillis } return START_NOT_STICKY } private fun getNotificationIcon(): Int { val useWhiteIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP return if (useWhiteIcon) R.drawable.ic_bushnell_round else R.drawable.app_rate_logo } private fun checkForUpdate(fileText: String) { val fileTextArray = fileText.lines() AppLog.errorLog("$fileTextArray") if (fileTextArray.size >= 2) { val latestVersion = splitWithEqualSignRetrieveValue(fileTextArray[0]) ?: "" val isForceUpdate = splitWithEqualSignRetrieveValue(fileTextArray[1]).toBoolean() val downloadSize = "0" try { AppState.config.appVersionInServer = latestVersion AppState.config.needForceUpdate = isForceUpdate AppState.config.downloadSize = downloadSize ?: "" AppState.config.skipUpdate=false } catch (e: Exception) { } EventBus.getDefault().postSticky( UpdateMessageEvent( latestVersion = latestVersion, isForceUpdate = isForceUpdate, downloadSize = downloadSize ) ) } } private fun splitWithEqualSignRetrieveValue(text: String): String? { val splitArray = text.split("=") if (splitArray.size == 2) { return splitArray[1] } return null } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( channelId, "Foreground Service Channel", NotificationManager.IMPORTANCE_LOW ) notificationChannel.setSound(null, null) val notificationManager = getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(notificationChannel) } } override fun onDestroy() { super.onDestroy() job?.cancel() AppConstant.isAppUpdateCheckServiceRunning = false } }
Trailcamera/AppUpdateCheckForegroundService.kt
1993515748
class CameraLocationFragment : BaseFragment(), LocationProvider.LocationUpdateListener { private lateinit var binding: FragmentCameraLocationBinding private lateinit var commonToolbarBinding: LayoutCommonToolbarBinding // private lateinit var cameraLocationVM: CameraLocationViewModel private val cameraLocationVM: CameraLocationViewModel by viewModels() private lateinit var cameraList: ArrayList<CameraBasicInfo> private var selectedCameraObj: CameraBasicInfo? = null private var screenTitle: String = "" private var mapViewType: Int = GoogleMap.MAP_TYPE_HYBRID private var isMapViewTypeChanged = false private lateinit var clusterManager: ClusterManager<LocationItem> private var locationProvider: LocationProvider? = null private val gpsReceiver = GpsLocationReceiver() private var newLocation: Location? = null private var nMap: GoogleMap? = null companion object { @JvmStatic fun newInstance(bundle: Bundle? = null) = CameraLocationFragment() .apply { arguments = bundle } const val BUNDLE_EXTRA_CAMERA_LIST = "camera_list" const val BUNDLE_EXTRA_TITLE = "title" var TAG = CameraLocationFragment::class.java.simpleName.toString() } override fun initToolbar() { super.initToolbar() commonToolbarBinding = binding.toolbar commonToolbarBinding.ivBack.visibility = View.VISIBLE commonToolbarBinding.tvToolbarTitle.text = screenTitle } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentCameraLocationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isAdded && activity != null) setMapView() cameraList = arguments?.getSerializable(BUNDLE_EXTRA_CAMERA_LIST) as ArrayList<CameraBasicInfo> screenTitle = arguments?.getString(BUNDLE_EXTRA_TITLE).toString() initToolbar() if (cameraList.size <= 1) setCameraLocationsObserver() } private fun setMapView() { val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync(callback) } override fun init() { // initViewModel() setClickListeners() locationProvider = LocationProvider(requireContext(), this) setFragmentResultListener(CameraConstants.RESULT_CAMERA_EDIT_LOCATION) { key, bundle -> if (bundle.getString("data") == CameraConstants.CAMERA_EDIT_LOCATION_CONFIRM) { cameraLocationVM.isLocationEdited = true removeEditLocationFragment() cameraLocationVM.editedCameraId = bundle.getInt("cameraId", -1) AppLog.errorLog("" + cameraLocationVM.editedCameraId) if (cameraList.size >= 1) setMapView() } } } override fun setObservers() { setCameraSelectedObserver() setProgressObserver() } /* private fun initViewModel() { cameraLocationVM = ViewModelProvider(requireActivity()).get( CameraLocationViewModel::class.java ) }*/ private fun setClickListeners() { binding.tvStreet.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) mapViewType = GoogleMap.MAP_TYPE_TERRAIN isMapViewTypeChanged = true setMapView() } binding.tvHybrid.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) mapViewType = GoogleMap.MAP_TYPE_HYBRID isMapViewTypeChanged = true setMapView() } binding.tvSatellite.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) mapViewType = GoogleMap.MAP_TYPE_SATELLITE isMapViewTypeChanged = true setMapView() } binding.ivMyLocation.setOnClickListener { cameraLocationVM.isMyLocationClicked = true if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { if (checkLocationDisabled()) checkLocationPermission() else { initWebServiceCallAfterChecks() } } else { checkLocationPermission() } } binding.tvEdit.setOnClickListener { showCameraLocationEditScreen() } binding.lyLocationTitle.setOnClickListener{ } } private val callback = OnMapReadyCallback { googleMap -> googleMap.mapType = mapViewType googleMap.uiSettings.isMapToolbarEnabled =false nMap = googleMap if(!isMapViewTypeChanged) { if (cameraList.size > 0) { if (cameraList.size > 1) { binding.cvSwitchMapType.visibility = View.VISIBLE setUpCluster(googleMap, cameraList, false) } else { val orangeMarkerBMapDescriptor = BitmapDescriptorFactory.fromResource((R.drawable.ic_map_marker_orange)) val camera = cameraList[0] val cameraLocation = LatLng(camera.latitude!!, camera.longitude!!) val cameraName = camera.cameraName googleMap.addMarker( MarkerOptions().position(cameraLocation).title(cameraName) .icon(orangeMarkerBMapDescriptor) )?.tag = camera.cameraID googleMap.animateCamera( CameraUpdateFactory.newLatLngZoom( cameraLocation, MAP_ZOOM_LEVEL ) ) selectedCameraObj = camera getCameraSelected(camera) } } }else { isMapViewTypeChanged = false } } private val anchorClick = GoogleMap.OnMarkerClickListener { marker -> val selectedAnchorTag = marker.tag val selectedCamera = cameraList.filter { it.cameraID == selectedAnchorTag }[0] selectedCameraObj = selectedCamera getCameraSelected(selectedCamera) false } private fun getCameraSelected(selectedCamera: CameraBasicInfo) { if (isAdded && activity!=null && NetworkUtil.isNetworkConnected(requireActivity())) { cameraLocationVM.getCameraSelected(context, selectedCamera,0) } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } private fun setCameraSelectedObserver() { cameraLocationVM.cameraAddressLiveData.observe(viewLifecycleOwner, EventObserver { if (it.isNotEmpty()) { setCameraNameAndAddress(selectedCameraObj?.cameraName, it) } }) } private fun setCameraNameAndAddress(cameraName: String?, addressText: String) { binding.tvNameTitle.text = cameraName binding.tvLocationName.text = addressText binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE if(selectedCameraObj?.active!=null&&selectedCameraObj?.active!!) binding.tvEdit.visibility = View.VISIBLE else binding.tvEdit.visibility = View.GONE } private fun setProgressObserver() { cameraLocationVM.progressStatus.observe(viewLifecycleOwner, EventObserver { if (cameraLocationVM.isBlockingOperationInProgress) { if (it) { DialogUtil.showProgressDialog( requireActivity(), getString(R.string.fetching_camera_address) ) } else { DialogUtil.dismissProgressDialog() } } }) } private fun setCameraLocationsObserver() { cameraLocationVM.getAllCameraLocationInfoFromDatabase() ?.observe(viewLifecycleOwner, Observer { list -> if (!list.isNullOrEmpty()) { if (list.size > 1) { if (nMap != null) { setUpCluster(nMap!!, list as ArrayList<CameraBasicInfo>, true) } } } }) } private fun setUpCluster( map: GoogleMap, list: ArrayList<CameraBasicInfo>, isFromObserver: Boolean ) { map.clear() if (!isFromObserver) { for(i in 0 until cameraList.size){ if(cameraList[i].latitude!! != 0.0 && cameraList[i].longitude!! != 0.0 ){ selectedCameraObj = cameraList[i] break } } if (cameraLocationVM.isLocationEdited && cameraLocationVM.editedCameraId >= 0) { val lastItemIndex = cameraList.indexOfLast { it.cameraID == cameraLocationVM.editedCameraId } selectedCameraObj = cameraList[lastItemIndex] getCameraSelected(selectedCameraObj!!) cameraLocationVM.isLocationEdited = false } map.moveCamera( CameraUpdateFactory.newLatLngZoom( LatLng( selectedCameraObj?.latitude!!, selectedCameraObj?.longitude!! ), LOCATIONS_ZOOM_LEVEL ) ) } clusterManager = ClusterManager(requireActivity(), map) clusterManager.renderer = MarkerClusterRenderer( requireActivity(), map, clusterManager, isFromObserver ) map.setOnCameraIdleListener(clusterManager) clusterManager.setOnClusterItemClickListener { var selectedCamera = CameraBasicInfo() for (i in 0 until list.size) { if (it.snippet.equals("Camera $i")) { selectedCamera = list[i] break } } if (!isFromObserver) { selectedCameraObj = selectedCamera getCameraSelected(selectedCamera) } false } clusterManager.setOnClusterClickListener { map.animateCamera( CameraUpdateFactory.newLatLngZoom( it.position, (floor((map.cameraPosition.zoom + 1).toDouble()).toFloat()) ), 300, null ) true } addLocations(isFromObserver, list) } private fun addLocations(isFromObserver: Boolean, list: ArrayList<CameraBasicInfo>) { for (i in 0 until list.size) { if (isFromObserver && selectedCameraObj?.cameraID != list[i].cameraID) { val offset = i / 800.0 val lat = list[i].latitude!! + offset val lon = list[i].longitude!! + offset val offsetItem = LocationItem( lat, lon, list[i].cameraName!!, "Camera $i" ) clusterManager.addItem(offsetItem) } else if (!isFromObserver) { val offset = i / 800.0 val lat = list[i].latitude!! + offset val lon = list[i].longitude!! + offset val offsetItem = LocationItem( lat, lon, list[i].cameraName!!, "Camera $i" ) clusterManager.addItem(offsetItem) } } if (isFromObserver) { Handler(Looper.getMainLooper()).postDelayed({ if (isAdded) { mapViewType = GoogleMap.MAP_TYPE_HYBRID setMapView() } }, 2000) } } private fun checkLocationDisabled(): Boolean { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager return !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } override fun handleNewLocation(location: Location?) { if (location != null) { newLocation = location if (cameraLocationVM.isMyLocationClicked) { cameraLocationVM.isMyLocationClicked = false setMyLocationOnFocus() } } else { locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } } private fun setMyLocationOnFocus() { if (activity!= null && isAdded && !requireActivity().isFinishing && newLocation?.latitude != null && newLocation?.longitude != null) { val myLocation = LatLng(newLocation?.latitude!!, newLocation?.longitude!!) val locationMarkerBMapDescriptor = BitmapDescriptorFactory.fromResource((R.drawable.ic_current_location)) selectedCameraObj!!.latitude = newLocation!!.latitude selectedCameraObj!!.longitude = newLocation!!.longitude selectedCameraObj!!.cameraName = "My Location" nMap?.addMarker( MarkerOptions().position(myLocation).title(selectedCameraObj!!.cameraName) .icon(locationMarkerBMapDescriptor) ) nMap?.animateCamera( CameraUpdateFactory.newLatLngZoom( myLocation, AppConstant.EDIT_MAP_ZOOM_LEVEL ) ) binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE binding.tvNameTitle.text = selectedCameraObj!!.cameraName binding.tvLocationName.text = getString(R.string.fetching_camera_location_address) getCameraSelected(selectedCameraObj!!) } else { AppLog.errorLog("get last location : setMyLocationOnFocus") locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } } override fun locationUpdateTimeout() { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } override fun locationSettingError(error: String) { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } override fun locationDisabled() { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } @SuppressLint("MissingPermission") private fun checkLocationPermission() { if (PermissionUtil().checkIfPermissionGranted( context, Manifest.permission.ACCESS_FINE_LOCATION ) ) { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false initWebServiceCallAfterChecks() } else { PermissionUtil().requestPermission( context, Manifest.permission.ACCESS_FINE_LOCATION, object : PermissionResultListener { override fun onPermissionGranted() { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false initWebServiceCallAfterChecks() } override fun onPermissionDenied() { if (cameraLocationVM.isMyLocationClicked) showGoToSettingsDialog() cameraLocationVM.isLocationDisabled = true } override fun onPermissionRationaleShouldBeShown() { /** * //No specific implementation. */ } } ) } } private fun showGoToSettingsDialog() { if (isAdded){ AlertDialog.Builder(requireContext()) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton( "OK" ) { _, _ -> Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${requireActivity().packageName}") ).apply { addCategory(Intent.CATEGORY_DEFAULT) resultLauncher.launch(this) } } .setNegativeButton("cancel", null) .create() .show() } } private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val data: Intent? = result.data AppLog.errorLog("intent$data") } } private fun initWebServiceCallAfterChecks() { if (NetworkUtil.isNetworkConnected(requireActivity()) && isAdded && activity != null) { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager cameraLocationVM.isLocationDisabled = !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) locationProvider?.let { handleOnLocationEnabled() } } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } @SuppressLint("MissingPermission") private fun handleOnLocationEnabled() = if (newLocation == null) { locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } else { if (NetworkUtil.isNetworkConnected(requireActivity()) && isAdded && activity != null) { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false setMyLocationOnFocus() } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } private fun showCameraLocationEditScreen() { val bundle = Bundle() bundle.putSerializable( EditCameraLocationFragment.CAMERA_DETAILS, selectedCameraObj ) bundle.putInt(EditCameraLocationFragment.SCREEN_MODE, CameraConstants.UPDATE_LOCATION) val cameraSectionBaseFragment: CameraSectionBaseFragment = parentFragment as CameraSectionBaseFragment cameraSectionBaseFragment.showCameraLocationEditScreen(bundle) } private fun removeEditLocationFragment() { (this.parentFragment as CameraSectionBaseFragment).removeEditCameraLocation() } @Subscribe(threadMode = ThreadMode.MAIN) fun onMessageEvent(event: LocationStatusChangeEvent) { if (cameraLocationVM.isLocationDisabled) { Handler(Looper.getMainLooper()).postDelayed({ if (isAdded) { try { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { checkLocationPermission() } } catch (e: Exception) { AppLog.errorLog(e.message.toString()) } } }, 1000) } } override fun onStart() { super.onStart() if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this) } requireActivity().registerReceiver( gpsReceiver, IntentFilter("android.location.PROVIDERS_CHANGED") ) } override fun onStop() { super.onStop() cameraLocationVM.isNewLocationSet = false if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this) } requireActivity().unregisterReceiver(gpsReceiver) } }
Trailcamera/CameraLocationFragment.kt
1765486511
class EditCameraLocationFragment : BaseFragment(), LocationProvider.LocationUpdateListener { private lateinit var binding: FragmentEditCameraLocationBinding private lateinit var commonToolbarBinding: LayoutCommonToolbarBinding // private lateinit var cameraLocationVM: CameraLocationViewModel private val cameraLocationVM: CameraLocationViewModel by viewModels() private var childProgressbarBinding: ProgressLayoutBinding? = null private var cameraInfo: CameraBasicInfo? = null private var isSecondTimeMapLoad = 0 private var nMap: GoogleMap? = null private var mapViewType: Int = GoogleMap.MAP_TYPE_HYBRID private var newLocationLatLong: LatLng? = null private var isMapViewTypeChanged = false private lateinit var clusterManager: ClusterManager<LocationItem> private var locationProvider: LocationProvider? = null private val gpsReceiver = GpsLocationReceiver() private var newLocation: Location? = null companion object { @JvmStatic fun newInstance(bundle: Bundle? = null) = EditCameraLocationFragment() .apply { arguments = bundle } var TAG = EditCameraLocationFragment::class.java.simpleName.toString() const val CAMERA_DETAILS = "camera_details" const val SCREEN_MODE = "screen_mode" } override fun initToolbar() { super.initToolbar() commonToolbarBinding = binding.toolbar commonToolbarBinding.ivBack.visibility = View.VISIBLE commonToolbarBinding.tvToolbarTitle.text = resources.getText(R.string.edit_camera_location) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentEditCameraLocationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isAdded && activity != null) setMapView() } private fun setMapView() { val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync(callback) } override fun init() { // initViewModel() setClickListeners() locationProvider = LocationProvider(requireContext(), this) } override fun setObservers() { setProgressObserver() setMessageObserver() setCameraSelectedObserver() postCameraSettingsObserver() setCameraLocationsObserver() } /* private fun initViewModel() { cameraLocationVM = ViewModelProvider(requireActivity()).get( CameraLocationViewModel::class.java ) }*/ @SuppressLint("MissingPermission") private val callback = OnMapReadyCallback { googleMap -> googleMap?.let { googleMap.mapType = mapViewType nMap = googleMap if (!isMapViewTypeChanged) { val camera = getCameraLocationDetails() camera?.let { val latitude = if (camera.latitude != null) camera.latitude!! else 0.0 val longitude = if (camera.longitude != null) camera.longitude!! else 0.0 var cameraLocation = LatLng(latitude, longitude) if (cameraLocationVM.isNewLocationSet) { newLocationLatLong?.let { cameraLocation = it } } else { cameraLocation = LatLng(latitude, longitude) } googleMap.animateCamera( CameraUpdateFactory.newLatLngZoom( cameraLocation, EDIT_MAP_ZOOM_LEVEL ) ) cameraInfo = camera getCameraSelected(camera) googleMap.setOnCameraMoveListener { if (isSecondTimeMapLoad == 2) { binding.lyLocationTitle.visibility = View.GONE binding.cvSwitchMapType.visibility = View.GONE } } googleMap.setOnCameraIdleListener { if (isSecondTimeMapLoad >= 2) { val newLatLng = googleMap.cameraPosition.target newLocationLatLong = newLatLng cameraLocationVM.isNewLocationSet = true cameraInfo!!.latitude = newLatLng.latitude cameraInfo!!.longitude = newLatLng.longitude if (cameraInfo!!.latitude != null && cameraInfo!!.longitude != null) { binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE binding.tvNameTitle.text = cameraInfo!!.cameraName binding.tvLocationName.text = getString(R.string.fetching_camera_location_address) getCameraSelected(cameraInfo!!) } else { binding.lyLocationTitle.visibility = View.GONE binding.cvSwitchMapType.visibility = View.GONE } } else { getCameraSelected(cameraInfo!!) } } } } else { isMapViewTypeChanged = false } } } private fun getCameraLocationDetails(): CameraBasicInfo { /** V1.0.6 fixes**/ var cameraBasicInfo = CameraBasicInfo() if (arguments?.getInt(SCREEN_MODE) == UPDATE_LOCATION) { cameraBasicInfo = arguments?.getSerializable(CAMERA_DETAILS) as CameraBasicInfo } else { val cameraSettingObj = arguments?.getSerializable(CAMERA_DETAILS) as CameraSetting cameraBasicInfo.cameraID = cameraSettingObj.cameraObj?.cameraID cameraBasicInfo.cameraName = cameraSettingObj.cameraConfiguration?.name cameraBasicInfo.active = cameraSettingObj.cameraObj?.active cameraBasicInfo.latitude = cameraSettingObj.cameraConfiguration?.latitude cameraBasicInfo.longitude = cameraSettingObj.cameraConfiguration?.longitude } if (arguments?.getInt(SCREEN_MODE) == EDIT_LOCATION || arguments?.getInt(SCREEN_MODE) == UPDATE_LOCATION) { binding.btnUpdateLocation.text = resources.getText(R.string.camera_confirm_location) } else if (arguments?.getInt(SCREEN_MODE) == CONFIRM_LOCATION) { if (cameraBasicInfo.latitude.toString() .isEmpty() || cameraBasicInfo.longitude.toString().isEmpty() ) binding.btnUpdateLocation.text = resources.getText(R.string.camera_add_location) else binding.btnUpdateLocation.text = resources.getText(R.string.camera_confirm_location) } return cameraBasicInfo } private fun getCameraSelected(selectedCamera: CameraBasicInfo) { if (isAdded && activity != null) { if (NetworkUtil.isNetworkConnected(requireActivity())) { cameraLocationVM.getCameraSelected(context, selectedCamera) } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } } private fun setProgressObserver() { cameraLocationVM.progressStatus.observe(viewLifecycleOwner, EventObserver { if (cameraLocationVM.isUpdatingLocationOperationInProgress) { if (it) { DialogUtil.showProgressDialog( requireActivity(), getString(R.string.updating_camera_location) ) } else { DialogUtil.dismissProgressDialog() } } }) } private fun setMessageObserver() { cameraLocationVM.message.observe(viewLifecycleOwner, EventObserver { if (!it.isSuccessMessage && it.messageCode != null) { if (it.showAsInLayoutMessage) { when (it.messageCode) { WebConstant.RESPONSE_EMPTY_ARRAY -> { childProgressbarBinding?.clInLayoutProgressLoading?.visibility = View.GONE } else -> { childProgressbarBinding?.inLayoutProgressBar?.visibility = View.GONE childProgressbarBinding?.clInLayoutProgressLoading?.visibility = View.VISIBLE childProgressbarBinding?.tvLoading?.text = CommonUtil.getMessageText(requireActivity(), it.messageCode) } } } else { DialogUtil.showSingleActionButtonAlert(requireActivity(), object : SingleButtonDialogCallback { override fun onConfirmationDialogPositiveButtonClicked(mDialogID: Int) { /**No specific implementation**/ } }, CommonUtil.getMessageText(requireActivity(), it.messageCode)) } } }) } private fun setCameraSelectedObserver() { cameraLocationVM.cameraAddressEditScreenLiveData.observe(viewLifecycleOwner, EventObserver { if (it == "${cameraInfo?.latitude.toString()}, ${cameraInfo?.longitude.toString()}") { ++isSecondTimeMapLoad binding.tvNameTitle.text = cameraInfo?.cameraName binding.tvLocationName.text = getString(R.string.no_valid_address_available) binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE binding.tvLatitudeValue.text = cameraInfo?.latitude.toString() binding.tvLongitudeValue.text = cameraInfo?.longitude.toString() } else { if (cameraInfo != null) { setCameraNameAndAddress(cameraInfo!!, it) } } }) } private fun postCameraSettingsObserver() { cameraLocationVM.isCameraSettingPosted.observe(this, Observer { it.let { if ((null != cameraInfo?.latitude) && (null != cameraInfo?.longitude)) { val result = Bundle().apply { putDouble("newLatitude", cameraInfo?.latitude!!) putDouble("newLongitude", cameraInfo?.longitude!!) putInt("cameraId", cameraInfo?.cameraID!!) putString("newAddress", binding.tvLocationName.text.toString()) } if (arguments?.getInt(SCREEN_MODE) == EDIT_LOCATION) { result.putString( "data", CameraSettingsConstant.CAMERA_SETTINGS_EDIT_LOCATION ) setFragmentResult( CameraSettingsConstant.RESULT_CAMERA_SETTINGS_FILTER, result ) } else if (arguments?.getInt(SCREEN_MODE) == UPDATE_LOCATION) { result.putString("data", CAMERA_EDIT_LOCATION_CONFIRM) setFragmentResult(RESULT_CAMERA_EDIT_LOCATION, result) } else { result.putString("data", CAMERA_EDIT_LOCATION_CONFIRM) setFragmentResult(RESULT_CAMERA_EDIT_LOCATION, result) } } } }) } private fun setCameraLocationsObserver() { cameraLocationVM.getAllCameraLocationInfoFromDatabase() ?.observe(this, Observer { cameraList -> if (!cameraList.isNullOrEmpty()) { if (cameraList.size > 1) { if (nMap != null) { setUpCluster(nMap!!, cameraList) } } } }) } private fun setUpCluster(map: GoogleMap, cameraList: List<CameraBasicInfo>) { map.clear() clusterManager = ClusterManager(requireActivity(), map) clusterManager.renderer = MarkerClusterRenderer( requireActivity(), map, clusterManager, true ) map.setOnCameraIdleListener(clusterManager) clusterManager.setOnClusterItemClickListener { var selectedCamera = CameraBasicInfo() for (i in cameraList.indices) { if (it.snippet.equals("Camera $i")) { selectedCamera = cameraList[i] break } } getCameraSelected(selectedCamera) false } clusterManager.setOnClusterClickListener { map.animateCamera( CameraUpdateFactory.newLatLngZoom( it.position, (floor((map.cameraPosition.zoom + 1).toDouble()).toFloat()) ), 300, null ) true } addLocations(cameraList) } private fun addLocations(cameraList: List<CameraBasicInfo>) { for (i in cameraList.indices) { if (cameraInfo?.cameraID != cameraList[i].cameraID) { val offset = i / 800.0 val lat = cameraList[i].latitude!! + offset val lon = cameraList[i].longitude!! + offset val offsetItem = LocationItem( lat, lon, cameraList[i].cameraName!!, "Camera $i" ) clusterManager.addItem(offsetItem) } } Handler(Looper.getMainLooper()).postDelayed({ if (isAdded) { mapViewType = GoogleMap.MAP_TYPE_HYBRID setMapView() } }, 2000) } private fun setCameraNameAndAddress(camera: CameraBasicInfo, addressText: String) { ++isSecondTimeMapLoad binding.tvNameTitle.text = camera.cameraName binding.tvLocationName.text = addressText binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE binding.tvLatitudeValue.text = camera.latitude.toString() binding.tvLongitudeValue.text = camera.longitude.toString() } private fun setClickListeners() { binding.btnUpdateLocation.setOnClickListener { if (arguments?.getInt(SCREEN_MODE) == UPDATE_LOCATION) { val cameraBasicInfo = arguments?.getSerializable(CAMERA_DETAILS) as CameraBasicInfo updateLocationByCoordinates(cameraBasicInfo.cameraID!!) } else { updateLocationByCameraDetails() } } binding.ivMyLocation.setOnClickListener { cameraLocationVM.isMyLocationClicked = true if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false if (checkLocationDisabled()) checkLocationPermission() else { initWebServiceCallAfterChecks() } } else { checkLocationPermission() } } binding.tvStreet.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) mapViewType = GoogleMap.MAP_TYPE_TERRAIN isMapViewTypeChanged = true setMapView() } binding.tvHybrid.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) mapViewType = GoogleMap.MAP_TYPE_HYBRID isMapViewTypeChanged = true setMapView() } binding.tvSatellite.setOnClickListener { binding.tvStreet.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvHybrid.setTextColor( ContextCompat.getColor( requireContext(), R.color.text_color_light_black_dark_white ) ) binding.tvSatellite.setTextColor( ContextCompat.getColor( requireContext(), R.color.app_orange_95_trans ) ) mapViewType = GoogleMap.MAP_TYPE_SATELLITE isMapViewTypeChanged = true setMapView() } } private fun triggerSetCameraSettingAPICall( cameraId: Int, cameraConfiguration: CameraConfigurationDTO ) { if (NetworkUtil.isNetworkConnected(requireActivity()) && isAdded && activity != null) { cameraLocationVM.isAPICallPendingDueToConnectivity = false cameraLocationVM.setCameraSettings(cameraId, cameraConfiguration) } else { cameraLocationVM.isAPICallPendingDueToConnectivity = true cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } private fun checkLocationDisabled(): Boolean { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager return !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } override fun handleNewLocation(location: Location?) { if (location != null) { newLocation = location if (cameraLocationVM.isMyLocationClicked) { cameraLocationVM.isMyLocationClicked = false setMyLocationOnFocus() } } else { locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } } private fun setMyLocationOnFocus() { if (activity!= null && isAdded && !requireActivity().isFinishing && cameraInfo != null && newLocation != null && newLocation?.latitude != null && newLocation?.longitude != null) { val myLocation = LatLng(newLocation?.latitude!!, newLocation?.longitude!!) newLocationLatLong = myLocation cameraLocationVM.isNewLocationSet = true nMap?.animateCamera( CameraUpdateFactory.newLatLngZoom( myLocation, EDIT_MAP_ZOOM_LEVEL ) ) cameraInfo!!.latitude = newLocation!!.latitude cameraInfo!!.longitude = newLocation!!.longitude binding.lyLocationTitle.visibility = View.VISIBLE binding.cvSwitchMapType.visibility = View.VISIBLE binding.tvNameTitle.text = cameraInfo!!.cameraName binding.tvLocationName.text = getString(R.string.fetching_camera_location_address) getCameraSelected(cameraInfo!!) } else { AppLog.errorLog("get last location : setMyLocationOnFocus") locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } } override fun locationUpdateTimeout() { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } override fun locationSettingError(error: String) { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } override fun locationDisabled() { AppLog.debugLog(AppConstant.NOT_YET_IMPLEMENTED) } private fun updateLocationByCoordinates(cameraId: Int) { if (NetworkUtil.isNetworkConnected(requireActivity()) && isAdded && activity != null) { cameraLocationVM.isAPICallPendingDueToConnectivity = false cameraLocationVM.setCameraLocation( cameraId, UpdateLocationRequestDTO( latitude = cameraInfo!!.latitude!!, longitude = cameraInfo!!.longitude!! ) ) } else { cameraLocationVM.isAPICallPendingDueToConnectivity = true cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } private fun updateLocationByCameraDetails() { val cameraSettingObj = arguments?.getSerializable(CAMERA_DETAILS) as CameraSetting cameraSettingObj.cameraConfiguration?.let {config -> if (cameraSettingObj.cameraConfiguration != null && cameraSettingObj.cameraObj != null && cameraSettingObj.cameraObj?.cameraID != null) { triggerSetCameraSettingAPICall( cameraSettingObj.cameraObj?.cameraID!!, CameraConfigurationDTO( serialnumber = config.serialnumber, captureCount = config.captureCount, captureMode = config.captureMode!!, embedGPS = config.embedGPS, fieldScan = config.fieldScan, flashMode = config.flashMode, imageFormat = config.imageFormat, imageResolution = config.imageResolution, latitude = cameraInfo!!.latitude!!, ledIntensity = config.ledIntensity, longitude = cameraInfo!!.longitude!!, movieLength = config.movieLength, movieResolution = config.movieResolution, name = if(config.name.isNullOrEmpty()) "" else config.name!!, overwrite = config.overwrite, pirDelay = config.pirDelay, pirMode = config.pirMode, pirSensitivity = config.pirSensitivity!!, pirTimes = PirTimesDTO( config.pirTimes?.mF, config.pirTimes?.sAT, config.pirTimes?.sUN ), reportInterval = config.reportInterval, scan1End = config.scan1End!!, scan1Start = config.scan1Start!!, scan2End = config.scan2End!!, scan2Interval = config.scan2Interval!!, scan2Start = config.scan2Start!!, scanInterval = config.scanInterval, // sendsize=config. showTimestamp = config.showTimestamp, shutterSpeed = config.shutterSpeed, trackingMode = config.trackingMode, wirelessEnabled = config.wirelessEnabled, workMode = config.workMode ) ) } } } @SuppressLint("MissingPermission") private fun checkLocationPermission() { if (PermissionUtil().checkIfPermissionGranted( context, Manifest.permission.ACCESS_FINE_LOCATION ) ) { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false initWebServiceCallAfterChecks() } else { PermissionUtil().requestPermission( context, Manifest.permission.ACCESS_FINE_LOCATION, object : PermissionResultListener { override fun onPermissionGranted() { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false initWebServiceCallAfterChecks() } override fun onPermissionDenied() { if (cameraLocationVM.isMyLocationClicked) showGoToSettingsDialog() cameraLocationVM.isLocationDisabled = true } override fun onPermissionRationaleShouldBeShown() { /** * //No specific implementation. */ } } ) } } private fun showGoToSettingsDialog() { if (isAdded) { AlertDialog.Builder(requireContext()) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton( "OK" ) { _, _ -> Intent( ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${requireActivity().packageName}") ).apply { addCategory(Intent.CATEGORY_DEFAULT) resultLauncher.launch(this) } } .setNegativeButton("cancel", null) .create() .show() } } private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val data: Intent? = result.data AppLog.errorLog("intent$data") } } private fun initWebServiceCallAfterChecks() { if (NetworkUtil.isNetworkConnected(requireActivity()) && isAdded && activity != null) { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager cameraLocationVM.isLocationDisabled = !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) locationProvider?.let { handleOnLocationEnabled() } } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } @SuppressLint("MissingPermission") private fun handleOnLocationEnabled() = if (newLocation == null) { locationProvider?.getSingleLocationUpdate(checkIfLastLocationAvailable = true) } else { if (isAdded && activity != null) { if (NetworkUtil.isNetworkConnected(requireActivity())) { //nMap?.isMyLocationEnabled = true //nMap?.uiSettings?.isMyLocationButtonEnabled = false setMyLocationOnFocus() } else { cameraLocationVM.setMessage( false, WebConstant.WARNING_NO_NETWORK, showAsInLayoutMessage = true ) } } else { } } @Subscribe(threadMode = ThreadMode.MAIN) fun onMessageEvent(event: LocationStatusChangeEvent) { if (cameraLocationVM.isLocationDisabled) { Handler(Looper.getMainLooper()).postDelayed({ if (isAdded) { try { val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { checkLocationPermission() } } catch (e: Exception) { AppLog.errorLog(e.message.toString()) } } }, 1000) } } override fun onStart() { super.onStart() if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this) } requireActivity().registerReceiver( gpsReceiver, IntentFilter("android.location.PROVIDERS_CHANGED") ) } override fun onStop() { super.onStop() cameraLocationVM.isNewLocationSet = false if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this) } requireActivity().unregisterReceiver(gpsReceiver) } }
Trailcamera/EditCameraLocationFragment.kt
3649317833
import com.kslides.* import com.pambrose.srcref.Api.srcrefUrl import kotlinx.html.* fun main() { val slides = "src/main/kotlin/Slides.kt" fun srcrefLink(token: String, escapeHtml4: Boolean = false) = srcrefUrl( account = "kslides", repo = "kslides-template", path = slides, beginRegex = "\\s+// $token begin", beginOffset = 1, endRegex = "\\s+// $token end", endOffset = -1, escapeHtml4 = escapeHtml4, ) kslides { output { // Write the presentation's html files to /docs for GitHub Pages or netlify.com enableFileSystem = true // Run locally or on Heroku enableHttp = true } // CSS values assigned here are applied to all the presentations css += """ #githubCorner path { fill: #258BD2; } """ presentationConfig { history = true transition = Transition.SLIDE transitionSpeed = Speed.SLOW topLeftHref = "https://github.com/kslides/kslides-template/" // Assign to "" to turn this off topLeftTitle = "View presentation source on Github" topRightHref = "/" // Assign to "" to turn this off topRightTitle = "Go to 1st Slide" topRightText = "🏠" enableMenu = true theme = PresentationTheme.SOLARIZED slideNumber = "c/t" menuConfig { numbers = true } copyCodeConfig { timeout = 2000 copy = "Copy" copied = "Copied!" } slideConfig { // Assign slide config defaults for all presentations // backgroundColor = "blue" } } presentation { css += """ #ghsrc { font-size: 30px; text-decoration: underline; } img[alt=revealjs-image] { width: 1000px; } """ presentationConfig { transition = Transition.CONCAVE slideConfig { // Assign slide config defaults for all slides in this presentation //backgroundColor = "red" } } markdownSlide { slideConfig { transition = Transition.ZOOM } content { """ # Markdown Slide ## πŸ’ Press ESC to see presentation overview. """ } } htmlSlide { content { """ <h1>An HTML Slide 🐦</h1> <p>This is some text</p> """ } } dslSlide { content { h1 { +"A DSL Slide 🐦" } p { +"This is some text" } } } verticalSlides { // code1 begin markdownSlide { val src = "kslides-examples/src/main/kotlin/content/HelloWorldK.kt" content { """ ## Code with a markdownSlide ```kotlin [1,5|2,4|3] ${include(githubRawUrl("kslides", "kslides", src), "[3-7]")} ``` """ } } // code1 end markdownSlide { content { """ ## Slide Definition ```kotlin [] ${include(slides, beginToken = "code1 begin", endToken = "code1 end")} ``` <a id="ghsrc" href="${srcrefLink("code1", true)}" target="_blank">GitHub Source</a> """ } } } verticalSlides { // code2 begin dslSlide { val src = "kslides-examples/src/main/kotlin/content/HelloWorldK.kt" val url = githubRawUrl("kslides", "kslides", src) content { h2 { +"Code with a dslSlide" } // Display lines 3-7 of the url content and highlight lines 1 and 5, 2 and 4, and finally 3 codeSnippet { language = "kotlin" highlightPattern = "[1,5|2,4|3]" +include(url, "[3-7]") } } } // code2 end dslSlide { content { h2 { +"Slide Definition" } codeSnippet { language = "kotlin" +include(slides, beginToken = "code2 begin", endToken = "code2 end") } a { id = "ghsrc" href = srcrefLink("code2") target = "_blank" +"GitHub Source" } } } } verticalSlides { // code3 begin for (lines in "[8-12|3-12|2-13|]".toLinePatterns()) { dslSlide { autoAnimate = true slideConfig { transition = Transition.NONE } content { h2 { +"Animated Code without Line Numbers" } val file = "src/main/resources/json-example.json" codeSnippet { dataId = "code-animation" language = "json" highlightPattern = "none" +include(file, linePattern = lines) } } } } // code3 end markdownSlide { content { """ ## Slide Definition ```kotlin [] ${include(slides, beginToken = "code3 begin", endToken = "code3 end")} ``` <a id="ghsrc" href="${srcrefLink("code3", true)}" target="_blank">GitHub Source</a> """ } } } verticalSlides { // code4 begin for (lines in "[8-12|3-12|2-13|]".toLinePatterns().zip(listOf(3, 3, 2, 1))) { dslSlide { autoAnimate = true slideConfig { transition = Transition.NONE } content { h2 { +"Animated Code with Line Numbers" } val file = "src/main/resources/json-example.json" codeSnippet { dataId = "code-animation" language = "json" lineOffSet = lines.second +include(file, linePattern = lines.first) } } } } // code4 end markdownSlide { content { """ ## Slide Definition ```kotlin [] ${include(slides, beginToken = "code4 begin", endToken = "code4 end")} ``` <a id="ghsrc" href="${srcrefLink("code4", true)}" target="_blank">GitHub Source</a> """ } } } verticalSlides { // image begin markdownSlide { // Image size is controlled by css above content { """ ## Images ![revealjs-image](images/revealjs.png) """ } } // image end markdownSlide { content { """ ## Slide Definition ```kotlin [] ${include(slides, beginToken = "image begin", endToken = "image end")} ``` <a id="ghsrc" href="${srcrefLink("image", true)}" target="_blank">GitHub Source</a> """ } } } verticalSlides { // others begin markdownSlide { id = "otherslides" content { """ ## Other Presentations Defined In Slides.kt <span style="text-align: left; text-indent: 25%;"> [🐦 greattalk1/ Slides](/greattalk1) [🐦 greattalk1/other.html Slides](/greattalk1/other.html) [🐦 greattalk2.html Slides](/greattalk2.html) </span> """ } } // others end markdownSlide { content { """ ## Slide Definition ```kotlin ${include(slides, beginToken = "others begin", endToken = "others end")} ``` <a id="ghsrc" href="${srcrefLink("others", true)}" target="_blank">GitHub Source</a> """ } } } } presentation { path = "greattalk1" presentationConfig { topRightHref = "/#/otherslides" topRightTitle = "Go back to main presentation" topRightText = "πŸ”™" } dslSlide { content { h2 { +"greattalk1/index.html Slides" } } } } presentation { path = "greattalk1/other.html" presentationConfig { topRightHref = "/#/otherslides" topRightTitle = "Go back to main presentation" topRightText = "πŸ”™" } dslSlide { content { h2 { +"greattalk1/other.html slides" } } } } presentation { path = "greattalk2.html" presentationConfig { topRightHref = "/#/otherslides" topRightTitle = "Go back to main presentation" topRightText = "πŸ”™" } dslSlide { content { h2 { +"greattalk2.html slides" } } } } } }
aoc-talk/src/main/kotlin/Slides.kt
3457627833
package pl.slaszu.unit.analizer import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.domain.stockanalyzer.HighestPriceSinceFewDays import pl.slaszu.stockanalyzer.shared.getResourceAsText class HighestPriceSinceFewDaysTest { @Test fun `price change more then x percent works`() { val priceList = this.getPriceList("10days_highest_price_test.json") var logic = HighestPriceSinceFewDays(30, 10) var signal = logic.getSignal(priceList) println(signal) assertEquals(6.75f, signal?.data?.get("lastPrice")) assertEquals(5.95f, signal?.data?.get("maxPrice")) logic = HighestPriceSinceFewDays(30, 20) signal = logic.getSignal(priceList) assertEquals(null, signal) } private fun getPriceList(file: String): Array<StockPriceDto> { val resourceAsText = getResourceAsText("/fixtures/$file") val objectMapper = jacksonObjectMapper().findAndRegisterModules() return objectMapper.readValue(resourceAsText, Array<StockPriceDto>::class.java) } }
stockanalyzer/src/test/kotlin/pl/slaszu/unit/analizer/HighestPriceSinceFewDaysTest.kt
2394967164
package pl.slaszu.unit.analizer import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.domain.stockanalyzer.HighestPriceFluctuationsSinceFewDays import pl.slaszu.stockanalyzer.shared.getResourceAsText class HighestPriceFluctuationsSinceFewDaysTest { @Test fun `price change more then x percent works`() { val priceList = this.getPriceList("10days_no_empty.json") var logic = HighestPriceFluctuationsSinceFewDays(30, 10) var signal = logic.getSignal(priceList) Assertions.assertEquals(20, signal?.data?.get("calculatedPercent")?.toInt()) logic = HighestPriceFluctuationsSinceFewDays(30, 11) signal = logic.getSignal(priceList) Assertions.assertEquals(null, signal) } @Test fun `price change more then y percent works with empty days`() { val priceList = this.getPriceList("10days_some_empty.json") var logic = HighestPriceFluctuationsSinceFewDays(30, 2) var signal = logic.getSignal(priceList) Assertions.assertEquals(17.39f, signal?.data?.get("calculatedPercent")?.toFloat()) } private fun getPriceList(file: String): Array<StockPriceDto> { val resourceAsText = getResourceAsText("/fixtures/$file") val objectMapper = jacksonObjectMapper().findAndRegisterModules() return objectMapper.readValue(resourceAsText, Array<StockPriceDto>::class.java) } }
stockanalyzer/src/test/kotlin/pl/slaszu/unit/analizer/HighestPriceFluctuationsSinceFewDaysTest.kt
1794020420
package pl.slaszu.integration.config import org.springframework.context.annotation.Configuration import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.testcontainers.containers.MongoDBContainer import org.testcontainers.junit.jupiter.Container @Configuration @EnableMongoRepositories class MongoDBTestContainerConfig { @Container val mongoDBContainer: MongoDBContainer = MongoDBContainer("mongo:latest") .withExposedPorts(27017) init { mongoDBContainer.start() val mappedPort = mongoDBContainer.getMappedPort(27017) System.setProperty("mongodb.container.port", mappedPort.toString()) } }
stockanalyzer/src/test/kotlin/pl/slaszu/integration/config/MongoDBTestContainerConfig.kt
1798389844
package pl.slaszu.integration import kotlinx.datetime.LocalDateTime import kotlinx.datetime.toJavaLocalDateTime import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.testcontainers.junit.jupiter.Testcontainers import pl.slaszu.integration.config.MongoDBTestContainerConfig import pl.slaszu.stockanalyzer.StockanalyzerApplication import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import java.util.stream.Stream import java.time.LocalDateTime as LocalDateTimeJava @DataMongoTest @Testcontainers @ContextConfiguration(classes = [MongoDBTestContainerConfig::class, StockanalyzerApplication::class]) @ActiveProfiles("test") class AlertRepositoryTests(@Autowired val alertRepo: AlertRepository) { @AfterEach fun del_fixtures() { this.alertRepo.deleteAll() } @BeforeEach fun insert_fixtures() { this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.3f, emptyList(), "", LocalDateTime.parse("2023-01-01T12:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.0f, emptyList(), "", LocalDateTime.parse("2023-01-02T12:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.1f, emptyList(), "", LocalDateTime.parse("2023-01-03T12:00:00").toJavaLocalDateTime(), true ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.1f, emptyList(), "", LocalDateTime.parse("2023-01-03T12:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.2f, emptyList(), "", LocalDateTime.parse("2023-01-03T13:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.3f, emptyList(), "", LocalDateTime.parse("2023-01-03T14:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.3f, emptyList(), "", LocalDateTime.parse("2023-01-06T12:00:00").toJavaLocalDateTime() ) ) this.alertRepo.save( AlertModel( "XYZ", "Some Name", 5.3f, emptyList(), "", LocalDateTime.parse("2023-01-07T12:00:00").toJavaLocalDateTime() ) ) } @Test fun testGetAll() { val findAll = alertRepo.findAll() Assertions.assertEquals(8, findAll.size) } @ParameterizedTest @MethodSource("getDatesAfter") fun testDatesAfter(date: LocalDateTimeJava, expect: Int) { // check all var alertModels = alertRepo.findByDateAfterAndCloseIsFalse(date) Assertions.assertEquals(expect, alertModels.size) } @ParameterizedTest @MethodSource("getDatesBefore") fun testDatesBefore(date: LocalDateTimeJava, expect: Int) { // check all var alertModels = alertRepo.findAlertsActiveBeforeThatDate(date) Assertions.assertEquals(expect, alertModels.size) } @Test fun testCloseAll() { val date = LocalDateTimeJava.of(2023, 1, 3, 11, 59, 0) var alertModels = alertRepo.findByDateAfterAndCloseIsFalse(date) // close all found alertModels.forEach { val copy = it.copy(close = true) alertRepo.save(copy) } // get again not close after date val alertModelsAfter = alertRepo.findByDateAfterAndCloseIsFalse(date) Assertions.assertEquals(0, alertModelsAfter.size) } companion object { @JvmStatic fun getDatesBefore(): Stream<Arguments> { return listOf( Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 11, 59, 0), 2 ), Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 12, 0, 0), 2 ), Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 12, 59, 0), 3 ) ).stream() } @JvmStatic fun getDatesAfter(): Stream<Arguments> { return listOf( Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 11, 59, 0), 5 ), Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 12, 0, 0), 4 ), Arguments.of( LocalDateTimeJava.of(2023, 1, 3, 12, 59, 0), 4 ) ).stream() } } }
stockanalyzer/src/test/kotlin/pl/slaszu/integration/AlertRepositoryTests.kt
3985792228
package pl.slaszu.integration import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.testcontainers.junit.jupiter.Testcontainers import pl.slaszu.integration.config.MongoDBTestContainerConfig import pl.slaszu.stockanalyzer.StockanalyzerApplication @DataMongoTest @Testcontainers @ContextConfiguration(classes = [MongoDBTestContainerConfig::class, StockanalyzerApplication::class]) @ActiveProfiles("test") class StockanalyzerApplicationTests { @Test fun contextLoads() { } }
stockanalyzer/src/test/kotlin/pl/slaszu/integration/StockanalyzerApplicationTests.kt
4121490292
package pl.slaszu.integration import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.testcontainers.junit.jupiter.Testcontainers import pl.slaszu.integration.config.MongoDBTestContainerConfig import pl.slaszu.stockanalyzer.StockanalyzerApplication import pl.slaszu.stockanalyzer.domain.alert.CloseAlertService import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import java.time.LocalDateTime @Testcontainers @ContextConfiguration(classes = [MongoDBTestContainerConfig::class, StockanalyzerApplication::class]) @SpringBootTest @ActiveProfiles("test") class CloseAlertServiceTests( @Autowired val alertRepo: AlertRepository, @Autowired val closeAlertRepo: CloseAlertRepository, @Autowired val closeAlertService: CloseAlertService ) { private var alertSaved: AlertModel? = null @AfterEach fun del_fixtures() { this.closeAlertRepo.deleteAll() this.alertRepo.deleteAll() } @BeforeEach fun insert_fixtures() { val alert = AlertModel("PLW", "PLAYWAY", 286.45f, emptyList(), "fakeTweetId") this.alertSaved = this.alertRepo.save(alert) this.closeAlertRepo.save( CloseAlertModel( this.alertSaved!!, "tweetIdx33", 5f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( this.alertSaved!!, "tweetIdx22", -3f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( this.alertSaved!!, "tweetIdx11", -3f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( this.alertSaved!!, "tweetIdx11", -3f, 3 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "Y", "name y", 3.5f, emptyList(), "tweetId", LocalDateTime.now(), true ), "tweetIdx11", -3f, 2 ) ) } @Test fun testGetAll() { val findAll = closeAlertRepo.findAll() Assertions.assertEquals(5, findAll.size) val findByDaysAfterAndAlertClose = closeAlertRepo.findByDaysAfterAndAlertClose(2, false) Assertions.assertEquals(3, findByDaysAfterAndAlertClose.size) val findByAlertId = closeAlertRepo.findByAlertId(this.alertSaved?.id!!) Assertions.assertEquals(4, findByAlertId.size) val findByCloseDateAfterAndCloseIsFalse = alertRepo.findAlertsClosedAfterThatDate(LocalDateTime.now().minusDays(1)) Assertions.assertEquals(0, findByCloseDateAfterAndCloseIsFalse.size) this.closeAlertService.closeAlert(this.alertSaved!!) val findByAlertIdAfter = closeAlertRepo.findByAlertId(this.alertSaved?.id!!) Assertions.assertEquals(4, findByAlertIdAfter.size) findByAlertIdAfter.forEach { Assumptions.assumeTrue(it.alert.close) } val findById = alertRepo.findById(this.alertSaved?.id!!) Assertions.assertTrue(findById.get().close) val findByCloseDateAfterAndCloseIsFalseAfter = alertRepo.findAlertsClosedAfterThatDate(LocalDateTime.now().minusDays(1)) Assertions.assertEquals(1, findByCloseDateAfterAndCloseIsFalseAfter.size) val findByCloseDateAfterAndCloseIsFalseAfterNow = alertRepo.findAlertsClosedAfterThatDate(LocalDateTime.now()) Assertions.assertEquals(0, findByCloseDateAfterAndCloseIsFalseAfterNow.size) } }
stockanalyzer/src/test/kotlin/pl/slaszu/integration/CloseAlertServiceTests.kt
4189258596
package pl.slaszu.integration import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.testcontainers.junit.jupiter.Testcontainers import pl.slaszu.integration.config.MongoDBTestContainerConfig import pl.slaszu.stockanalyzer.StockanalyzerApplication import pl.slaszu.stockanalyzer.domain.alert.CloseAlertService import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import java.time.LocalDateTime import java.util.stream.Stream @DataMongoTest @Testcontainers @ContextConfiguration(classes = [MongoDBTestContainerConfig::class, StockanalyzerApplication::class]) @ActiveProfiles("test") class CloseAlertRepositoryTests( @Autowired val closeAlertRepo: CloseAlertRepository ) { @AfterEach fun del_fixtures() { this.closeAlertRepo.deleteAll() } fun getAlertId(): String { return "65eb0befc864193a40a3d007" } @BeforeEach fun insert_fixtures() { this.closeAlertRepo.save( CloseAlertModel( AlertModel( "X", "name", 5f, emptyList(), "tweetId", LocalDateTime.now(), true, null, getAlertId() ), "tweetIdx33", 5f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "Y", "name y", 3.5f, emptyList(), "tweetId", LocalDateTime.now(), true, null, getAlertId() ), "tweetIdx22", -3f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "Y", "name y", 3.5f, emptyList(), "tweetId", LocalDateTime.now(), true, null, getAlertId() ), "tweetIdx11", -3f, 2 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "X", "name", 5f, emptyList(), "tweetId", LocalDateTime.now(), true ), "tweetIdx", 5f, 7 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "Y", "name y", 3.5f, emptyList(), "tweetId", LocalDateTime.now(), true ), "tweetIdx", -3f, 7 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "X", "name", 5f, emptyList(), "tweetId" ), "tweetIdx", 5f, 7 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "Y", "name y", 3.5f, emptyList(), "tweetId" ), "tweetIdx", -3f, 7 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "X", "name", 4f, emptyList(), "tweetId" ), "tweetIdx", 2.5f, 7 ) ) this.closeAlertRepo.save( CloseAlertModel( AlertModel( "X", "name", 4.8f, emptyList(), "tweetId" ), "tweetIdx", 1f, 14 ) ) } @Test fun testGetAll() { val findAll = closeAlertRepo.findAll() Assertions.assertEquals(9, findAll.size) } @ParameterizedTest @MethodSource("getData") fun testData(stockCode: String, daysAfter: Int, expect: Int) { // check all val closeAlertModels = closeAlertRepo.findByStockCodeAndDaysAfter(stockCode, daysAfter) Assertions.assertEquals(expect, closeAlertModels.size) } @Test fun testDaysAfterAndAlertCloseIsFalse() { val findByDaysAfter = closeAlertRepo.findByDaysAfterAndAlertClose(7) Assertions.assertEquals(3, findByDaysAfter.size) } @Test fun testDaysAfterAndAlertCloseIsTrue() { val findByDaysAfter = closeAlertRepo.findByDaysAfterAndAlertClose(7, true) Assertions.assertEquals(2, findByDaysAfter.size) } @Test fun testFindByAlertId() { val findByDaysAfter = closeAlertRepo.findByAlertId(getAlertId()) Assertions.assertEquals(3, findByDaysAfter.size) } companion object { @JvmStatic fun getData(): Stream<Arguments> { return listOf( Arguments.of( "X", 7, 2 ), Arguments.of( "Y", 7, 1 ), Arguments.of( "X", 23, 0 ), ).stream() } } }
stockanalyzer/src/test/kotlin/pl/slaszu/integration/CloseAlertRepositoryTests.kt
647455458
package pl.slaszu.stockanalyzer.shared import java.net.URI import java.time.LocalDate import java.time.ZoneId import java.util.* import kotlin.math.abs import kotlin.math.pow import kotlin.math.roundToInt fun getResourceAsText(path: String): String? = object {}.javaClass.getResource(path)?.readText() fun Float.roundTo(numFractionDigits: Int): Float { val factor = 10.0.pow(numFractionDigits.toDouble()) return ((this * factor).roundToInt() / factor).toFloat() } fun calcPercent(price: Float, price2: Float): Float { if (price.equals(0f) || price2.equals(0f)) { return 0f } return abs((price - price2) / price * 100) } fun calcSellPrice(buyPrice: Float, resultPercent: Float): Float { return buyPrice + (buyPrice * resultPercent / 100) } fun Date.toLocalDate(): LocalDate { return this.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); } fun LocalDate.toDate(): Date { return Date.from(this.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()) } fun String.toUri(path: String): URI { return URI.create(this.plus(path)) }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/shared/utils.kt
944283311
package pl.slaszu.stockanalyzer.userinterface import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.context.annotation.Profile import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.application.CloseAlerts import pl.slaszu.stockanalyzer.application.CreateAlerts import pl.slaszu.stockanalyzer.application.CreateReport val logger = KotlinLogging.logger { } @Service @Profile("prod") class Scheduler( val createAlerts: CreateAlerts, val closeAlerts: CloseAlerts, val createReport: CreateReport ) { @Scheduled(cron = "0 * * * * *") @Profile("default") fun runTest() { logger.info { "Scheduler:runTest do nothing" } } @Scheduled(cron = "30 0,15,30,45 9-17 * * MON-FRI") fun runCreateAlert() { logger.info { "Scheduler:runCreateAlert" } this.createAlerts.run() } @Scheduled(cron = "45 5,20,35,50 9-17 * * MON-FRI") fun runCheckAlerts() { logger.info { "Scheduler:runCheckAlerts 7 andClose=false" } this.closeAlerts.runForDaysAfter(7) } @Scheduled(cron = "55 10,25,40,55 9-17 * * MON-FRI") fun runCheckAndCloseAlerts() { logger.info { "Scheduler:runCheckAndCloseAlerts 14 andClose=true" } this.closeAlerts.runForDaysAfter(14, true) } @Scheduled(cron = "0 0 18 * * SUN") fun runCreateWeekReport() { logger.info { "Scheduler:runCreateWeekReport 7" } this.createReport.runForDaysAfter(7) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/userinterface/scheduler.kt
438022955
package pl.slaszu.stockanalyzer.application import io.github.oshai.kotlinlogging.KLogger import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.alert.CloseAlertService import pl.slaszu.stockanalyzer.domain.chart.ChartPoint import pl.slaszu.stockanalyzer.domain.chart.ChartProvider import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import pl.slaszu.stockanalyzer.domain.publisher.Publisher import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.domain.stock.StockProvider import pl.slaszu.stockanalyzer.shared.roundTo import java.time.LocalDateTime @Service class CloseAlerts( private val stockProvider: StockProvider, private val alertRepo: AlertRepository, private val closeAlertRepo: CloseAlertRepository, private val chartProvider: ChartProvider, private val publisher: Publisher, private val closeAlertService: CloseAlertService, private val logger: KLogger = KotlinLogging.logger { } ) { fun runForDaysAfter(daysAfter: Int, andClose: Boolean = false) { val date = LocalDateTime.now().minusDays(daysAfter.toLong()) val alerts = this.alertRepo.findAlertsActiveBeforeThatDate(date) this.logger.info { "Get alert before $daysAfter days [date : ${date.toString()}]" } this.logger.info { "Alerts found qty : ${alerts.size}" } val findByDaysAfter = this.closeAlertRepo.findByDaysAfterAndAlertClose(daysAfter) alerts.filter { val find = findByDaysAfter.find { closeAlertModel -> closeAlertModel.alert.stockCode == it.stockCode } find == null }.also { this.logger.info { "Alerts to check qty : ${it.size}" } }.forEach { alert -> // get stock price now val stockPriceList = this.stockProvider.getStockPriceList(alert.stockCode) val first = stockPriceList.first() this.logger.info { "Stock ${alert.stockCode} had price ${alert.price} " + "and now has price ${first.price} [${first.updatedAt.toString()}]" } if (first.volume == 0) { this.logger.debug { "Skip this stock" } return@forEach // continue } val priceChangeInPercent = this.getPriceChangePercent(alert.price, first.price) val tweetId = this.publishCloseAndGetId(alert, stockPriceList, daysAfter) // add CloseAlertModel this.closeAlertRepo.save( CloseAlertModel( alert, tweetId, priceChangeInPercent, daysAfter, first.price ) ) if (andClose) { this.closeAlertService.closeAlert(alert) } } } private fun getPriceChangePercent(buy: Float, sell: Float): Float { return (((100 * sell) / buy) - 100).roundTo(2) } private fun publishCloseAndGetId(alert: AlertModel, priceList: Array<StockPriceDto>, daysAfter: Int): String { val first = priceList.first() val closePrice = first.price val priceChangeInPercent = this.getPriceChangePercent(alert.price, first.price) val alertLabel = "SELL ${alert.stockCode} $closePrice PLN" // find priceListElement for alert by date val priceListForAlert = priceList.find { it.date == alert.date.toLocalDate() } var buyPoint: ChartPoint? = null; if (priceListForAlert != null) { buyPoint = ChartPoint(priceListForAlert, alert.price, "BUY ${alert.stockCode} ${alert.price} PLN") } // get chart png val pngByteArray = this.chartProvider.getPngByteArray( alert.stockCode, priceList, buyPoint, // buy point ChartPoint(priceList.first(), closePrice, alertLabel) // close point ) // tweet alert return this.publisher.publish( pngByteArray, "$alertLabel (after $daysAfter days) | result: $priceChangeInPercent %", "#${alert.stockCode} #${alert.stockName} " + "#gpwApiSignals\nhttps://pl.tradingview.com/symbols/GPW-${alert.stockCode}/", alert.tweetId ) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/application/close_alerts.kt
2062249759
package pl.slaszu.stockanalyzer.application import io.github.oshai.kotlinlogging.KLogger import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import pl.slaszu.stockanalyzer.domain.chart.ChartPoint import pl.slaszu.stockanalyzer.domain.chart.ChartProvider import pl.slaszu.stockanalyzer.domain.publisher.Publisher import pl.slaszu.stockanalyzer.domain.stock.StockDto import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.domain.stock.StockProvider import pl.slaszu.stockanalyzer.domain.stockanalyzer.SignalProvider import pl.slaszu.stockanalyzer.domain.stockanalyzer.SignalsChecker import pl.slaszu.stockanalyzer.shared.roundTo import java.time.LocalDateTime @Service class CreateAlerts( private val stockProvider: StockProvider, private val signalProvider: SignalProvider, private val alertRepo: AlertRepository, private val chartProvider: ChartProvider, private val publisher: Publisher, private val logger: KLogger = KotlinLogging.logger { } ) { fun run() { val stockCodeList = this.stockProvider.getStockCodeList().also { logger.debug { "StockCodeList has ${it.size} qty" } } val date = LocalDateTime.now() val activeAlerts = this.alertRepo.findAlertsActiveBeforeThatDate(date) stockCodeList.filter { it.code != null // remove if code is null }.filter { val find = activeAlerts.find { alert -> alert.stockCode == it.code } find == null// remove if active alert for code exists }.also { logger.debug { "StockCodeList has ${it.size} qty after filter" } }.forEach { val stockPriceList = this.stockProvider.getStockPriceList(it.code!!) val signals = this.signalProvider.getSignals(stockPriceList) val signalsChecker = SignalsChecker(signals) if (signalsChecker.hasAll()) { logger.info { "Code ${it.code} has all signals \n ${signals.contentToString()}}" } // todo uncomment val publishedId = this.publishAlertAndGetId(it, stockPriceList) val alertModel = AlertModel( it.code, it.name, stockPriceList.first().price, signals.map { it.type }, publishedId ) alertRepo.save(alertModel) logger.info { "Saved alert: $alertModel" } } } } private fun publishAlertAndGetId(stock: StockDto, priceList: Array<StockPriceDto>): String { val buyPrice = priceList.first().price.roundTo(2) val alertLabel = "BUY ${stock.code} $buyPrice PLN" // get chart png val pngByteArray = this.chartProvider.getPngByteArray( "${stock.code}", priceList, ChartPoint(priceList.first(), buyPrice, alertLabel) ) // tweet alert return this.publisher.publish( pngByteArray, alertLabel, "#${stock.code} #${stock.name} #gpwApiSignals\nhttps://pl.tradingview.com/symbols/GPW-${stock.code}/" ) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/application/create_alerts.kt
1933390109
package pl.slaszu.stockanalyzer.application import io.github.oshai.kotlinlogging.KLogger import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import pl.slaszu.stockanalyzer.domain.publisher.Publisher import pl.slaszu.stockanalyzer.domain.report.ReportProvider import pl.slaszu.stockanalyzer.shared.roundTo import java.time.LocalDateTime @Service class CreateReport( private val closeAlertModelRepo: CloseAlertRepository, private val reportProvider: ReportProvider, private val publisher: Publisher, private val logger: KLogger = KotlinLogging.logger { } ) { fun runForDaysAfter(daysAfter: Int) { val date = LocalDateTime.now().minusDays(daysAfter.toLong()) val closedAlertModelList = this.closeAlertModelRepo.findCloseAlertsAfterDate(date) this.logger.debug { "Found ${closedAlertModelList.size} alert closed for date $date" } if (closedAlertModelList.isEmpty()) { return } val summaryPercent = this.getSummaryPercent(closedAlertModelList) val html = this.reportProvider.getHtml(closedAlertModelList, mapOf( "days" to daysAfter.toString(), "summary" to summaryPercent.toString() )) val pngByteArray = this.reportProvider.getPngByteArray(html) this.publisher.publish( pngByteArray, "Podsumowanie (last $daysAfter days)\n" + "Wynik $summaryPercent %", "${this.getTopDesc(closedAlertModelList)}\n" + "${this.getLastDesc(closedAlertModelList)}\n" + "#gpwApiSignals" ) } private fun getSummaryPercent(closeAlertsList: List<CloseAlertModel>): Float { return closeAlertsList.sumOf { it.resultPercent.toDouble() }.toFloat().roundTo(2) } private fun getTopDesc(closeAlertsList: List<CloseAlertModel>): String { // sortuj malejaco // tylko dodatnie zwoty // max 3 val res = closeAlertsList.filter { it.resultPercent > 0 }.sortedByDescending { it.resultPercent }.take(3) if (res.isEmpty()) { return ""; } return "\uD83D\uDFE9Najlepsze:\n" + res.joinToString("\n") { "${it.alert.stockName} [#${it.alert.stockCode}] +${it.resultPercent} %" } } private fun getLastDesc(closeAlertsList: List<CloseAlertModel>): String { // sortuj malejaco // tylko ujemne zwroty // max 3 val res = closeAlertsList.filter { it.resultPercent < 0 }.sortedByDescending { it.resultPercent }.takeLast(3) if (res.isEmpty()) { return ""; } return "\uD83D\uDFE5Najgorsze:\n" + res.joinToString("\n") { "${it.alert.stockName} [#${it.alert.stockCode}] ${it.resultPercent} %" } } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/application/create_report.kt
1135015444
package pl.slaszu.stockanalyzer.infrastructure.publisher import com.fasterxml.jackson.databind.ObjectMapper import io.github.oshai.kotlinlogging.KotlinLogging import io.github.redouane59.twitter.TwitterClient import io.github.redouane59.twitter.signature.TwitterCredentials import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @ConfigurationProperties(prefix = "twitter-config") data class TwitterConfig( val apiKey: String, val apiSecretKey: String, val accessToken: String, val accessTokenSecret: String ) @Configuration("twitterBeans") class Beans { @Bean fun getTwitterClient(objMapper: ObjectMapper, twitterConfig: TwitterConfig): TwitterClient { val logger = KotlinLogging.logger { } logger.debug { twitterConfig.toString() } val credentials = TwitterCredentials.builder() .apiKey(twitterConfig.apiKey) .accessToken(twitterConfig.accessToken) .apiSecretKey(twitterConfig.apiSecretKey) .accessTokenSecret(twitterConfig.accessTokenSecret) .build() return TwitterClient(credentials) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/publisher/config.kt
211465172
package pl.slaszu.stockanalyzer.infrastructure.publisher import io.github.oshai.kotlinlogging.KLogger import io.github.oshai.kotlinlogging.KotlinLogging import io.github.redouane59.twitter.TwitterClient import io.github.redouane59.twitter.dto.tweet.MediaCategory import io.github.redouane59.twitter.dto.tweet.TweetParameters import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.publisher.Publisher @Service @Profile("prod") class TwitterPublisher( val twitterClient: TwitterClient, val logger: KLogger = KotlinLogging.logger { } ) : Publisher { override fun publish( pngChartByteArray: ByteArray, title: String, desc: String, quotedPublishedId: String? ): String { val text = this.checkText("$title\n$desc") val uploadMediaResponse = twitterClient.uploadMedia( "stock_alert", pngChartByteArray, MediaCategory.TWEET_IMAGE ); val tweetParametersBuilder = TweetParameters.builder() .text(text) .media( TweetParameters.Media.builder().mediaIds(listOf(uploadMediaResponse.mediaId)).build() ) if (quotedPublishedId != null) tweetParametersBuilder.quoteTweetId(quotedPublishedId) try { val postTweet = twitterClient.postTweet(tweetParametersBuilder.build()) return postTweet.id } catch (e: Throwable) { this.logger.error(e) { "Twitter problem for tweet : $tweetParametersBuilder" } throw e } } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/publisher/twitter_publisher.kt
1468141213
package pl.slaszu.stockanalyzer.infrastructure.publisher import io.github.oshai.kotlinlogging.KLogger import io.github.oshai.kotlinlogging.KotlinLogging import org.jfree.chart.ChartUtils import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.publisher.Publisher import java.io.ByteArrayInputStream import javax.imageio.ImageIO import kotlin.io.path.Path import kotlin.io.path.outputStream import kotlin.random.Random @Service @Profile(value = ["test", "default"]) class TestPublisher( val logger: KLogger = KotlinLogging.logger { } ) : Publisher { override fun publish( pngChartByteArray: ByteArray, title: String, desc: String, quotedPublishedId: String? ): String { val randomInt = Random.nextInt(10000, 99999) val publisherId = "fake_publisher_$randomInt" val file = Path("chart_$publisherId.png") val text = this.checkText("$title\n$desc") ChartUtils.writeBufferedImageAsPNG(file.outputStream(), ImageIO.read(ByteArrayInputStream(pngChartByteArray))) this.logger.warn { "Fake publisher !!! \n$text\nchart=>${file.toAbsolutePath()}" } return publisherId; } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/publisher/local_publisher.kt
3234175550
package pl.slaszu.stockanalyzer.infrastructure.chart import org.jfree.chart.ChartUtils import org.jfree.chart.JFreeChart import org.jfree.chart.annotations.XYPointerAnnotation import org.jfree.chart.axis.AxisLabelLocation import org.jfree.chart.axis.DateAxis import org.jfree.chart.axis.NumberAxis import org.jfree.chart.plot.XYPlot import org.jfree.chart.renderer.xy.CandlestickRenderer import org.jfree.chart.ui.TextAnchor import org.jfree.data.xy.DefaultHighLowDataset import org.springframework.boot.info.BuildProperties import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.chart.ChartPoint import pl.slaszu.stockanalyzer.domain.chart.ChartProvider import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.shared.toDate import java.awt.Color import java.awt.Font import java.util.* import kotlin.math.absoluteValue @Service class JFreeChartProvider(val buildProperty: BuildProperties) : ChartProvider { override fun getPngByteArray( code: String, priceList: Array<StockPriceDto>, buyPoint: ChartPoint?, closePoint: ChartPoint? ): ByteArray { val size: Int = priceList.size val dateArray = arrayOfNulls<Date>(size) val highArray = DoubleArray(size) val lowArray = DoubleArray(size) val openArray = DoubleArray(size) val closeArray = DoubleArray(size) val volumeArray = DoubleArray(size) val pointMap = mutableMapOf<ChartPoint, Int>() for (i in 0 until size) { val s = priceList[i] dateArray[i] = s.date.toDate() highArray[i] = s.priceHigh.toDouble() lowArray[i] = s.priceLow.toDouble() openArray[i] = s.priceOpen.toDouble() closeArray[i] = s.price.toDouble() volumeArray[i] = s.volume.toDouble() if (s == buyPoint?.point) { pointMap[buyPoint] = i } if (s == closePoint?.point) { pointMap[closePoint] = i } } val defaultHighLowDataset = DefaultHighLowDataset( code, dateArray, highArray, lowArray, openArray, closeArray, volumeArray ) val plot = this.getJFreeChartPlot(defaultHighLowDataset) if (buyPoint != null && pointMap[buyPoint] != null) { plot.addAnnotation( getAnnotationPointer( buyPoint.label, defaultHighLowDataset.getXValue(0, pointMap[buyPoint]!!), buyPoint.pointValue.toDouble() ) ) } if (closePoint != null && pointMap[closePoint] != null) { val pointer = getAnnotationPointer( closePoint.label, defaultHighLowDataset.getXValue(0, pointMap[closePoint]!!), closePoint.pointValue.toDouble() ) this.setPointerAngle(pointer, highArray.max(), lowArray.min(), buyPoint?.pointValue?.toDouble()) plot.addAnnotation(pointer) } val chart = JFreeChart(code, JFreeChart.DEFAULT_TITLE_FONT, plot, false); val bufferedImage = chart.createBufferedImage(800, 600) return ChartUtils.encodeAsPNG(bufferedImage) } private fun setPointerAngle(pointer: XYPointerAnnotation, max: Double, min: Double, reservedValue: Double?) { if (reservedValue == null) { return; // do nothing } val xScale = max - min val pointScale = (reservedValue - pointer.y).absoluteValue val scalePercentDifferent = (100 * pointScale) / xScale val xStep = xScale / 10 if (scalePercentDifferent < 5) { // reserved point is higher than point, and point - xStep (about 10% of chart) is higher then min if (reservedValue >= pointer.y && (pointer.y - xStep) > min) { pointer.angle = (180 - 30) * Math.PI / 180 // 180-30 = 150 degrees } // reserved point is higher than point, and point - xStep (about 10% of chart) is lower then min if (reservedValue >= pointer.y && (pointer.y - xStep) <= min) { pointer.angle = (180 + 60) * Math.PI / 180 // 180 + 60 = 240 degrees } // reserved point is lower than point, and point + xStep (about 10% of chart) is higher then max if (reservedValue < pointer.y && (pointer.y + xStep) > max) { pointer.angle = (180 - 60) * Math.PI / 180 // 180-60 = 120 degrees } // reserved point is lower than point, and point + xStep (about 10% of chart) is higher then max if (reservedValue < pointer.y && (pointer.y + xStep) <= max) { pointer.angle = (180 + 30) * Math.PI / 180 // 180+30 = 210 degrees } } } private fun getJFreeChartPlot(dataset: DefaultHighLowDataset): XYPlot { val timeAxis = DateAxis("#gpwApiSignals ver.${this.buildProperty.version}") timeAxis.labelLocation = AxisLabelLocation.HIGH_END val valueAxis = NumberAxis("price"); valueAxis.autoRangeIncludesZero = false; val plot = XYPlot(dataset, timeAxis, valueAxis, null); plot.renderer = CandlestickRenderer(); return plot } private fun getAnnotationPointer( label: String, chartX: Double, chartY: Double ): XYPointerAnnotation { val pointer = XYPointerAnnotation( label, chartX, chartY, Math.PI ) pointer.setBaseRadius(90.0) pointer.setTipRadius(10.0) pointer.setFont(Font("SansSerif", Font.BOLD, 14)) pointer.setPaint(Color.BLACK) pointer.setTextAnchor(TextAnchor.HALF_ASCENT_RIGHT) return pointer; } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/chart/jfree_chart_provider.kt
2031991355
package pl.slaszu.stockanalyzer.infrastructure.report import com.samskivert.mustache.Mustache import gui.ava.html.image.generator.HtmlImageGenerator import kotlinx.datetime.toKotlinLocalDateTime import org.jfree.chart.ChartUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.mustache.MustacheResourceTemplateLoader import org.springframework.boot.info.BuildProperties import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import pl.slaszu.stockanalyzer.domain.report.ReportProvider import pl.slaszu.stockanalyzer.shared.calcSellPrice import pl.slaszu.stockanalyzer.shared.roundTo import java.io.File import java.time.format.DateTimeFormatter @Service class MustacheReportProvider( private val closeAlertRepository: CloseAlertRepository, private val templateLoader: MustacheResourceTemplateLoader, private val compiler: Mustache.Compiler, private val buildProperties: BuildProperties ) : ReportProvider { override fun getHtml(closeAlertModelList: List<CloseAlertModel>, data: Map<String, String>?): String { val reader = templateLoader.getTemplate("report") val template = compiler.compile(reader) val html = template.execute(ReportContext(closeAlertModelList, buildProperties, data ?: mapOf())) File("testing.html").writeText(html) return html } override fun getPngByteArray(html: String): ByteArray { val imageGenerator = HtmlImageGenerator() imageGenerator.loadHtml(html) return ChartUtils.encodeAsPNG(imageGenerator.bufferedImage) } } class ReportContext( private val closeAlertModelList: List<CloseAlertModel>, private val build: BuildProperties, private var data: Map<String, String> ) { var rows: MutableList<Map<String, String>> = mutableListOf() init { val formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss") val data = this.data.toMutableMap() data.putIfAbsent("summary", "0") data.putIfAbsent("days", "0") data["summary_class"] = if (this.data.getOrDefault("summary", "0").toFloat() > 0) "green" else "red" this.data = data.toMap() this.closeAlertModelList.sortedByDescending { it.resultPercent }.forEach { this.rows.add( mapOf( "stock" to "${it.alert.stockName} [${it.alert.stockCode}]", "buy_price" to "${it.alert.price}", "buy_date" to it.alert.date.format(formatter), "result" to "${it.resultPercent}", "result_class" to if (it.resultPercent > 0) "green" else "red", "days" to "${it.daysAfter}", "sell_price" to "${it.price ?: calcSellPrice(it.alert.price, it.resultPercent).roundTo(2)}", "sell_date" to it.date.format(formatter) ) ) } } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/report/mustache_provider.kt
1024358065
package pl.slaszu.stockanalyzer.infrastructure.stock import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.client.RestTemplate @ConfigurationProperties(prefix = "stock-api") data class StockApiParams(val url: String) { } @Configuration("stockBeans") class Beans(val params: StockApiParams) { init { val logger = KotlinLogging.logger { } logger.debug { params } } @Bean fun getRestTemplate(): RestTemplate { return RestTemplate() } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/stock/config.kt
3964599669
package pl.slaszu.stockanalyzer.infrastructure.stock import org.springframework.stereotype.Service import org.springframework.web.client.RestTemplate import pl.slaszu.stockanalyzer.domain.stock.StockDto import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.domain.stock.StockProvider import pl.slaszu.stockanalyzer.shared.toUri @Service class StockProviderRestTemplate(var restTmp: RestTemplate, var params: StockApiParams) : StockProvider { override fun getStockCodeList(): Array<StockDto> { val value = this.restTmp.getForEntity( params.url.toUri("/stocks"), Array<StockDto>::class.java ); return value.body ?: emptyArray<StockDto>(); } override fun getStockPriceList(stockCode: String): Array<StockPriceDto> { val value = this.restTmp.getForEntity( params.url.toUri("/stocks/prices/$stockCode"), Array<StockPriceDto>::class.java ); return value.body ?: emptyArray<StockPriceDto>(); } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/infrastructure/stock/provider.kt
3395103191
package pl.slaszu.stockanalyzer.domain.stockanalyzer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class SignalBeans { @Bean fun highestPriceFluctuationsSince10Days(): HighestPriceFluctuationsSinceFewDays { return HighestPriceFluctuationsSinceFewDays(15,2) } @Bean fun highestPriceSince10Days(): HighestPriceSinceFewDays { return HighestPriceSinceFewDays(15, 2) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stockanalyzer/config.kt
4072263178
package pl.slaszu.stockanalyzer.domain.stockanalyzer enum class SignalEnum { HIGHEST_PRICE_FLUCTUATIONS_SINCE_FEW_DAYS, HIGHEST_PRICE_SINCE_FEW_DAYS } data class Signal( val type: SignalEnum, val desc: String, val data: Map<String, Float> = emptyMap() ) { } class SignalsChecker(private val signals: Array<Signal>) { private val signalsFromEntry = mutableListOf<SignalEnum>() init { this.signals.forEach { signalsFromEntry.add(it.type) } } fun hasAll(): Boolean { return signalsFromEntry.containsAll(SignalEnum.entries) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stockanalyzer/signal.kt
2930741443
package pl.slaszu.stockanalyzer.domain.stockanalyzer import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto @Service class SignalProvider(private val signalLogicList: List<SignalLogic>) { fun getSignals(priceList: Array<StockPriceDto>): Array<Signal> { val signalResultList = mutableListOf<Signal>() this.signalLogicList.forEach { val signal = it.getSignal(priceList) if (signal != null) { signalResultList.add(signal) } } return signalResultList.toTypedArray() } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stockanalyzer/provider.kt
3546442448
package pl.slaszu.stockanalyzer.domain.stockanalyzer import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import pl.slaszu.stockanalyzer.shared.calcPercent import pl.slaszu.stockanalyzer.shared.roundTo interface SignalLogic { fun getSignal(priceList: Array<StockPriceDto>): Signal? } class HighestPriceFluctuationsSinceFewDays(private val days: Int, private val moreThenPercent: Int) : SignalLogic { override fun getSignal(priceList: Array<StockPriceDto>): Signal? { /* 1. sort and get last x days 2. remove last day and remember it 3. get max price from x days without last day 4. if last day price i higher than y percent then signal */ /* 1. sort and get last x days 2. remove last day and remember it 3. get max price from x days without last day 4. if last day price i higher than y percent then signal */ if (priceList.size < 2 || days < 2) { // min 2 elements are required to work return null; } // 1 priceList.sortByDescending { it.date } var end = days if (days > priceList.lastIndex) { end = priceList.lastIndex } // 2 val sliceArray = priceList.sliceArray(1..end) // from 1, first is the latest day val latest = priceList.first() // sort slice by date asc sliceArray.reverse() // calculate avg change percent per days var sumPercent: Float = 0f var qty = 0; var vNext: StockPriceDto? = null for ((i, vPrev) in sliceArray.withIndex()) { val iNext = i + 1 if (iNext > sliceArray.lastIndex) break vNext = sliceArray[iNext] if (vNext.price.equals(0f) || vPrev.price.equals(0f)) { continue } // calc percent sumPercent += calcPercent(vPrev.price, vNext.price).roundTo(2) qty++ } if (vNext == null || qty == 0) { return null } val avgPercent = (sumPercent / qty).roundTo(2) // calc latest price val percent = calcPercent(vNext.price, latest.price).roundTo(2) // check condition if (percent >= avgPercent + moreThenPercent) { return createSignal(avgPercent, percent) } return null; } private fun createSignal(avgPercent: Float, calculatedPercent: Float): Signal { return Signal( SignalEnum.HIGHEST_PRICE_FLUCTUATIONS_SINCE_FEW_DAYS, "Price fluctuation $calculatedPercent% is highest since $days days!", mapOf( "avgPercent" to avgPercent, "calculatedPercent" to calculatedPercent ) ) } } class HighestPriceSinceFewDays(private val days: Int, private val higherThenPercent: Int) : SignalLogic { override fun getSignal(priceList: Array<StockPriceDto>): Signal? { /* 1. sort and get last x days 2. remove last day and remember it 3. get max price from x days without last day 4. if last day price i higher than y percent then signal */ if (priceList.size < 2 || days < 2) { // min 2 elements are required to work return null; } // 1 priceList.sortByDescending { it.date } var end = days if (days > priceList.lastIndex) { end = priceList.lastIndex } // 2 val sliceArray = priceList.sliceArray(1..end) // from 1, first is the latest day val latest = priceList.first() // 3 val maxPriceHigh = sliceArray.maxOf { it.priceHigh }.roundTo(2) val percent = calcPercent(maxPriceHigh, latest.price).roundTo(2) if (percent > higherThenPercent && maxPriceHigh < latest.price) { return createSignal( latest.priceHigh, days, mapOf( "maxPrice" to maxPriceHigh, "lastPrice" to latest.price, "higherThenPercent" to percent ) ) } return null } private fun createSignal(maxPrice: Float, days: Int, data: Map<String, Float>): Signal { return Signal( SignalEnum.HIGHEST_PRICE_SINCE_FEW_DAYS, "Price $maxPrice is the highest since $days days!", data ) } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stockanalyzer/signal_logic.kt
4166064958
package pl.slaszu.stockanalyzer.domain.publisher import com.twitter.twittertext.TwitterTextParser import java.io.File interface Publisher { fun publish(pngChartByteArray: ByteArray, title: String, desc: String, quotedPublishedId: String? = null): String fun checkText(text: String): String { val parseTweet = TwitterTextParser.parseTweet(text) if (!parseTweet.isValid) { println("Text is no valid ! Text length: '${parseTweet.weightedLength}' dose not to fit to range '${parseTweet.validTextRange.start} to ${parseTweet.validTextRange.end}'") val lessText = text.substringBeforeLast("\n") if (lessText.length == text.length) { throw Exception("$text has same size as $lessText !") } return checkText(lessText); } println("Text length: '${parseTweet.weightedLength}' fit to range '${parseTweet.validTextRange.start} to ${parseTweet.validTextRange.end}'") return text } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/publisher/publisher.kt
3641073766
package pl.slaszu.stockanalyzer.domain.alert import org.springframework.stereotype.Service import pl.slaszu.stockanalyzer.domain.alert.model.AlertModel import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertRepository import java.time.LocalDateTime @Service class CloseAlertService( val alertRepo: AlertRepository, val closeAlertRepo: CloseAlertRepository ) { fun closeAlert(alert: AlertModel) { // id must exists val alertId = alert.id!! val alertRefreshed = alert.copy(close = true, closeDate = LocalDateTime.now()) val findByAlertIdList = this.closeAlertRepo.findByAlertId(alertId) findByAlertIdList.forEach { val closeAlertModelRefreshed = it.copy(alert = alertRefreshed) this.closeAlertRepo.save(closeAlertModelRefreshed) } this.alertRepo.save(alertRefreshed) } } @Service class CloseAlertProvider(val closeAlertRepository: CloseAlertRepository) { fun getAllForAlerts(alertList: List<AlertModel>): List<CloseAlertModel> { val result = mutableListOf<CloseAlertModel>() alertList.forEach { result.addAll(this.closeAlertRepository.findByAlertId(it.id!!)) } return result.toList() } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/alert/alert_services.kt
1362337069
package pl.slaszu.stockanalyzer.domain.alert.model import org.springframework.data.annotation.TypeAlias import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.Query import pl.slaszu.stockanalyzer.domain.stockanalyzer.SignalEnum import java.time.LocalDateTime @Document("alert") @TypeAlias("alert") data class AlertModel( val stockCode: String, val stockName: String, val price: Float, val signals: List<SignalEnum>, val tweetId: String, val date: LocalDateTime = LocalDateTime.now(), val close: Boolean = false, val closeDate: LocalDateTime? = null, val id: String? = null ) { } interface AlertRepository : MongoRepository<AlertModel, String> { /** * test purpose only */ fun findByDateAfterAndCloseIsFalse(date: LocalDateTime): List<AlertModel> @Query("{\$and: [{'date' : { \$lt: ?0 }}, {'close': false}]}") fun findAlertsActiveBeforeThatDate(date: LocalDateTime): List<AlertModel> @Query("{\$and: [{'closeDate' : { \$gt: ?0 }}, {'close': true}]}") fun findAlertsClosedAfterThatDate(date: LocalDateTime): List<AlertModel> }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/alert/model/alert.kt
3195235915
package pl.slaszu.stockanalyzer.domain.alert.model import org.springframework.data.annotation.TypeAlias import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.Query import java.time.LocalDateTime @Document("close_alert") @TypeAlias("close_alert") data class CloseAlertModel( val alert: AlertModel, val tweetId: String, val resultPercent: Float, val daysAfter: Int, val price: Float? = null, val date: LocalDateTime = LocalDateTime.now(), val id: String? = null ) { } interface CloseAlertRepository : MongoRepository<CloseAlertModel, String> { @Query("{\$and: [{'alert.stockCode': ?0}, {'daysAfter': ?1}, {'alert.close': false}]}") fun findByStockCodeAndDaysAfter(stockCode: String, daysAfter: Int): List<CloseAlertModel> @Query("{\$and: [{'daysAfter': ?0}, {'alert.close': ?1}]}") fun findByDaysAfterAndAlertClose(daysAfter: Int, alertClose: Boolean = false): List<CloseAlertModel> @Query("{ 'alert._id': ObjectId(?0) }") fun findByAlertId(alertId: String): List<CloseAlertModel> @Query("{'date' : { \$gt: ?0 }}") fun findCloseAlertsAfterDate(date: LocalDateTime): List<CloseAlertModel> }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/alert/model/close_alert.kt
1520743069
package pl.slaszu.stockanalyzer.domain.chart import pl.slaszu.stockanalyzer.domain.stock.StockPriceDto import java.util.Date interface ChartProvider { fun getPngByteArray( code: String, priceList: Array<StockPriceDto>, buyPoint: ChartPoint? = null, closePoint: ChartPoint? = null ): ByteArray } data class ChartPoint(val point: StockPriceDto, val pointValue: Float, val label: String)
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/chart/provider.kt
3591070102
package pl.slaszu.stockanalyzer.domain.report import pl.slaszu.stockanalyzer.domain.alert.model.CloseAlertModel interface ReportProvider { fun getHtml(closeAlertModelList: List<CloseAlertModel>, data: Map<String, String>?): String fun getPngByteArray(html: String): ByteArray }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/report/provider.kt
3944569017
package pl.slaszu.stockanalyzer.domain.stock import com.fasterxml.jackson.annotation.JsonFormat import java.time.LocalDate import java.time.LocalDateTime data class StockDto(val name:String, val code:String?) { } data class StockPriceDto( val priceOpen: Float, val priceHigh: Float, val priceLow: Float, val price: Float, val volume: Int, val amount: Int, @JsonFormat(pattern = "yyyy-MM-dd") val date: LocalDate, @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss Z") val updatedAt: LocalDateTime ) { }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stock/dto.kt
220395526
package pl.slaszu.stockanalyzer.domain.stock interface StockProvider { fun getStockCodeList(): Array<StockDto> fun getStockPriceList(stockCode: String): Array<StockPriceDto> }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/domain/stock/provider.kt
3381028402
package pl.slaszu.stockanalyzer import io.sentry.Sentry import org.springframework.beans.factory.annotation.Value import org.springframework.boot.ApplicationRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.info.BuildProperties import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.scheduling.annotation.EnableScheduling import pl.slaszu.stockanalyzer.application.CreateReport import pl.slaszu.stockanalyzer.domain.alert.model.AlertRepository import pl.slaszu.stockanalyzer.infrastructure.publisher.TwitterConfig import pl.slaszu.stockanalyzer.infrastructure.stock.StockApiParams @SpringBootApplication @EnableMongoRepositories @EnableConfigurationProperties( StockApiParams::class, TwitterConfig::class ) @EnableScheduling class StockanalyzerApplication fun main(args: Array<String>) { runApplication<StockanalyzerApplication>(*args) println("Hello world") } @Configuration class ProdBeans { @Bean fun sentryInit(): ApplicationRunner { return ApplicationRunner { Sentry.init { options -> options.dsn = "https://[email protected]/4507126154657792" // Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring. // We recommend adjusting this value in production. //options.tracesSampleRate = 1.0 // When first trying Sentry it's good to see what the SDK is doing: options.isDebug = true } println("sentry init done") } } @Bean fun testMongoConnection( buildProperty: BuildProperties, alertRepo: AlertRepository, @Value("\${spring.data.mongodb.uri}") mongoUrl: String ): ApplicationRunner { return ApplicationRunner { buildProperty.forEach { println("${it.key} => ${it.value}") } println("$mongoUrl") val findAll = alertRepo.findAll() println("Mongo test, alert models find ${findAll.size} qty") } } } @Configuration @Profile("default") class SomeBeans { // @Bean // fun testCreateAlert(action: CreateAlerts): ApplicationRunner { // return ApplicationRunner { // action.run() // } // } // // @Bean // fun testCloseAlert(action: CloseAlerts): ApplicationRunner { // return ApplicationRunner { // action.runForDaysAfter(0, true) // } // } // @Bean fun testCreateReport(action: CreateReport): ApplicationRunner { return ApplicationRunner { action.runForDaysAfter(18) } } }
stockanalyzer/src/main/kotlin/pl/slaszu/stockanalyzer/StockanalyzerApplication.kt
3024290006
package tr.com.borabuyukbas.phonebackup import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("tr.com.borabuyukbas.phonebackup", appContext.packageName) } }
PhoneBackup/app/src/androidTest/java/tr/com/borabuyukbas/phonebackup/ExampleInstrumentedTest.kt
2862649435
package tr.com.borabuyukbas.phonebackup import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
PhoneBackup/app/src/test/java/tr/com/borabuyukbas/phonebackup/ExampleUnitTest.kt
2459789691
package tr.com.borabuyukbas.phonebackup.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/ui/theme/Color.kt
3764083320
package tr.com.borabuyukbas.phonebackup.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun PhoneBackupTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/ui/theme/Theme.kt
1209262585
package tr.com.borabuyukbas.phonebackup.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/ui/theme/Type.kt
1075652943
package tr.com.borabuyukbas.phonebackup import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Application() } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/MainActivity.kt
3499722460
package tr.com.borabuyukbas.phonebackup import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import tr.com.borabuyukbas.phonebackup.components.Header import tr.com.borabuyukbas.phonebackup.components.Navbar import tr.com.borabuyukbas.phonebackup.components.NavbarItem import tr.com.borabuyukbas.phonebackup.screens.Backup import tr.com.borabuyukbas.phonebackup.screens.Restore import tr.com.borabuyukbas.phonebackup.ui.theme.PhoneBackupTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun Application() { val navController = rememberNavController() val navigationList = listOf( NavbarItem("backup", "Backup", Icons.Filled.Build), NavbarItem("restore", "Restore", Icons.Filled.Refresh) ) PhoneBackupTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Scaffold( topBar = { Header() }, bottomBar = { Navbar(navController, navigationList) }, ) { paddingValues -> NavHost(navController = navController, startDestination = "backup", modifier = Modifier.padding(paddingValues)) { composable("backup") { Backup() } composable("restore") { Restore() } } } } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/Application.kt
1508944019
package tr.com.borabuyukbas.phonebackup.utils import android.content.ContentValues import android.content.Context import android.provider.CalendarContract import androidx.compose.runtime.MutableState data class Calendar( val dtStart: Long?, val dtEnd: Long?, val duration: String?, val title: String?, val description: String?, val eventLocation: String?, val eventTimeZone: String?, val allDay: Boolean?, val exDate: String?, val exRule: String?, val rDate: String?, val rRule: String?, val hasAlarm: Boolean?, val status: Int?, val selfAttendeeStatus: Int?, val organizer: String?, val hasAttendeeData: Boolean?, val accessLevel: Int?, val availability: Int? ) : BaseUtil { override fun importToDevice(context: Context) { val values = ContentValues().apply { put(CalendarContract.Events.CALENDAR_ID, defaultCalendarId.value(context)) put(CalendarContract.Events.DTSTART, dtStart) put(CalendarContract.Events.DTEND, dtEnd) put(CalendarContract.Events.DURATION, duration) put(CalendarContract.Events.TITLE, title) put(CalendarContract.Events.DESCRIPTION, description) put(CalendarContract.Events.EVENT_LOCATION, eventLocation) put(CalendarContract.Events.EVENT_TIMEZONE, eventTimeZone) put(CalendarContract.Events.ALL_DAY, allDay) put(CalendarContract.Events.EXDATE, exDate) put(CalendarContract.Events.EXRULE, exRule) put(CalendarContract.Events.RDATE, rDate) put(CalendarContract.Events.RRULE, rRule) put(CalendarContract.Events.HAS_ALARM, hasAlarm) put(CalendarContract.Events.STATUS, status) put(CalendarContract.Events.SELF_ATTENDEE_STATUS, selfAttendeeStatus) put(CalendarContract.Events.ORGANIZER, organizer) put(CalendarContract.Events.HAS_ATTENDEE_DATA, hasAttendeeData) put(CalendarContract.Events.ACCESS_LEVEL, accessLevel) put(CalendarContract.Events.AVAILABILITY, availability) } context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values) } companion object : BaseUtilHelper<Calendar> { private val defaultCalendarId: Lazy<(Context) -> Long?> by lazy { lazy { { context: Context -> getDefaultCalendarId(context) ?: throw IllegalStateException("Default calendar ID not found.") } } } private fun getDefaultCalendarId(context: Context): Long? { val projection = arrayOf(CalendarContract.Calendars._ID) val selection = "${CalendarContract.Calendars.IS_PRIMARY} = 1" val cursor = context.contentResolver.query( CalendarContract.Calendars.CONTENT_URI, projection, selection, null, null ) cursor?.use { if (cursor.moveToFirst()) { return getValue<Long>(cursor, 0) } } return null } override suspend fun getAll( context: Context, progress: MutableState<Float>? ): List<Calendar> { val returnList = mutableListOf<Calendar>() val cursor = context.contentResolver.query( CalendarContract.Events.CONTENT_URI, arrayOf( CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.DURATION, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.EVENT_LOCATION, CalendarContract.Events.EVENT_TIMEZONE, CalendarContract.Events.ALL_DAY, CalendarContract.Events.EXDATE, CalendarContract.Events.EXRULE, CalendarContract.Events.RDATE, CalendarContract.Events.RRULE, CalendarContract.Events.HAS_ALARM, CalendarContract.Events.STATUS, CalendarContract.Events.SELF_ATTENDEE_STATUS, CalendarContract.Events.ORGANIZER, CalendarContract.Events.HAS_ATTENDEE_DATA, CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.AVAILABILITY, ), null, null, null ) ?: return returnList if (progress != null) { progress.value = 0.0f } val totalRows = cursor.count.toFloat() var i = 0 while (cursor.moveToNext()) { returnList.add( Calendar( getValue(cursor, 0), getValue(cursor, 1), getValue(cursor, 2), getValue(cursor, 3), getValue(cursor, 4), getValue(cursor, 5), getValue(cursor, 6), getValue(cursor, 7), getValue(cursor, 8), getValue(cursor, 9), getValue(cursor, 10), getValue(cursor, 11), getValue(cursor, 12), getValue(cursor, 13), getValue(cursor, 14), getValue(cursor, 15), getValue(cursor, 16), getValue(cursor, 17), getValue(cursor, 18), ) ) i++ if (progress != null) { progress.value = i / totalRows } } return returnList } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/utils/Calendar.kt
2618314962
package tr.com.borabuyukbas.phonebackup.utils import android.content.ContentValues import android.content.Context import android.provider.Telephony import androidx.compose.runtime.MutableState data class SMS( val address: String?, val body: String?, val type: Int?, val date: Long?, ) : BaseUtil { private var read: Boolean? = null // To exclude it from comparison/de-duplication. constructor( address: String?, body: String?, type: Int?, date: Long?, read: Boolean? ) : this(address, body, type, date) { this.read = read } override fun importToDevice(context: Context) { if (address == null) return if (!threadIdMap.containsKey(address)) { val threadId = Telephony.Threads.getOrCreateThreadId( context, address ) threadIdMap[address] = threadId } val values = ContentValues().apply { put(Telephony.Sms.ADDRESS, address) put(Telephony.Sms.BODY, body) put(Telephony.Sms.TYPE, type) put(Telephony.Sms.DATE, date) put(Telephony.Sms.READ, read) put(Telephony.Sms.THREAD_ID, threadIdMap[address]) } context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values) } companion object : BaseUtilHelper<SMS> { private val threadIdMap: MutableMap<String, Long> = mutableMapOf() override suspend fun getAll(context: Context, progress: MutableState<Float>?): List<SMS> { val returnList = mutableListOf<SMS>() val cursor = context.contentResolver.query( Telephony.Sms.CONTENT_URI, arrayOf( Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.TYPE, Telephony.Sms.DATE, Telephony.Sms.READ, ), null, null, null ) ?: return returnList if (progress != null) { progress.value = 0.0f } val totalRows = cursor.count.toFloat() var i = 0 while (cursor.moveToNext()) { returnList.add( SMS( getValue(cursor, 0), getValue(cursor, 1), getValue(cursor, 2), getValue(cursor, 3), getValue(cursor, 4), ) ) i++ if (progress != null) { progress.value = i / totalRows } } return returnList } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/utils/SMS.kt
1737353149
package tr.com.borabuyukbas.phonebackup.utils import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.provider.ContactsContract import android.provider.ContactsContract.CommonDataKinds.StructuredName import androidx.compose.runtime.MutableState data class Contact ( val name: String?, val phoneNumbers: List<String> ) : BaseUtil { override fun importToDevice(context: Context) { val rawContactUri = context.contentResolver.insert(ContactsContract.RawContacts.CONTENT_URI, ContentValues()) val rawContactId = rawContactUri?.let { ContentUris.parseId(it) } val nameValues = ContentValues().apply { put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId) put(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) put(StructuredName.DISPLAY_NAME, name) } context.contentResolver.insert(ContactsContract.Data.CONTENT_URI, nameValues) for (phoneNumber in phoneNumbers) { val phoneValues = ContentValues().apply { put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId) put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber) put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) } context.contentResolver.insert(ContactsContract.Data.CONTENT_URI, phoneValues) } } companion object : BaseUtilHelper<Contact> { override suspend fun getAll( context: Context, progress: MutableState<Float>? ): List<Contact> { val returnList = mutableListOf<Contact>() val phoneNumberMap: MutableMap<Int, MutableList<String>> = mutableMapOf() val phoneNumberCursor = context.contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, arrayOf( ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID ), null, null ) if (phoneNumberCursor != null) { while (phoneNumberCursor.moveToNext()) { val phoneNo = getValue<String>(phoneNumberCursor, 0) val contactId = getValue<Int>(phoneNumberCursor, 1) if (phoneNo == null || contactId == null) continue if (!phoneNumberMap.containsKey(contactId)) { phoneNumberMap[contactId] = mutableListOf() } phoneNumberMap[contactId]!!.add(phoneNo) } phoneNumberCursor.close() } val cursor = context.contentResolver.query( ContactsContract.Contacts.CONTENT_URI, arrayOf( ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER ), null, null, null ) ?: return returnList if (progress != null) { progress.value = 0.0f } val totalRows = cursor.count.toFloat() var i = 0 while (cursor.moveToNext()) { val hasPhoneNumber = getValue<Boolean>(cursor, 2) if (hasPhoneNumber != null && hasPhoneNumber) { val id = getValue<Int>(cursor, 0) val name = getValue<String>(cursor, 1) val phoneNumbers = phoneNumberMap[id] ?: listOf() returnList.add( Contact( name, phoneNumbers ) ) } i++ if (progress != null) { progress.value = i / totalRows } } return returnList } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/utils/Contact.kt
1613834722
package tr.com.borabuyukbas.phonebackup.utils import android.content.ContentValues import android.content.Context import android.provider.CallLog.Calls import androidx.compose.runtime.MutableState data class Call ( val number: String?, val date: Long?, val type: Int?, val new: Boolean?, val duration: Int? ) : BaseUtil { override fun importToDevice(context: Context) { val values = ContentValues().apply { put(Calls.NUMBER, number) put(Calls.DATE, date) put(Calls.TYPE, type) put(Calls.NEW, new) put(Calls.DURATION, duration) } context.contentResolver.insert(Calls.CONTENT_URI, values) } companion object : BaseUtilHelper<Call> { override suspend fun getAll(context: Context, progress: MutableState<Float>?): List<Call> { val returnList = mutableListOf<Call>() val cursor = context.contentResolver.query( Calls.CONTENT_URI, arrayOf( Calls.NUMBER, Calls.DATE, Calls.TYPE, Calls.NEW, Calls.DURATION ), null, null, null ) ?: return returnList if (progress != null) { progress.value = 0.0f } val totalRows = cursor.count.toFloat() var i = 0 while (cursor.moveToNext()) { returnList.add( Call( getValue(cursor, 0), getValue(cursor, 1), getValue(cursor, 2), getValue(cursor, 3), getValue(cursor, 4), ) ) i++ if (progress != null) { progress.value = i / totalRows } } return returnList } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/utils/Call.kt
1882667142
package tr.com.borabuyukbas.phonebackup.utils import android.content.Context import android.database.Cursor import androidx.compose.foundation.ScrollState import androidx.compose.runtime.MutableState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch inline fun <reified T> getValue(cursor: Cursor, index: Int): T? { val isNull = cursor.isNull(index) if (isNull) return null return when (T::class) { String::class -> cursor.getString(index) as T Boolean::class -> (cursor.getInt(index) == 1) as T Int::class -> cursor.getInt(index) as T Long::class -> cursor.getLong(index) as T else -> throw Exception("Unhandled return type") } } fun createLogFunction (logText: MutableState<String>, scrollState: ScrollState): (String) -> Unit { return { CoroutineScope(Dispatchers.Default).launch { logText.value += "${it}\n" scrollState.scrollTo(scrollState.maxValue) } } } data class AllUtils(val sms: List<SMS>, val contacts: List<Contact>, val calls: List<Call>, val calendar: List<Calendar>) interface BaseUtil { fun importToDevice(context: Context) } interface BaseUtilHelper<T> { suspend fun getAll(context: Context, progress: MutableState<Float>? = null): List<T> }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/utils/BaseUtil.kt
642476229
package tr.com.borabuyukbas.phonebackup.screens import android.Manifest import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Phone import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.google.gson.Gson import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tr.com.borabuyukbas.phonebackup.components.PermissionCheckbox import tr.com.borabuyukbas.phonebackup.utils.AllUtils import tr.com.borabuyukbas.phonebackup.utils.Calendar import tr.com.borabuyukbas.phonebackup.utils.Call import tr.com.borabuyukbas.phonebackup.utils.Contact import tr.com.borabuyukbas.phonebackup.utils.SMS import tr.com.borabuyukbas.phonebackup.utils.createLogFunction @Composable fun Restore() { val smsChecked = remember { mutableStateOf(false) } val contactsChecked = remember { mutableStateOf(false) } val callLogsChecked = remember { mutableStateOf(false) } val calendarChecked = remember { mutableStateOf(false) } val smsLoading = remember { mutableStateOf(false) } val contactsLoading = remember { mutableStateOf(false) } val callLogsLoading = remember { mutableStateOf(false) } val calendarLoading = remember { mutableStateOf(false) } val smsProgress = remember { mutableFloatStateOf(0.0f) } val contactsProgress = remember { mutableFloatStateOf(0.0f) } val callLogsProgress = remember { mutableFloatStateOf(0.0f) } val calendarProgress = remember { mutableFloatStateOf(0.0f) } val context = LocalContext.current val returnStr = remember { mutableStateOf("") } val returnScroll = rememberScrollState() val log = createLogFunction(returnStr, returnScroll) val parsedObject = remember { mutableStateOf<AllUtils?>(null) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.OpenDocument(), onResult = { if (it != null) { returnStr.value = "" CoroutineScope(Dispatchers.IO).launch { withContext(Dispatchers.IO) { val stream = context.contentResolver.openInputStream(it) if (stream != null) { val fileContent = stream.readBytes().decodeToString() try { parsedObject.value = Gson().fromJson(fileContent, AllUtils::class.java) log("Backup successfully loaded.") } catch (e: Exception) { parsedObject.value = null log("Cannot load backup file (parsing error).") } finally { stream.close() } } } } } } ) Column ( modifier = Modifier.padding(32.dp), verticalArrangement = Arrangement.spacedBy(24.dp) ) { Column ( verticalArrangement = Arrangement.spacedBy(12.dp) ) { Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Column ( modifier = Modifier.padding(4.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "${if(parsedObject.value == null) 0 else parsedObject.value!!.sms.size} SMS") Text(text = "${if(parsedObject.value == null) 0 else parsedObject.value!!.contacts.size} Contacts") } Column ( modifier = Modifier.padding(4.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "${if(parsedObject.value == null) 0 else parsedObject.value!!.calls.size} Calls") Text(text = "${if(parsedObject.value == null) 0 else parsedObject.value!!.calendar.size} Events") } Button( onClick = { launcher.launch(arrayOf("application/json")) } ) { Text(text = "Choose") } } PermissionCheckbox("SMS", Icons.Filled.Email, Manifest.permission.READ_SMS, smsChecked, smsProgress, smsLoading, parsedObject.value == null || parsedObject.value!!.sms.isEmpty(), checkDefaultSMS = true) PermissionCheckbox("Contacts", Icons.Filled.Person, Manifest.permission.WRITE_CONTACTS, contactsChecked, contactsProgress, contactsLoading, parsedObject.value == null || parsedObject.value!!.contacts.isEmpty()) PermissionCheckbox("Call Logs", Icons.Filled.Phone, Manifest.permission.WRITE_CALL_LOG, callLogsChecked, callLogsProgress, callLogsLoading, parsedObject.value == null || parsedObject.value!!.calls.isEmpty()) PermissionCheckbox("Calendar", Icons.Filled.DateRange, Manifest.permission.WRITE_CALENDAR, calendarChecked, calendarProgress, calendarLoading, parsedObject.value == null || parsedObject.value!!.calendar.isEmpty()) } Button( modifier = Modifier.fillMaxWidth(), enabled = smsChecked.value || contactsChecked.value || callLogsChecked.value || calendarChecked.value, onClick = { CoroutineScope(Dispatchers.IO).launch { smsLoading.value = false contactsLoading.value = false callLogsLoading.value = false calendarLoading.value = false returnStr.value = "" if (parsedObject.value != null) { if (smsChecked.value) { smsLoading.value = true withContext(Dispatchers.IO) { val sms = SMS.getAll(context, smsProgress) log("Found ${sms.size} SMS") val filteredSMS = parsedObject.value!!.sms.filter { it !in sms } log("Importing ${filteredSMS.size} different SMS.") filteredSMS.forEach { it.importToDevice(context) } } } if (contactsChecked.value) { contactsLoading.value = true withContext(Dispatchers.IO) { val contacts = Contact.getAll(context, contactsProgress) log("Found ${contacts.size} Contacts") val filteredContacts = parsedObject.value!!.contacts.filter { it !in contacts } log("Importing ${filteredContacts.size} different Contacts.") filteredContacts.forEach { it.importToDevice(context) } } } if (callLogsChecked.value) { callLogsLoading.value = true withContext(Dispatchers.IO) { val calls = Call.getAll(context, callLogsProgress) log("Found ${calls.size} Calls") val filteredCalls = parsedObject.value!!.calls.filter { it !in calls } log("Importing ${filteredCalls.size} different Calls.") filteredCalls.forEach { it.importToDevice(context) } } } if (calendarChecked.value) { calendarLoading.value = true withContext(Dispatchers.IO) { val calendar = Calendar.getAll(context, calendarProgress) log("Found ${calendar.size} Calendar Events") val filteredCalendar = parsedObject.value!!.calendar.filter { it !in calendar } log("Importing ${filteredCalendar.size} different Events.") filteredCalendar.forEach { it.importToDevice(context) } } } } log("Restoring successfully completed.") smsLoading.value = false contactsLoading.value = false callLogsLoading.value = false calendarLoading.value = false } } ) { Text(text = "Restore") } Text( text = returnStr.value, modifier = Modifier .fillMaxWidth() .verticalScroll(returnScroll) ) } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/screens/Restore.kt
669984959
package tr.com.borabuyukbas.phonebackup.screens import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Phone import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.google.gson.Gson import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tr.com.borabuyukbas.phonebackup.components.PermissionCheckbox import tr.com.borabuyukbas.phonebackup.utils.AllUtils import tr.com.borabuyukbas.phonebackup.utils.Calendar import tr.com.borabuyukbas.phonebackup.utils.Call import tr.com.borabuyukbas.phonebackup.utils.Contact import tr.com.borabuyukbas.phonebackup.utils.SMS import tr.com.borabuyukbas.phonebackup.utils.createLogFunction import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Composable fun Backup() { val smsChecked = remember { mutableStateOf(false) } val contactsChecked = remember { mutableStateOf(false) } val callLogsChecked = remember { mutableStateOf(false) } val calendarChecked = remember { mutableStateOf(false) } val smsLoading = remember { mutableStateOf(false) } val contactsLoading = remember { mutableStateOf(false) } val callLogsLoading = remember { mutableStateOf(false) } val calendarLoading = remember { mutableStateOf(false) } val smsProgress = remember { mutableFloatStateOf(0.0f) } val contactsProgress = remember { mutableFloatStateOf(0.0f) } val callLogsProgress = remember { mutableFloatStateOf(0.0f) } val calendarProgress = remember { mutableFloatStateOf(0.0f) } val context = LocalContext.current val returnStr = remember { mutableStateOf("") } val returnScroll = rememberScrollState() val log = createLogFunction(returnStr, returnScroll) val saveContent = remember { mutableStateOf("") } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.CreateDocument("application/json"), onResult = { if (it != null) { CoroutineScope(Dispatchers.IO).launch { withContext(Dispatchers.IO) { val stream = context.contentResolver.openOutputStream(it) if (stream != null) { stream.write(saveContent.value.toByteArray()) stream.close() } log("Backup successfully completed.") } } } } ) Column ( modifier = Modifier.padding(32.dp), verticalArrangement = Arrangement.spacedBy(24.dp) ) { Column ( verticalArrangement = Arrangement.spacedBy(12.dp) ) { PermissionCheckbox("SMS", Icons.Filled.Email, android.Manifest.permission.READ_SMS, smsChecked, smsProgress, smsLoading) PermissionCheckbox("Contacts", Icons.Filled.Person, android.Manifest.permission.READ_CONTACTS, contactsChecked, contactsProgress, contactsLoading) PermissionCheckbox("Call Logs", Icons.Filled.Phone, android.Manifest.permission.READ_CALL_LOG, callLogsChecked, callLogsProgress, callLogsLoading) PermissionCheckbox("Calendar", Icons.Filled.DateRange, android.Manifest.permission.READ_CALENDAR, calendarChecked, calendarProgress, calendarLoading) } Button( modifier = Modifier.fillMaxWidth(), enabled = (smsChecked.value || contactsChecked.value || callLogsChecked.value || calendarChecked.value) && (!smsLoading.value && !contactsLoading.value && !callLogsLoading.value && !calendarLoading.value), onClick = { CoroutineScope(Dispatchers.IO).launch { smsLoading.value = false contactsLoading.value = false callLogsLoading.value = false calendarLoading.value = false returnStr.value = "" var sms: List<SMS> = listOf() var contacts: List<Contact> = listOf() var calls: List<Call> = listOf() var calendar: List<Calendar> = listOf() if (smsChecked.value) { smsLoading.value = true withContext(Dispatchers.IO) { sms = SMS.getAll(context, smsProgress) log("Found ${sms.size} SMS") } } if (contactsChecked.value) { contactsLoading.value = true withContext(Dispatchers.IO) { contacts = Contact.getAll(context, contactsProgress) log("Found ${contacts.size} Contacts") } } if (callLogsChecked.value) { callLogsLoading.value = true withContext(Dispatchers.IO) { calls = Call.getAll(context, callLogsProgress) log("Found ${calls.size} Calls") } } if (calendarChecked.value) { calendarLoading.value = true withContext(Dispatchers.IO) { calendar = Calendar.getAll(context, calendarProgress) log("Found ${calendar.size} Calendar Events") } } withContext(Dispatchers.IO) { log("Converting data to JSON object.") saveContent.value = Gson().toJson(AllUtils( sms, contacts, calls, calendar )) launcher.launch("backup_${LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmm"))}") } smsLoading.value = false contactsLoading.value = false callLogsLoading.value = false calendarLoading.value = false } } ) { Text(text = "Backup") } Text( text = returnStr.value, modifier = Modifier .fillMaxWidth() .horizontalScroll(returnScroll) ) } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/screens/Backup.kt
567728386
package tr.com.borabuyukbas.phonebackup.components import android.app.Activity import android.app.role.RoleManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableFloatState import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.PermissionStatus import com.google.accompanist.permissions.rememberPermissionState @OptIn(ExperimentalPermissionsApi::class) @Composable fun PermissionCheckbox( text: String, icon: ImageVector, requiredPermission: String, checked: MutableState<Boolean>, progress: MutableFloatState, loading: MutableState<Boolean>, forceDisable: Boolean = false, checkDefaultSMS: Boolean = false, ) { val (checkedState, onStateChange) = checked val permissionState = rememberPermissionState(requiredPermission) val isDefaultSMSApp = remember { mutableStateOf(false) } val context = LocalContext.current val roleManager = context.getSystemService(RoleManager::class.java) val roleRequestIntent = roleManager.createRequestRoleIntent(RoleManager.ROLE_SMS) if (roleManager.isRoleAvailable(RoleManager.ROLE_SMS)) { isDefaultSMSApp.value = roleManager.isRoleHeld(RoleManager.ROLE_SMS) } val defaultSMSAppRequest = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { isDefaultSMSApp.value = true } } Row( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .toggleable( value = checkedState, onValueChange = { onStateChange(!checkedState) }, role = Role.Checkbox, enabled = permissionState.status == PermissionStatus.Granted && (!checkDefaultSMS || isDefaultSMSApp.value) && !forceDisable ) .background(if (permissionState.status != PermissionStatus.Granted || (checkDefaultSMS && !isDefaultSMSApp.value) || forceDisable) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.inversePrimary) .padding(18.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row { Checkbox ( checked = checkedState, onCheckedChange = null ) Icon( icon, contentDescription = text, modifier = Modifier.padding(start = 8.dp) ) Text( text = text, modifier = Modifier.padding(start = 4.dp) ) } if ((permissionState.status != PermissionStatus.Granted) || (checkDefaultSMS && !isDefaultSMSApp.value)) { Button( onClick = { if (checkDefaultSMS) defaultSMSAppRequest.launch(roleRequestIntent) else permissionState.launchPermissionRequest() }, enabled = !forceDisable ) { Text("Allow") } } if (loading.value) { CircularProgressIndicator( progress = progress.floatValue ) } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/components/PermissionCheckbox.kt
1739738348
package tr.com.borabuyukbas.phonebackup.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import tr.com.borabuyukbas.phonebackup.R @OptIn(ExperimentalMaterial3Api::class) @Preview(showBackground = true) @Composable fun Header() { CenterAlignedTopAppBar( colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = MaterialTheme.colorScheme.primary, titleContentColor = MaterialTheme.colorScheme.background, ), title = { Row ( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Icon( painterResource(R.drawable.phonebackup), stringResource(R.string.app_name) ) Text( text = "PhoneBackup", fontSize = 28.sp, fontWeight = FontWeight.Medium, style = TextStyle( platformStyle = PlatformTextStyle( includeFontPadding = false ) ) ) } } ) }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/components/Header.kt
2896271407
package tr.com.borabuyukbas.phonebackup.components import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.vector.ImageVector import androidx.navigation.NavController import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.currentBackStackEntryAsState class NavbarItem(val nav: String, val name: String, val icon: ImageVector) @Composable fun Navbar(navController: NavController, navigationList: List<NavbarItem>) { val navBackStackEntry = navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry.value?.destination NavigationBar { navigationList.forEachIndexed { index, item -> NavigationBarItem( icon = { Icon(item.icon, contentDescription = item.name) }, label = { Text(item.name) }, selected = currentDestination?.hierarchy?.any { it.route == item.nav } == true, onClick = { navController.navigate(item.nav) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } ) } } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/components/Navbar.kt
961301210
package tr.com.borabuyukbas.phonebackup import android.content.BroadcastReceiver import android.content.Context import android.content.Intent class DummyBroadcast : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { TODO() } }
PhoneBackup/app/src/main/java/tr/com/borabuyukbas/phonebackup/DummyBroadcast.kt
3141416963
package klees import io.kotest.core.spec.style.StringSpec class AllowOnlyPoliciesTest : StringSpec({ "basic policy" { data class Principal(val id: String = uuid()) data class Document(val createdBy: String) val authorizer = authorizationPolicy<Principal> { resourcePolicy<Document> { allow("read") { true } allow("write") { resource.createdBy == principal.id } } } val creatorId = uuid() val document = Document(creatorId) val creator = Principal(creatorId) val someOtherUser = Principal() authorizer.shouldAllow(creator, "read", document) authorizer.shouldAllow(creator, "write", document) authorizer.shouldAllow(someOtherUser, "read", document) authorizer.shouldNotAllow(someOtherUser, "write", document) } "policy with multiple resources" { data class Principal(val id: String = uuid()) data class Document(val createdBy: String) data class Folder(val createdBy: String) val authorizer = authorizationPolicy<Principal> { resourcePolicy<Document> { // Only owning user can read/write a document allow("read", "write") { resource.createdBy == principal.id } } resourcePolicy<Folder> { // Only owning user can add a document allow("add-document") { resource.createdBy == principal.id } } } val creatorId = uuid() val document = Document(creatorId) val folder = Folder(creatorId) val creator = Principal(creatorId) val someOtherUser = Principal() authorizer.shouldAllow(creator, "read", document) authorizer.shouldAllow(creator, "write", document) authorizer.shouldNotAllow(someOtherUser, "read", document) authorizer.shouldNotAllow(someOtherUser, "write", document) authorizer.shouldAllow(creator, "add-document", folder) authorizer.shouldNotAllow(someOtherUser, "add-document", document) } "allowAll" { data class Principal(val id: String, val role: String) data class Document(val createdBy: String) val authorizer = authorizationPolicy<Principal> { resourcePolicy<Document> { allow("read", "write") { resource.createdBy == principal.id } allowAll { principal.role == "admin" } } } val document = Document(createdBy = "creatorId") val creator = Principal("creatorId", "user") authorizer.shouldAllow(creator, "read", document) authorizer.shouldAllow(creator, "write", document) authorizer.shouldNotAllow(creator, "delete", document) val admin = Principal("adminId", "admin") authorizer.shouldAllow(admin, "read", document) authorizer.shouldAllow(admin, "write", document) authorizer.shouldAllow(admin, "delete", document) } "expenses" { data class Principal( val id: String, val role: UserRole, val department: String, val directReports: Set<String> = emptySet() ) data class Expense( val submittedBy: String, val sum: Long, val status: ExpenseStatus = ExpenseStatus.PENDING ) val authorizer = authorizationPolicy<Principal> { resourcePolicy<Expense> { // The only ones that can read are // - the user that created the Expense // - any user in Finance department // - any MANAGER to which the user reports to allow("read") { resource.submittedBy == principal.id || principal.department == "Finance" || (principal.role == UserRole.MANAGER && resource.submittedBy in principal.directReports) } // Only the user themselves can update an expense IF it's still PENDING allow("update") { principal.id == resource.submittedBy && resource.status == ExpenseStatus.PENDING } // Anyone in Finance can approve if the sum is <= 100, otherwise they have to be a MANAGER in Finance allow("approve") { principal.department == "Finance" && (resource.sum <= 100 || principal.role == UserRole.MANAGER) } // Admin can do anything allowAll { principal.role == UserRole.ADMIN } } } val submittedBy = uuid() val expense = Expense(submittedBy, 80) val largeExpense = Expense(submittedBy, 120) val submitter = Principal(submittedBy, UserRole.USER, "IT") val managerOfSubmitter = Principal(uuid(), UserRole.MANAGER, "IT", setOf(submittedBy)) val someOtherManager = Principal(uuid(), UserRole.MANAGER, "HR", setOf(uuid())) val someOtherUser = Principal(uuid(), UserRole.USER, "Ops", setOf(uuid())) val userInFinance = Principal(uuid(), UserRole.USER, "Finance") val managerInFinance = Principal(uuid(), UserRole.MANAGER, "Finance") authorizer.shouldAllow(submitter, "read", expense) authorizer.shouldAllow(userInFinance, "read", expense) authorizer.shouldAllow(managerInFinance, "read", expense) authorizer.shouldAllow(managerOfSubmitter, "read", expense) authorizer.shouldNotAllow(someOtherManager, "read", expense) authorizer.shouldNotAllow(someOtherUser, "read", expense) authorizer.shouldAllow(submitter, "update", expense) authorizer.shouldNotAllow(submitter, "update", Expense(submittedBy, 50, ExpenseStatus.APPROVED)) authorizer.shouldNotAllow(userInFinance, "update", expense) authorizer.shouldNotAllow(managerInFinance, "update", expense) authorizer.shouldNotAllow(managerOfSubmitter, "update", expense) authorizer.shouldNotAllow(someOtherManager, "update", expense) // Anyone in Finance can approve if the sum is <= 100, otherwise they have to be a MANAGER in Finance authorizer.shouldAllow(userInFinance, "approve", expense) authorizer.shouldAllow(managerInFinance, "approve", expense) authorizer.shouldNotAllow(userInFinance, "approve", largeExpense) authorizer.shouldAllow(managerInFinance, "approve", largeExpense) authorizer.shouldNotAllow(submitter, "approve", expense) authorizer.shouldNotAllow(managerOfSubmitter, "approve", expense) authorizer.shouldNotAllow(someOtherManager, "approve", expense) authorizer.shouldNotAllow(someOtherUser, "approve", expense) authorizer.shouldNotAllow(someOtherUser, "approve", expense) val admin = Principal(uuid(), UserRole.ADMIN, "Doesn't matter") authorizer.shouldAllow(admin, "read", expense) authorizer.shouldAllow(admin, "update", expense) authorizer.shouldAllow(admin, "approve", expense) authorizer.shouldAllow(admin, "approve", largeExpense) } }) { private enum class UserRole { USER, MANAGER, ADMIN } private enum class ExpenseStatus { PENDING, APPROVED } }
klees/klees-core/src/test/kotlin/klees/AllowOnlyPoliciesTest.kt
2718143611
package klees import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.mockk.spyk import io.mockk.verify import java.util.* fun <P : Any, R : Any> AuthorizationPolicy<P>.shouldAllow(principal: P, action: String, resource: R) { val authorizer = spyk(this) authorizer.check { principal can action(resource) } authorizer.check { principal.can(action, resource) } authorizer.checkAll(principal, resource, action) verify(exactly = 3) { authorizer.allowed(principal, action, resource) } authorizer.allowed(principal, action, resource) shouldBe true authorizer.allAllowed(principal, resource, action) shouldBe true } fun <P : Any, R : Any> AuthorizationPolicy<P>.shouldNotAllow(principal: P, action: String, resource: R) { val authorizer = spyk(this) shouldThrow<PermissionDeniedException> { authorizer.check { principal can action(resource) } } shouldThrow<PermissionDeniedException> { authorizer.check { principal.can(action, resource) } } shouldThrow<PermissionDeniedException> { authorizer.checkAll(principal, resource, action) } verify(exactly = 3) { authorizer.allowed(principal, action, resource) } authorizer.allowed(principal, action, resource) shouldBe false authorizer.allAllowed(principal, resource, action) shouldBe false } fun uuid(): String = UUID.randomUUID().toString()
klees/klees-core/src/test/kotlin/klees/test-utils.kt
3861170165
package klees import io.kotest.core.spec.style.StringSpec class Example : StringSpec({ "example" { data class Principal(val id: String, val role: String) data class Document(val ownerId: String, val locked: Boolean = false) val read = "read" val write = "write" // An authorization policy starts by specifying the principal type val authPolicy = authorizationPolicy<Principal> { // Derived roles are dynamically evaluated based on the principal and the resource being accessed derivedRoles<Document> { "owner" { resource.ownerId == principal.id } } // A resource policy describes principal permissions for actions against a resource type // Resource policies are built using allow(), allowAll(), deny() and denyAll() calls. // allow() and deny() take a vararg list of action names and a block defining the permission logic (returns Boolean) // allowAll / denyAll are used to blanket enable/disable all actions based on the described logic resourcePolicy<Document> { // Using the derived role defined above allow(write) { hasDerivedRole("owner") } // Use principal and resource fields to define the logic for the permission allowAll { principal.role == "ADMIN" && !resource.locked } // Use the p and r shorthand versions for lengthier expressions allow("archive") { (p.role == "ADMIN" || p.role == "MANAGER") && !r.locked } // Allow any principal to perform this action allow(read) { true } // Deny all actions when a document is locked. Deny always takes priority over a previously inferred allow. denyAll { resource.locked } } } val principal = Principal(uuid(), "USER") val document = Document(uuid()) // Use check() to throw an exception when the operation is not permitted authPolicy.check { principal can read(document) } // Use allowed() to get back a boolean instead of throwing an exception val allowed = authPolicy.allowed(principal, read, document) } })
klees/klees-core/src/test/kotlin/klees/Example.kt
3869066899
package klees import io.kotest.core.spec.style.StringSpec class AllowAndDenyPoliciesTest : StringSpec({ "deny based on resource state" { data class Principal(val id: String = uuid()) data class Document(val createdBy: String, val status: DocumentStatus) val authorizer = authorizationPolicy<Principal> { resourcePolicy<Document> { allow("read") { true } // Only the owner can delete allow("delete") { resource.createdBy == principal.id } // No one can delete a published document deny("delete") { resource.status == DocumentStatus.PUBLISHED } } } val creatorId = uuid() val creator = Principal(creatorId) val someOtherUser = Principal() authorizer.shouldAllow(creator, "read", Document(creatorId, DocumentStatus.DRAFT)) authorizer.shouldAllow(someOtherUser, "read", Document(creatorId, DocumentStatus.DRAFT)) authorizer.shouldAllow(creator, "delete", Document(creatorId, DocumentStatus.DRAFT)) authorizer.shouldNotAllow(someOtherUser, "delete", Document(creatorId, DocumentStatus.DRAFT)) // Deny takes precedence, even when the owner is the creator authorizer.shouldNotAllow(creator, "delete", Document(creatorId, DocumentStatus.PUBLISHED)) authorizer.shouldNotAllow(someOtherUser, "delete", Document(creatorId, DocumentStatus.PUBLISHED)) } "holidays" { data class Principal( val id: String = uuid(), val role: UserRole, val directReports: Set<String> = emptySet(), ) data class HolidayRequest( val requestedBy: String, val days: Int ) val authorizer = authorizationPolicy<Principal> { resourcePolicy<HolidayRequest> { // Only the owning user and their manager can read a holiday request allow("read") { (resource.requestedBy == principal.id) || (resource.requestedBy in principal.directReports) } // Only their manager can approve a holiday request allow("approve") { resource.requestedBy in principal.directReports } // No one can approve holidays that are longer than 15 days deny("approve") { resource.days > 15 } } } val requestedBy = uuid() val request = HolidayRequest(requestedBy, 10) val requester = Principal(requestedBy, UserRole.USER) val managerOfRequester = Principal(uuid(), UserRole.MANAGER, setOf(requestedBy)) val someOtherManager = Principal(uuid(), UserRole.MANAGER, setOf(uuid())) val someOtherUser = Principal(uuid(), UserRole.USER) authorizer.shouldAllow(requester, "read", request) authorizer.shouldAllow(managerOfRequester, "read", request) authorizer.shouldNotAllow(someOtherUser, "read", request) authorizer.shouldNotAllow(someOtherManager, "read", request) authorizer.shouldAllow(managerOfRequester, "approve", request) authorizer.shouldNotAllow(requester, "approve", request) authorizer.shouldNotAllow(someOtherUser, "approve", request) authorizer.shouldNotAllow(someOtherManager, "approve", request) authorizer.shouldNotAllow(requester, "approve", HolidayRequest(requestedBy, 20)) authorizer.shouldNotAllow(managerOfRequester, "approve", HolidayRequest(requestedBy, 16)) authorizer.shouldNotAllow(someOtherUser, "approve", HolidayRequest(requestedBy, 25)) authorizer.shouldNotAllow(someOtherManager, "approve", HolidayRequest(requestedBy, 20)) } }) { private enum class DocumentStatus { DRAFT, PUBLISHED } private enum class UserRole { USER, MANAGER } }
klees/klees-core/src/test/kotlin/klees/AllowAndDenyPoliciesTest.kt
1613469746
package klees import io.kotest.core.spec.style.StringSpec class DerivedRolesTest : StringSpec({ "document owner" { data class Principal(val id: String = uuid()) data class Document( val createdBy: String, val collaborators: Set<String> = emptySet() ) val authorizer = authorizationPolicy<Principal> { derivedRoles<Document> { "owner" { principal.id == resource.createdBy } "collaborator" { principal.id in resource.collaborators } } resourcePolicy<Document> { // Anyone can read allow("read") { true } // Only owner and collaborators can write allow("write") { hasDerivedRole("owner") || hasDerivedRole("collaborator") } // Only the owner can archive it allow("archive") { "owner" in derivedRoles } } } val ownerId = uuid() val collaboratorId = uuid() val owner = Principal(ownerId) val collaborator = Principal(collaboratorId) val document = Document(ownerId, setOf(collaboratorId)) val someOtherUser = Principal() authorizer.shouldAllow(owner, "read", document) authorizer.shouldAllow(collaborator, "read", document) authorizer.shouldAllow(someOtherUser, "read", document) authorizer.shouldAllow(owner, "write", document) authorizer.shouldAllow(collaborator, "write", document) authorizer.shouldNotAllow(someOtherUser, "write", document) authorizer.shouldAllow(owner, "archive", document) authorizer.shouldNotAllow(collaborator, "archive", document) authorizer.shouldNotAllow(someOtherUser, "archive", document) } })
klees/klees-core/src/test/kotlin/klees/DerivedRolesTest.kt
3473631511
package klees import io.kotest.core.spec.style.StringSpec class OrdersTest : StringSpec({ "online order management" { data class Order( val status: OrderStatus, var customerId: String, var handlingEmployee: String? = null, var courier: String? = null, ) data class Principal( val id: String, val role: UserRole, ) val checkoutOrder = "checkoutOrder" val cancelOrder = "cancelOrder" val dispatchOrder = "dispatchOrder" val markOrderOutForDelivery = "markOrderOutForDelivery" val markOrderDelivered = "markOrderDelivered" val orderCustomer = "orderCustomer" val orderHandler = "orderHandler" val orderCourier = "orderCourier" val authorizer = authorizationPolicy<Principal> { derivedRoles<Order> { orderCustomer { resource.customerId == principal.id } orderHandler { resource.handlingEmployee == principal.id } orderCourier { resource.courier == principal.id } } resourcePolicy<Order> { // Only a customer can check out an order and only if it's in a DRAFT state allow(checkoutOrder) { principal.role == UserRole.CUSTOMER && resource.status == OrderStatus.DRAFT } // Only the customer and the handling employee can cancel an order allow(cancelOrder) { hasAnyDerivedRole(orderCustomer, orderHandler) } // Orders can't be cancelled when dispatched, out for delivery, delivered deny(cancelOrder) { resource.status in setOf( OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED ) } // Only the employee handling the order can dispatch it, and not if it has payment issues allow(dispatchOrder) { hasDerivedRole(orderHandler) && resource.status != OrderStatus.PAYMENT_ISSUE } // Only the courier for this order can mark order as out for delivery or delivered allow(markOrderOutForDelivery, markOrderDelivered) { principal.id == resource.courier } // No one can do anything with an order once it's delivered denyAll { resource.status == OrderStatus.DELIVERED } } } val customerId = uuid() val customer = Principal(customerId, UserRole.CUSTOMER) val handlingEmployee = Principal(uuid(), UserRole.EMPLOYEE) val otherEmployee = Principal(uuid(), UserRole.EMPLOYEE) val courier = Principal(uuid(), UserRole.COURIER) val otherCourier = Principal(uuid(), UserRole.COURIER) fun AuthorizationPolicy<Principal>.shouldNotAllowStatuses(principal: Principal, action: String, vararg orderStatuses: OrderStatus) { orderStatuses.forEach { this.shouldNotAllow(principal, action, Order(it, customerId, handlingEmployee.id, courier.id)) } } fun AuthorizationPolicy<Principal>.shouldNotAllowAnyStatus(principal: Principal, action: String) { OrderStatus.entries.forEach { this.shouldNotAllow(principal, action, Order(it, customerId, handlingEmployee.id, courier.id)) } } // Only a customer can check out an order and only if it's in a DRAFT state authorizer.shouldAllow(customer, checkoutOrder, Order(OrderStatus.DRAFT, customerId)) authorizer.shouldNotAllow(customer, checkoutOrder, Order(OrderStatus.CHECKED_OUT, customerId)) authorizer.shouldNotAllow(customer, checkoutOrder, Order(OrderStatus.PROCESSING, customerId)) authorizer.shouldNotAllowAnyStatus(handlingEmployee, checkoutOrder) authorizer.shouldNotAllowAnyStatus(otherEmployee, checkoutOrder) authorizer.shouldNotAllowAnyStatus(courier, checkoutOrder) authorizer.shouldNotAllowAnyStatus(otherCourier, checkoutOrder) // Only the customer and the handling employee can cancel an order authorizer.shouldAllow(customer, cancelOrder, Order(OrderStatus.CHECKED_OUT, customerId)) authorizer.shouldAllow(handlingEmployee, cancelOrder, Order(OrderStatus.CHECKED_OUT, customerId, handlingEmployee.id)) authorizer.shouldNotAllowAnyStatus(otherEmployee, cancelOrder) authorizer.shouldNotAllowAnyStatus(courier, cancelOrder) authorizer.shouldNotAllowAnyStatus(otherCourier, cancelOrder) // Orders can't be cancelled when dispatched, out for delivery, delivered authorizer.shouldNotAllowStatuses(customer, cancelOrder, OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED) authorizer.shouldNotAllowStatuses(handlingEmployee, cancelOrder, OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED) authorizer.shouldNotAllowStatuses(otherEmployee, cancelOrder, OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED) authorizer.shouldNotAllowStatuses(courier, cancelOrder, OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED) authorizer.shouldNotAllowStatuses(otherCourier, cancelOrder, OrderStatus.DISPATCHED, OrderStatus.OUT_FOR_DELIVERY, OrderStatus.DELIVERED) // Only the employee handling the order can dispatch it, and not if it has payment issues authorizer.shouldAllow(handlingEmployee, dispatchOrder, Order(OrderStatus.PROCESSING, customerId, handlingEmployee.id)) authorizer.shouldNotAllow(otherEmployee, dispatchOrder, Order(OrderStatus.PROCESSING, customerId, handlingEmployee.id)) authorizer.shouldNotAllow(handlingEmployee, dispatchOrder, Order(OrderStatus.PAYMENT_ISSUE, customerId, handlingEmployee.id)) // Only the courier for this order can mark order as out for delivery or delivered val fullOrder = Order(OrderStatus.DISPATCHED, customerId, handlingEmployee.id, courier.id) authorizer.shouldAllow(courier, markOrderOutForDelivery, fullOrder) authorizer.shouldAllow(courier, markOrderDelivered, fullOrder) authorizer.shouldNotAllow(otherCourier, markOrderOutForDelivery, fullOrder) authorizer.shouldNotAllow(otherCourier, markOrderDelivered, fullOrder) authorizer.shouldNotAllow(handlingEmployee, markOrderDelivered, fullOrder) fun AuthorizationPolicy<Principal>.shouldNotAllowAnyActionWhenDelivered(principal: Principal) { this.shouldNotAllow(principal, checkoutOrder, Order(OrderStatus.DELIVERED, customerId, handlingEmployee.id, courier.id)) this.shouldNotAllow(principal, cancelOrder, Order(OrderStatus.DELIVERED, customerId, handlingEmployee.id, courier.id)) this.shouldNotAllow(principal, dispatchOrder, Order(OrderStatus.DELIVERED, customerId, handlingEmployee.id, courier.id)) this.shouldNotAllow(principal, markOrderOutForDelivery, Order(OrderStatus.DELIVERED, customerId, handlingEmployee.id, courier.id)) this.shouldNotAllow(principal, markOrderDelivered, Order(OrderStatus.DELIVERED, customerId, handlingEmployee.id, courier.id)) } // No one can do anything with an order once it's delivered authorizer.shouldNotAllowAnyActionWhenDelivered(customer) authorizer.shouldNotAllowAnyActionWhenDelivered(handlingEmployee) authorizer.shouldNotAllowAnyActionWhenDelivered(otherEmployee) authorizer.shouldNotAllowAnyActionWhenDelivered(courier) authorizer.shouldNotAllowAnyActionWhenDelivered(otherCourier) } }) { private enum class UserRole { CUSTOMER, EMPLOYEE, COURIER } private enum class OrderStatus { DRAFT, // The customer is still choosing items CHECKED_OUT, // The customer sent the order to the company (finished buying online) CANCELLED, // The customer or the company cancelled the order (customer changed their mind, or company doesn't have it in stock) PAYMENT_ISSUE, // The company found problems with the order payment (card rejected, etc.) PROCESSING, // The company is reviewing the order, confirming stock, packaging, etc DISPATCHED, // The order is dispatched OUT_FOR_DELIVERY, // The order is out for delivery to the customer DELIVERED, // The courier had to re-arrange delivery to customer } }
klees/klees-core/src/test/kotlin/klees/OrdersTest.kt
3432434128
package klees import kotlin.reflect.KClass class PermissionDeniedException(message: String) : RuntimeException(message) fun <Principal : Any> authorizationPolicy(init: AuthorizationPolicy<Principal>.() -> Unit): AuthorizationPolicy<Principal> { val authorizer = AuthorizationPolicy<Principal>() init(authorizer) return authorizer } class AuthorizationPolicy<Principal : Any> { private val resourcePolicies = mutableMapOf<KClass<*>, ResourcePolicy<Principal, *>>() private val resourceDerivedRolesPolicies = mutableMapOf<KClass<*>, ResourceDerivedRolesPolicy<Principal, *>>() inline fun <reified Resource : Any> derivedRoles(init: ResourceDerivedRolesPolicy<Principal, Resource>.() -> Unit) { val derivedRole = ResourceDerivedRolesPolicy<Principal, Resource>() init(derivedRole) addDerivedRole(Resource::class, derivedRole) } inline fun <reified Resource : Any> resourcePolicy(init: ResourcePolicy<Principal, Resource>.() -> Unit) { val policy = ResourcePolicy<Principal, Resource>() init(policy) addPolicy(Resource::class, policy) } fun <Resource : Any> addPolicy(cls: KClass<Resource>, policy: ResourcePolicy<Principal, Resource>) { resourcePolicies[cls] = policy } fun <Resource : Any> addDerivedRole(cls: KClass<Resource>, derivedRole: ResourceDerivedRolesPolicy<Principal, Resource>) { resourceDerivedRolesPolicies[cls] = derivedRole } /** * Returns a boolean indicating whether the principal is allowed the specified action against the resource. * Use this method when you wish to perform a permission check and handle a boolean value rather than an exception. */ fun <Resource : Any> allowed(principal: Principal, action: String, resource: Resource): Boolean { val resourcePolicy = resourcePolicies[resource::class] ?: throw IllegalArgumentException("No policies found for class ${resource::class}") val derivedRolesForResource = resourceDerivedRolesPolicies[resource::class] as ResourceDerivedRolesPolicy<Principal, Resource>? val derivedRoles = derivedRolesForResource?.getDerivedRoles(principal, resource) ?: emptySet() return (resourcePolicy as ResourcePolicy<Principal, Resource>).allowed(principal, resource, action, derivedRoles) } fun <Resource : Any> allAllowed(principal: Principal, resource: Resource, vararg actions: String): Boolean { return actions.all { allowed(principal, it, resource) } } /** * Checks that the action by the principal is allowed against the resource. * Throws a [PermissionDeniedException] when the action is not allowed. * Use this method when you wish to perform a permission check and throw an exception. */ @Throws(PermissionDeniedException::class) fun <Resource : Any> check(principal: Principal, action: String, resource: Resource) { if (!allowed(principal, action, resource)) { throw PermissionDeniedException("Action not allowed") } } fun <Resource : Any> checkAll(principal: Principal, resource: Resource, vararg actions: String) { actions.forEach { check(principal, it, resource) } } fun check(block: AuthorizationPolicy<Principal>.() -> PermissionCheck<Principal>) { check(block(this)) } private fun check(check: PermissionCheck<Principal>) { check( principal = check.principal, action = check.action, resource = check.resource ) } infix fun Principal.can(resourceAction: ResourceAction): PermissionCheck<Principal> { return PermissionCheck(this, resourceAction) } fun Principal.can(vararg actions: ResourceAction): Collection<PermissionCheck<Principal>> { return actions.map { PermissionCheck(this, it) } } fun Principal.can(action: String, resource: Any): PermissionCheck<Principal> { return PermissionCheck(this, action, resource) } infix operator fun String.invoke(resource: Any): ResourceAction { return ResourceAction(resource, this) } } data class ResourceAction(val resource: Any, val action: String) data class PermissionCheck<Principal : Any>( val principal: Principal, val action: String, val resource: Any ) { constructor(principal: Principal, resourceAction: ResourceAction) : this( principal = principal, action = resourceAction.action, resource = resourceAction.resource ) }
klees/klees-core/src/main/kotlin/klees/authorization-policy.kt
3393301895
package klees class ResourceDerivedRoleContext<Principal : Any, Resource : Any>( val principal: Principal, val resource: Resource, ) { val p: Principal = principal val r: Resource = resource } typealias ResourceDerivedRoleCondition<Principal, Resource> = ResourceDerivedRoleContext<Principal, Resource>.() -> Boolean class ResourceDerivedRolesPolicy<Principal : Any, Resource : Any> { private val rules = mutableListOf<Rule<Principal, Resource>>() operator fun String.invoke(condition: ResourceDerivedRoleCondition<Principal, Resource>) { rules.add(Rule(this, condition)) } fun getDerivedRoles(principal: Principal, resource: Resource): Set<String> { val context = ResourceDerivedRoleContext(principal, resource) return rules.filter { it.condition(context) }.map { it.role }.toSet() } class Rule<Principal : Any, Resource : Any>( val role: String, val condition: ResourceDerivedRoleCondition<Principal, Resource> ) }
klees/klees-core/src/main/kotlin/klees/derived-roles.kt
2347053174
package klees private typealias ActionCondition<Principal, Resource> = ActionContext<Principal, Resource>.() -> Boolean private typealias ActionMatcher = (String) -> Boolean class ActionContext<Principal : Any, Resource : Any>( val principal: Principal, val resource: Resource, val derivedRoles: Set<String> ) { val p: Principal = principal val r: Resource = resource fun hasDerivedRole(derivedRole: String): Boolean { return derivedRoles.contains(derivedRole) } fun hasAnyDerivedRole(vararg derivedRoles: String): Boolean { return derivedRoles.any { hasDerivedRole(it) } } } class ResourcePolicy<Principal : Any, Resource : Any> { private val rules = mutableListOf<Rule<Principal, Resource>>() fun allow(vararg actions: String, condition: ActionCondition<Principal, Resource>) { rules.add(Rule({ it in actions }, condition, Rule.Effect.ALLOW)) } fun allowAll(condition: ActionCondition<Principal, Resource>) { rules.add(Rule({ true }, condition, Rule.Effect.ALLOW)) } fun denyAll(condition: ActionCondition<Principal, Resource>) { rules.add(Rule({ true }, condition, Rule.Effect.DENY)) } fun deny(vararg actions: String, condition: ActionCondition<Principal, Resource>) { rules.add(Rule({ it in actions }, condition, Rule.Effect.DENY)) } fun allowed(principal: Principal, resource: Resource, action: String, derivedRoles: Set<String>): Boolean { val actionContext = ActionContext(principal, resource, derivedRoles) val matchingRules = rules.filter { it.matchesContext(action, actionContext) } // If no rules match then this action should be denied if (matchingRules.isEmpty()) { return false } // Only return true if none of the rules are of type DENY return matchingRules.none { it.effect == Rule.Effect.DENY } } class Rule<Principal : Any, Resource : Any>( val actionMatcher: ActionMatcher, val condition: ActionCondition<Principal, Resource>, val effect: Effect ) { fun matchesContext(action: String, context: ActionContext<Principal, Resource>): Boolean { return actionMatcher(action) && condition(context) } enum class Effect { ALLOW, DENY } } }
klees/klees-core/src/main/kotlin/klees/resource-policy.kt
2568220504
package com.example.gasto_calorico_and_imc import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.gasto_calorico_and_imc", appContext.packageName) } }
gasto-calorico-and-imc/app/src/androidTest/java/com/example/gasto_calorico_and_imc/ExampleInstrumentedTest.kt
3843501215
package com.example.gasto_calorico_and_imc import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
gasto-calorico-and-imc/app/src/test/java/com/example/gasto_calorico_and_imc/ExampleUnitTest.kt
1455494408
package com.example.gasto_calorico_and_imc import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { private lateinit var btnIMC: Button; private lateinit var btnCaloricLoss: Button; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnIMC = findViewById(R.id.btn_imc); btnIMC.setOnClickListener{ val intent = Intent(this, IMCActivity::class.java); startActivity(intent) } btnCaloricLoss = findViewById(R.id.btn_caloric_loss); btnCaloricLoss.setOnClickListener{ val intent = Intent(this, CaloricLossActivity::class.java); startActivity(intent) } } }
gasto-calorico-and-imc/app/src/main/java/com/example/gasto_calorico_and_imc/MainActivity.kt
3640317109
package com.example.gasto_calorico_and_imc import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ImageView import android.widget.Spinner import android.widget.TextView class CaloricLossActivity : AppCompatActivity() { private lateinit var editAge: EditText private lateinit var editWeight: EditText private lateinit var textResult: TextView var selectedActivity = "" var gender = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_caloric_loss) editAge = findViewById(R.id.value_age) editWeight = findViewById(R.id.value_weight_caloric) textResult = findViewById(R.id.result_caloric_loss) val selectPhysicalActivity = findViewById<Spinner>(R.id.selectPhysicalActivity) val optionsPhysicalActivities = arrayOf("Leve", "Moderado", "Intenso") val adapter = ArrayAdapter(this, R.layout.spinner_item_layout, optionsPhysicalActivities) selectPhysicalActivity.adapter = adapter; selectPhysicalActivity.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long) { selectedActivity = optionsPhysicalActivities[position] } override fun onNothingSelected(p0: AdapterView<*>?) {} } } fun selectedMan(view: View) { val imgMan: ImageView = findViewById(R.id.select_man) val imgWoman: ImageView = findViewById(R.id.select_woman) imgMan.setImageResource(R.drawable.selected_man) imgWoman.setImageResource(R.drawable.woman) gender = "man" } fun selectedWoman(view: View) { val imgMan: ImageView = findViewById(R.id.select_man) val imgWoman: ImageView = findViewById(R.id.select_woman) imgMan.setImageResource(R.drawable.man) imgWoman.setImageResource(R.drawable.selected_woman) gender = "woman" } private fun basalEnergetic(age: Int, gender: String, weight: Double): Double { // man if (age in 1..2 && gender == "man") { return (59.512 / 1000 * weight) - (304 / 10) } else if (age in 3..9 && gender == "man") { return (22706 / 1000 * weight) + (5043 / 10) } else if (age in 10..17 && gender == "man") { return (17686 / 1000 * weight) + (6582 / 10) } else if (age in 18..30 && gender == "man") { return (15057 / 1000 * weight) + (69224 / 100) } else if (age in 31..60 && gender == "man") { return (11472 / 1000 * weight) + (8731 / 10) } else if (age > 60 && gender == "man") { return (11711 / 1000 * weight) + (5877 / 10) } // woman else if (age in 1..2 && gender == "woman") { return (58317 / 1000 * weight) - (311 / 10) } else if (age in 3..9 && gender == "woman") { return (20315 / 1000 * weight) + (4859 / 10) } else if (age in 10..17 && gender == "woman") { return (13384 / 1000 * weight) + (6926 / 10) } else if (age in 18..30 && gender == "woman") { return (14818 / 1000 * weight) + (4866 / 10) } else if (age in 31..60 && gender == "woman") { return (8126 / 1000 * weight) + (8456 / 10) } else if (age > 60 && gender == "woman") { return (9082 / 1000 * weight) + (6585 / 10) } else { return 0.0 } } private fun activityFactor(basalValue: Double): Double { if (selectedActivity == "Leve") { return basalValue * 1.55 } else if (selectedActivity == "Moderado") { return basalValue * 1.84 } else { return basalValue * 2.2 } } fun calculateCaloricLoss(view: View) { val age = editAge.text.toString().toIntOrNull() ?: 0 val weight = editWeight.text.toString().toDoubleOrNull() ?: 0.0 val resultBasalEnergetic = basalEnergetic(age, gender, weight) val resultActivityFactor = activityFactor(resultBasalEnergetic) textResult.text = "Seu gasto calΓ³rico estimado Γ©: ${resultActivityFactor.toInt()}kcal por dia" textResult.setTextColor(Color.parseColor("#0000FF")); } }
gasto-calorico-and-imc/app/src/main/java/com/example/gasto_calorico_and_imc/CaloricLossActivity.kt
2419731990
package com.example.gasto_calorico_and_imc import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView class IMCActivity : AppCompatActivity() { private lateinit var editWeight: EditText private lateinit var editHeight: EditText private lateinit var textResult: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_imc_activity) editWeight = findViewById(R.id.value_weight) editHeight = findViewById(R.id.value_height) textResult = findViewById(R.id.result_imc) } fun calculateIMC(view: View) { val weight = editWeight.text.toString().toDoubleOrNull() ?: 0.0 val height = editHeight.text.toString().toDoubleOrNull() ?: 0.0 val imc = weight / (height * height) val result = when { imc < 18.5 -> "O resultado do seu IMC: Baixo" imc in 18.5..24.9 -> "O resultado do seu IMC: Normal" imc in 25.0..29.9 -> "O resultado do seu IMC: Sobrepeso" imc > 29.9 -> "O resultado do seu IMC: Obeso" else -> "Error! Verifique novamente os valores informados" } textResult.text = result textResult.setTextColor(Color.parseColor("#0000FF")); } }
gasto-calorico-and-imc/app/src/main/java/com/example/gasto_calorico_and_imc/IMCActivity.kt
1090202454
package com.example.joinu.member.service import com.example.joinu.common.authority.JwtTokenProvider import com.example.joinu.common.status.Gender import com.example.joinu.common.status.ROLE import com.example.joinu.event.dto.EventDto import com.example.joinu.member.dto.MemberDtoRequest import com.example.joinu.member.dto.MemberDtoResponse import com.example.joinu.member.entity.Member import com.example.joinu.member.entity.MemberRole import com.example.joinu.member.repository.MemberRepository import com.example.joinu.member.repository.MemberRoleRepository import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.be import io.kotest.matchers.should import io.mockk.* import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.impl.annotations.SpyK import org.assertj.core.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.data.repository.findByIdOrNull import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.crypto.password.PasswordEncoder import java.time.LocalDate import java.util.* import kotlin.collections.List private var memberRepository: MemberRepository = mockk(relaxed = true) private var memberRoleRepository: MemberRoleRepository = mockk(relaxed = true) private var authenticationManagerBuilder: AuthenticationManagerBuilder = mockk() private var jwtTokenProvider: JwtTokenProvider = mockk() private var passwordEncoder: PasswordEncoder = mockk(relaxed = true) @InjectMockKs var memberService: MemberService = MemberService( memberRepository, memberRoleRepository, authenticationManagerBuilder, jwtTokenProvider, passwordEncoder ) class MemberServiceTest : BehaviorSpec({ Given("νšŒμ›κ°€μž… ν…ŒμŠ€νŠΈ") { val memberSignupDto = MemberDtoRequest( id = null, _loginId = "ν…ŒμŠ€νŠΈ_둜그인_아이디", _password = "password123!", _name = "ν…ŒμŠ€νŠΈ_이름", _birthDate = LocalDate.now().toString(), _gender = Gender.MAN.toString(), _email = "[email protected]", ) val member = Member( id = 1L, loginId = "ν…ŒμŠ€νŠΈ_아이디", password = "ν…ŒμŠ€νŠΈ_λΉ„λ°€λ²ˆν˜Έ", name = "ν…ŒμŠ€νŠΈ_이름", birthDate = LocalDate.now(), gender = Gender.MAN, email = "ν…ŒμŠ€νŠΈ_이메일", ) val memberRole = MemberRole(role = ROLE.MEMBER, member = member) every { memberRepository.findByLoginId("ν…ŒμŠ€νŠΈ_둜그인_아이디") } returns null every { memberRepository.save(any()) } returns member every { memberRoleRepository.save(any()) } returns memberRole When("μœ μ € νšŒμ› κ°€μž…μ„ μ§„ν–‰ν•˜λ©΄") { val result = memberService.signUp(memberSignupDto) Then("μ •μƒμ μœΌλ‘œ νšŒμ› κ°€μž…μ΄ μ§„ν–‰λ˜μ–΄μ•Όν•œλ‹€.") { result should be("νšŒμ›κ°€μž…μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } } } }) //class MemberServiceTest:BehaviorSpe { // // // @BeforeEach // fun setUp() { // MockKAnnotations.init(this, relaxed = true) // } // // @Test // fun testMockk() { // // νšŒμ› 생성 // val member = MemberDtoResponse( // id = 100L, // loginId = "ν…ŒμŠ€νŠΈ 둜그인 아이디", // name = "ν…ŒμŠ€νŠΈ 이름", // birthDate = "2024-03-04", // κ³ μ •λœ λ‚ μ§œ μ‚¬μš© // gender = Gender.MAN.toString(), // email = "[email protected]", // roles = listOf(ROLE.MEMBER) // ) // val member1 = Member( // id = 100L, // loginId = "ν…ŒμŠ€νŠΈ 둜그인 아이디", // password = "ν…ŒμŠ€νŠΈ λΉ„λ°€λ²ˆν˜Έ", // name = "ν…ŒμŠ€νŠΈ 이름", // birthDate = LocalDate.now(), // κ³ μ •λœ λ‚ μ§œ μ‚¬μš© // gender = Gender.MAN, // email = "[email protected]", // ) // every { memberRepository.findByIdOrNull(100L) } returns member1 // // val result = memberService.searchMyInfo(100L) // // // signUp λ©”μ„œλ“œκ°€ ν•œ 번 ν˜ΈμΆœλ˜μ—ˆλŠ”μ§€ 확인 // verify(exactly = 1) { memberRepository.findByIdOrNull(100L) } // // confirmVerified(memberRepository) // // } // //// @Test //// fun whenGetBankAccount_thenReturnBankAccount() { //// var member = Member( //// id = 1, //// loginId = "test", //// password = "password123!", //// name = "Test User", //// birthDate = LocalDate.now(), //// gender = Gender.MAN, //// email = "[email protected]", //// ) //// memberRepository.save(member) //// member = memberRepository.findByLoginId("test")!! //// //given //// every { memberRepository.findByIdOrNull(1) } returns member; //// //// //when //// val result = memberRepository.getReferenceById(1); //// //// //then //// verify(exactly = 1) { memberRepository.findByIdOrNull(1) }; //// assertEquals(member, result) //// } //// //// @Test //// fun 멀버_생성() { //// //given //// val memberLoginId = "test_user" //// val member = MemberDtoRequest( //// id = null, //// _loginId = memberLoginId, //// _password = "password123!", //// _name = "Test User", //// _birthDate = LocalDate.now().toString(), //// _gender = Gender.MAN.toString(), //// _email = "[email protected]", //// ) //// //// //when //// memberService.signUp(member) //// val savedMember = memberRepository.findByLoginId(memberLoginId) //// //// //then ////// verify(exactly==1) { memberRepository.findByLoginId(memberLoginId) } //// if (savedMember != null) { //// Assertions.assertThat(member.id).isEqualTo(savedMember.id) //// } //// } //}
Joint-Schedule-Service/backend/src/test/kotlin/com/example/joinu/member/service/MemberServiceTest.kt
1261024140
package com.example.joinu import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class JoinUApplicationTests { @Test fun contextLoads() { } }
Joint-Schedule-Service/backend/src/test/kotlin/com/example/joinu/JoinUApplicationTests.kt
1422452264
package com.example.joinu.event.controller import com.example.joinu.event.entity.Event import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import java.time.LocalDateTime class EventControllerTest { }
Joint-Schedule-Service/backend/src/test/kotlin/com/example/joinu/event/controller/EventControllerTest.kt
2319344049
package com.example.joinu.event.service import com.example.joinu.common.status.Gender import com.example.joinu.event.dto.EventDto import com.example.joinu.event.entity.Event import com.example.joinu.event.entity.MemberEvent import com.example.joinu.event.repository.EventRepository import com.example.joinu.event.repository.MemberEventRepository import com.example.joinu.member.entity.Member import com.example.joinu.member.repository.MemberRepository import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.ArgumentMatchers.any import org.mockito.BDDMockito.given import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.jupiter.MockitoExtension import org.springframework.security.crypto.password.PasswordEncoder import java.time.LocalDate import java.time.LocalDateTime import java.util.* @ExtendWith(MockitoExtension::class) class EventServiceTest { @Mock private lateinit var eventRepository: EventRepository @Mock private lateinit var memberEventRepository: MemberEventRepository @Mock private lateinit var memberRepository: MemberRepository @InjectMocks private lateinit var eventService: EventService @Test fun `test create event`() { //given val member = Member( loginId = "test_user", password = "password123!", name = "Test User", birthDate = LocalDate.now(), gender = Gender.MAN, email = "[email protected]" ) val eventDto = EventDto( event_id = null, title = "Test Event", start = Date(), end = Date(), color = "#FF0000", disabled = false, editable = true, deletable = true, allDay = false ) //when val savedMember = memberRepository.save(member) val savedMemberId = savedMember.id eventService.create(eventDto, savedMemberId!!) val eventList = memberRepository.findEventsByMemberId(savedMemberId) //then assertTrue(eventList.isNotEmpty()) assertTrue(eventList.any { it.title == eventDto.title }) } }
Joint-Schedule-Service/backend/src/test/kotlin/com/example/joinu/event/service/EventServiceTest.kt
2062278200
package com.example.joinu.calendars.dto import com.example.joinu.calendars.entity.CalendarEvent import com.example.joinu.common.status.Category import java.util.Date data class CalendarListDtoResponse( val calendarId: Long, val category: Category, val name: String, val author: String, val description: String, val color: String ) /** * List of calendar ID */ data class CalendarEventsDtoQRequest( val calendar_id: List<Long> ) data class CalendarEventsDtoResponse( val title: String, val description: String, val start: Date, val end: Date, val calendar: String = "", ) data class CreateCalendarDtoRequest( val category: String, val name: String, val description: String, val color: String, val events: List<CreateCalendarEventsDto> ) data class CreateCalendarEventsDto( val eventId: Int, val title: String, val description: String, val start: Date, val end: Date, ) { fun toEntity(): CalendarEvent = CalendarEvent( title = title, description = description, start = start, end = end ) }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/calendars/dto/CalendarsDtos.kt
2571856747
package com.example.joinu.calendars.repository import com.example.joinu.calendars.entity.CalendarEvent import com.example.joinu.calendars.entity.Calendars import org.springframework.data.jpa.repository.JpaRepository interface CalendarsRepository : JpaRepository<Calendars, Long> { } interface CalendarEventRepository : JpaRepository<CalendarEvent, Long> { }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/calendars/repository/CalendarsRepositories.kt
2889195758
package com.example.joinu.calendars.entity import com.example.joinu.calendars.dto.CalendarEventsDtoResponse import com.example.joinu.calendars.dto.CalendarListDtoResponse import com.example.joinu.common.status.Category import com.example.joinu.common.status.Const.DEFAULT_COLOR import jakarta.persistence.* import java.util.* /** * Repersents a calendar that can be subscribed. * @property id Identitier for the calendar * @property category Category of the calendar (school, sports, study, daily, etc..) * @property name The name of calendar * @property author The Author name (member login Id) of calendar * @property description Description of Calendar * @property events Events belong the calendar */ @Entity class Calendars( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, @Enumerated(EnumType.STRING) val category: Category = Category.DAILY, val name: String = "", val author: String = "", val description: String = "", val color: String = DEFAULT_COLOR, @OneToMany(fetch = FetchType.LAZY, mappedBy = "calendars") val events: List<CalendarEvent> = ArrayList(), ) { fun toCalendarListDtoResponse(): CalendarListDtoResponse = CalendarListDtoResponse(id!!, category, name, author, description, color) } /** * Represents an event in a calendar. * @property id The unique identifier for the event. * @property calendars The id of Calendar these events belong to. * @property title The title of the event. * @property description The description of the event. * @property start The start date and time of the event. * @property end The end date and time of the event. */ @Entity class CalendarEvent( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @ManyToOne(fetch = FetchType.LAZY) var calendars: Calendars? = null, @Column(nullable = false, length = 100) var title: String, @Column var description: String, @Column var start: Date, @Column var end: Date, ) { fun toCalendarEventsDtoResponse(): CalendarEventsDtoResponse = CalendarEventsDtoResponse(title, description, start, end) }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/calendars/entity/CalendarsEntities.kt
3098860275
package com.example.joinu.calendars.controller import com.example.joinu.calendars.dto.CalendarEventsDtoQRequest import com.example.joinu.calendars.dto.CalendarEventsDtoResponse import com.example.joinu.calendars.dto.CalendarListDtoResponse import com.example.joinu.calendars.dto.CreateCalendarDtoRequest import com.example.joinu.calendars.service.CalendarsService import com.example.joinu.common.dto.BaseResponse import com.example.joinu.common.exception.InvalidInputException import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/api/calendars") class CalendarsController( private val calendarsService: CalendarsService ) { /** * Get All Calendar List by CalendarListDtoResponse * * @return List of CalendarListDtoResponse */ @GetMapping() fun getCalendars(): BaseResponse<List<CalendarListDtoResponse>> { val result = calendarsService.getCalendars() return BaseResponse(data = result) } /** * Get Calendar Events by Calendar Id */ @GetMapping("/events/{calendarId}") fun getCalendarsEventsById(@PathVariable calendarId: Long): BaseResponse<List<CalendarEventsDtoResponse>> { val calendarEvents = calendarsService.getCalendarEventsById(calendarId) return BaseResponse(data = calendarEvents) } /** * Get Calendar Events by List of Calendar */ @PostMapping("/events") fun getCalendarEvents(@RequestBody calendarEventsDtoQRequest: CalendarEventsDtoQRequest): BaseResponse<MutableList<CalendarEventsDtoResponse>> { val calendarEvents = calendarsService.getCalendarEvents(calendarEventsDtoQRequest) return BaseResponse(data = calendarEvents) } /** * Create Calendar * * @param createCalendarDtoRequest * @return return result message */ @PostMapping("/create") fun createCalendar(@RequestBody createCalendarDtoRequest: CreateCalendarDtoRequest): BaseResponse<String> { val result = calendarsService.createCalendar(createCalendarDtoRequest) return BaseResponse(message = result) } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/calendars/controller/CalendarsController.kt
3365689781
package com.example.joinu.calendars.service import com.example.joinu.calendars.dto.CalendarEventsDtoQRequest import com.example.joinu.calendars.dto.CalendarEventsDtoResponse import com.example.joinu.calendars.dto.CalendarListDtoResponse import com.example.joinu.calendars.dto.CreateCalendarDtoRequest import com.example.joinu.calendars.entity.Calendars import com.example.joinu.calendars.repository.CalendarEventRepository import com.example.joinu.calendars.repository.CalendarsRepository import com.example.joinu.common.dto.CustomUser import com.example.joinu.common.exception.InvalidInputException import com.example.joinu.common.status.Category import com.example.joinu.common.status.Const.DEFAULT_COLOR import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Service @Service class CalendarsService( private val calendarsRepository: CalendarsRepository, private val calendarsEventRepository: CalendarEventRepository, ) { /** * Get All Calendar List by CalendarListDtoResponse */ fun getCalendars(): List<CalendarListDtoResponse> { val CalendarList = calendarsRepository.findAll() return CalendarList.map { it.toCalendarListDtoResponse() } } /** * Get Calendar Events by List of Calendar */ fun getCalendarEvents(calendarEventsDtoQRequest: CalendarEventsDtoQRequest): MutableList<CalendarEventsDtoResponse> { val result: MutableList<CalendarEventsDtoResponse> = mutableListOf() calendarEventsDtoQRequest.calendar_id.forEach { val calendar = calendarsRepository.findById(it).orElseThrow { InvalidInputException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μΊ˜λ¦°λ” μ•„μ΄λ””μž…λ‹ˆλ‹€.") } val responseEvents = calendar.events.map { it.toCalendarEventsDtoResponse() } result.addAll(responseEvents) } return result } /** * Get Calendar Events by List of Calendar */ fun getCalendarEventsById(calendarId: Long): List<CalendarEventsDtoResponse> { val calendar = calendarsRepository.findById(calendarId).orElseThrow { InvalidInputException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μΊ˜λ¦°λ” μ•„μ΄λ””μž…λ‹ˆλ‹€.") } val responseEvents = calendar.events.map { it.toCalendarEventsDtoResponse() } return responseEvents } /** * Create Calendar */ fun createCalendar(createCalendarDtoRequest: CreateCalendarDtoRequest): String { val userName = (SecurityContextHolder.getContext().authentication.principal as CustomUser).username val calendar = Calendars( category = Category.valueOf(createCalendarDtoRequest.category), name = createCalendarDtoRequest.name, author = userName, description = createCalendarDtoRequest.description, color = if (createCalendarDtoRequest.color.isNotBlank()) createCalendarDtoRequest.color else DEFAULT_COLOR ) val savedCalendar = calendarsRepository.save(calendar) createCalendarDtoRequest.events.forEach { val CalendarEvent = it.toEntity() CalendarEvent.calendars = savedCalendar calendarsEventRepository.save(CalendarEvent) } return "${userName} 일정이 μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€." } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/calendars/service/CalendarsService.kt
517106185
package com.example.joinu.subscribecalendars.dto /** * This DTO transfer request data for subscribe the calendar. * * @property id Id for calendar that member wants to subscribe * @property alias Alias for calendar by member * @property color Color for Calendar Events */ data class SubscribeRequestDto( val id: Long, val alias: String, val color: String, ) /** * This DTO transfer request data for unsubscribe the calendar. * * @property id Id for calendar that member wants to subscribe */ data class UnbscribeRequestDto( val id: Long, )
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/subscribecalendars/dto/SubscribeCalendarsDtos.kt
720558962
package com.example.joinu.subscribecalendars.repository import com.example.joinu.subscribecalendars.entity.SubscribeCalendars import com.example.joinu.team.entity.MemberTeam import org.springframework.data.jpa.repository.JpaRepository interface SubscribeCalendarsRepository : JpaRepository<SubscribeCalendars, Long> { fun deleteByMemberIdAndCalendarsId(memberId: Long, calendarsId: Long): Long fun findByMemberId(memberId: Long): List<SubscribeCalendars> }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/subscribecalendars/repository/SubscribeCalendarsRepositories.kt
3754360555
package com.example.joinu.subscribecalendars.entity import com.example.joinu.calendars.entity.Calendars import com.example.joinu.common.status.Category import com.example.joinu.common.status.Const.DEFAULT_COLOR import com.example.joinu.common.status.Gender import com.example.joinu.member.entity.Member import jakarta.persistence.* /** * 멀버가 κ΅¬λ…ν•˜κ³  μžˆλŠ” μΊ˜λ¦°λ” μ—”ν‹°ν‹° * @property id * @property member κ΅¬λ…ν•˜κ³  μžˆλŠ” ν•΄λ‹Ή 멀버 * @property calendars κ΅¬λ…ν•˜λŠ” μΊ˜λ¦°λ” * @property alias κ΅¬λ…ν•˜λŠ” μΊ˜λ¦°λ”μ˜ 별칭 */ @Entity class SubscribeCalendars( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "member_id") val member: Member? = null, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "calendars_id") val calendars: Calendars? = null, var alias: String, var color: String = DEFAULT_COLOR, ) { }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/subscribecalendars/entity/SubscribeCalendarsEntities.kt
1964882386
package com.example.joinu.subscribecalendars.controller import com.example.joinu.calendars.entity.Calendars import com.example.joinu.common.dto.BaseResponse import com.example.joinu.common.dto.CustomUser import com.example.joinu.member.entity.Member import com.example.joinu.subscribecalendars.dto.SubscribeRequestDto import com.example.joinu.subscribecalendars.dto.UnbscribeRequestDto import com.example.joinu.subscribecalendars.entity.SubscribeCalendars import com.example.joinu.subscribecalendars.service.SubscribeCalendarsServices import com.fasterxml.jackson.databind.ser.Serializers.Base import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/subscribe") class SubscribeCalendarsController( private val subscribeCalendarsServices: SubscribeCalendarsServices ) { /** * Subscribe the Calendar * * @param SubscribeRequestDto * @return String message */ @PostMapping("/subscribe") fun subscribeCalendar(@RequestBody subscribeRequestDto: SubscribeRequestDto): BaseResponse<String> { val result = subscribeCalendarsServices.subscribeCalendar(subscribeRequestDto) return BaseResponse(message = result) } /** * Unsubscribing calendar * * @param UnbscribeRequestDto * @return String message */ @PostMapping("/unsubscribe") fun unsubscribeCalendar(@RequestBody unbscribeRequestDto: UnbscribeRequestDto): BaseResponse<String> { val result = subscribeCalendarsServices.unsubscribeCalendar(unbscribeRequestDto) return BaseResponse(message = result) } /** * Get List of Subscribed calendar * * @return Subscribe Calendar List */ @GetMapping() fun getSubscribeList(): BaseResponse<List<Long?>> { val result = subscribeCalendarsServices.getSubscribeList() return BaseResponse(data = result) } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/subscribecalendars/controller/SubscribeCalendarsController.kt
3461387096
package com.example.joinu.subscribecalendars.service import com.example.joinu.calendars.entity.Calendars import com.example.joinu.common.dto.CustomUser import com.example.joinu.member.entity.Member import com.example.joinu.subscribecalendars.dto.SubscribeRequestDto import com.example.joinu.subscribecalendars.dto.UnbscribeRequestDto import com.example.joinu.subscribecalendars.entity.SubscribeCalendars import com.example.joinu.subscribecalendars.repository.SubscribeCalendarsRepository import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class SubscribeCalendarsServices( private val subscribeCalendarsRepository: SubscribeCalendarsRepository ) { /** * Subscribe the Calendar * * @param SubscribeRequestDto * @return String message */ fun subscribeCalendar(subscribeRequestDto: SubscribeRequestDto): String { val userId = (SecurityContextHolder.getContext().authentication.principal as CustomUser).userId val member = Member(id = userId) val calendars = Calendars(id = subscribeRequestDto.id) val subscribeCalendars = SubscribeCalendars( member = member, calendars = calendars, alias = subscribeRequestDto.alias, color = subscribeRequestDto.color ) subscribeCalendarsRepository.save(subscribeCalendars) return "일정이 κ΅¬λ…λ˜μ—ˆμŠ΅λ‹ˆλ‹€." } /** * Unsubscribing calendar * * @param UnbscribeRequestDto * @return String message */ fun unsubscribeCalendar(unbscribeRequestDto: UnbscribeRequestDto): String { val userId = (SecurityContextHolder.getContext().authentication.principal as CustomUser).userId subscribeCalendarsRepository.deleteByMemberIdAndCalendarsId(userId, unbscribeRequestDto.id) return "일정 ꡬ독이 μ·¨μ†Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€." } /** * Get List of Subscribed calendar * * @return Subscribe Calendar List */ fun getSubscribeList(): List<Long?> { val userId = (SecurityContextHolder.getContext().authentication.principal as CustomUser).userId val result = subscribeCalendarsRepository.findByMemberId(userId).map { it.calendars!!.id } return result } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/subscribecalendars/service/SubscribeCalendarsServices.kt
1393406645
package com.example.joinu.member.dto import com.example.joinu.common.annotation.ValidEnum import com.example.joinu.common.status.Gender import com.example.joinu.common.status.ROLE import com.example.joinu.member.entity.Member import com.fasterxml.jackson.annotation.JsonProperty import jakarta.validation.constraints.Email import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.Pattern import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* data class MemberDtoRequest( var id: Long?, @field:NotBlank @JsonProperty("loginId") private val _loginId: String?, @field:NotBlank @field:Pattern( regexp = "^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#\$%^&*])[a-zA-Z0-9!@#\$%^&*]{8,20}\$", message = "영문, 숫자, 특수문자λ₯Ό ν¬ν•¨ν•œ 8~20자리둜 μž…λ ₯ν•΄μ£Όμ„Έμš”" ) @JsonProperty("password") private val _password: String?, @field:NotBlank @JsonProperty("name") private val _name: String?, @field:NotBlank @field:Pattern( regexp = "^([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))$", message = "λ‚ μ§œν˜•μ‹(YYYY-MM-DD)을 ν™•μΈν•΄μ£Όμ„Έμš”" ) @JsonProperty("birthDate") private val _birthDate: String?, @field:NotBlank @field:ValidEnum(enumClass = Gender::class, message = "MAN μ΄λ‚˜ WOMAN 쀑 ν•˜λ‚˜λ₯Ό μ„ νƒν•΄μ£Όμ„Έμš”.") @JsonProperty("gender") private val _gender: String?, @field:NotBlank @field:Email @JsonProperty("email") private val _email: String?, ) { val loginId: String get() = _loginId!! val password: String get() = _password!! val name: String get() = _name!! val birthDate: LocalDate get() = _birthDate!!.toLocalDate() val gender: Gender get() = Gender.valueOf(_gender!!) val email: String get() = _email!! private fun String.toLocalDate(): LocalDate = LocalDate.parse(this, DateTimeFormatter.ofPattern("yyyy-MM-dd")) fun toEntity(): Member = Member(id, loginId, password, name, birthDate, gender, email) } data class MemberPutDtoRequest( var id: Long?, @field:NotBlank @JsonProperty("loginId") private val _loginId: String?, @field:Pattern( regexp = "^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#\$%^&*])[a-zA-Z0-9!@#\$%^&*]{8,20}\$", message = "영문, 숫자, 특수문자λ₯Ό ν¬ν•¨ν•œ 8~20자리둜 μž…λ ₯ν•΄μ£Όμ„Έμš”" ) @JsonProperty("password") private val _password: String?, @JsonProperty("name") private val _name: String?, @field:Email @JsonProperty("email") private val _email: String?, ) { val loginId: String get() = _loginId!! val password: String? get() = _password val name: String? get() = _name val email: String? get() = _email } data class LoginDto( @field:NotBlank @JsonProperty("loginId") private val _loginId: String?, @field:NotBlank @JsonProperty("password") private val _password: String?, ) { val loginId: String get() = _loginId!! val password: String get() = _password!! } data class MemberInfoDtoRequest( @field:NotBlank @JsonProperty("loginId") private val _loginId: String?, ) { val loginId: String get() = _loginId!! } data class MemberDtoResponse( val id: Long, val loginId: String, val name: String, val birthDate: String, val gender: String, val email: String, val roles: List<ROLE>, ) data class MemberInfoDtoResponse( val id: Long, val loginId: String, val avator: String, )
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/member/dto/MemberDtos.kt
2972239856
package com.example.joinu.member.repository import com.example.joinu.event.entity.Event import com.example.joinu.member.entity.Member import com.example.joinu.member.entity.MemberRole import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param interface MemberRepository : JpaRepository<Member, Long> { fun findByLoginId(loginId: String): Member? @Query("SELECT e FROM Event e JOIN MemberEvent ue ON e.id = ue.event.id WHERE ue.member.id = :memberId") fun findEventsByMemberId(@Param("memberId") memberId: Long): List<Event> } interface MemberRoleRepository : JpaRepository<MemberRole, Long>
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/member/repository/MemberRepositories.kt
748919659
package com.example.joinu.member.entity import com.example.joinu.common.status.Gender import com.example.joinu.common.status.ROLE import com.example.joinu.event.entity.Event import com.example.joinu.event.entity.MemberEvent import com.example.joinu.member.dto.MemberDtoResponse import com.example.joinu.member.dto.MemberInfoDtoResponse import com.example.joinu.member.dto.MemberPutDtoRequest import jakarta.persistence.* import org.springframework.security.crypto.password.PasswordEncoder import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* @Entity @Table( uniqueConstraints = [UniqueConstraint(name = "uk_member_login_id", columnNames = ["loginId"])] ) class Member( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, length = 30, updatable = false) val loginId: String = "", @Column(nullable = false, length = 100) var password: String = "", @Column(nullable = false, length = 10) var name: String = "", @Column(nullable = false) @Temporal(TemporalType.DATE) val birthDate: LocalDate = LocalDate.now(), @Column(nullable = false, length = 5) @Enumerated(EnumType.STRING) val gender: Gender = Gender.MAN, @Column(nullable = false, length = 30) var email: String = "", var avator: String = "/img/default_avator.png", ) { @OneToMany(fetch = FetchType.LAZY, mappedBy = "member") val memberRole: List<MemberRole>? = null private fun LocalDate.formatDate(): String = this.format(DateTimeFormatter.ofPattern("yyyyMMdd")) fun toDto(): MemberDtoResponse { val roles: List<ROLE> = memberRole?.map { it.role } ?: emptyList() return MemberDtoResponse(id!!, loginId, name, birthDate.formatDate(), gender.desc, email, roles) } fun toMemberInfoDto(): MemberInfoDtoResponse { return MemberInfoDtoResponse(id!!, loginId, avator) } fun encodePassword(passwordEncoder: PasswordEncoder) { password = passwordEncoder.encode(password) } fun updateMember(memberPutDtoRequest: MemberPutDtoRequest) { memberPutDtoRequest.name?.let { newName -> name = newName } memberPutDtoRequest.email?.let { newEmail -> email = newEmail } if (memberPutDtoRequest.password != null) { password = memberPutDtoRequest.password!! } } } @Entity class MemberRole( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, length = 30) @Enumerated(EnumType.STRING) val role: ROLE, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(foreignKey = ForeignKey(name = "fk_member_role_member_id")) val member: Member, )
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/member/entity/MemberEntities.kt
928255051
package com.example.joinu.member.controller import com.example.joinu.common.authority.TokenInfo import com.example.joinu.common.dto.BaseResponse import com.example.joinu.common.dto.CustomUser import com.example.joinu.member.dto.* import com.example.joinu.member.service.MemberService import jakarta.validation.Valid import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RequestMapping("/api/member") @RestController class MemberController( private val memberService: MemberService ) { /** * νšŒμ›κ°€μž… */ @PostMapping("/signup") fun signUp(@RequestBody @Valid memberDtoRequest: MemberDtoRequest): BaseResponse<Unit> { val resultMsg: String = memberService.signUp(memberDtoRequest) return BaseResponse(message = resultMsg) } /** * 둜그인 */ @PostMapping("/login") fun login(@RequestBody @Valid loginDto: LoginDto): BaseResponse<TokenInfo> { val tokenInfo = memberService.login(loginDto) return BaseResponse(data = tokenInfo) } /** * λ‚΄ 정보 보기 */ @GetMapping("/info") fun searchMyInfo(): BaseResponse<MemberDtoResponse> { val userId = (SecurityContextHolder.getContext().authentication.principal as CustomUser).userId val response = memberService.searchMyInfo(userId) return BaseResponse(data = response) } /** * λ‹€λ₯Έ μ‚¬λžŒ 정보 보기 */ @PostMapping("/info") fun searchMemberInfo(@RequestBody memberInfo: MemberInfoDtoRequest): BaseResponse<MemberInfoDtoResponse> { val response = memberService.searchMemberInfo(memberInfo.loginId) return BaseResponse(data = response) } /** * λ‚΄ 정보 μ €μž₯ */ @PutMapping("/info") fun saveMyInfo(@RequestBody @Valid memberDtoRequest: MemberPutDtoRequest): BaseResponse<Unit> { val userId = (SecurityContextHolder.getContext().authentication.principal as CustomUser).userId memberDtoRequest.id = userId val resultMsg: String = memberService.saveMyInfo(memberDtoRequest) return BaseResponse(message = resultMsg) } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/member/controller/MemberController.kt
1703075116
package com.example.joinu.member.service import com.example.joinu.common.authority.JwtTokenProvider import com.example.joinu.common.authority.TokenInfo import com.example.joinu.common.exception.InvalidInputException import com.example.joinu.common.status.ROLE import com.example.joinu.member.dto.* import com.example.joinu.member.entity.Member import com.example.joinu.member.entity.MemberRole import com.example.joinu.member.repository.MemberRepository import com.example.joinu.member.repository.MemberRoleRepository import jakarta.transaction.Transactional import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.repository.findByIdOrNull import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service @Transactional @Service class MemberService( private val memberRepository: MemberRepository, private val memberRoleRepository: MemberRoleRepository, private val authenticationManagerBuilder: AuthenticationManagerBuilder, private val jwtTokenProvider: JwtTokenProvider, @Autowired private val passwordEncoder: PasswordEncoder ) { /** * νšŒμ›κ°€μž… */ fun signUp(memberDtoRequest: MemberDtoRequest): String { // ID 쀑볡 검사 var member: Member? = memberRepository.findByLoginId(memberDtoRequest.loginId) if (member != null) { throw InvalidInputException("loginId", "이미 λ“±λ‘λœ ID μž…λ‹ˆλ‹€.") } member = memberDtoRequest.toEntity() member.encodePassword(passwordEncoder) memberRepository.save(member) val memberRole: MemberRole = MemberRole(null, ROLE.MEMBER, member) memberRoleRepository.save(memberRole) return "νšŒμ›κ°€μž…μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€." } /** * 둜그인 -> 토큰 λ°œν–‰ */ fun login(loginDto: LoginDto): TokenInfo { val authenticationToken = UsernamePasswordAuthenticationToken(loginDto.loginId, loginDto.password) val authentication = authenticationManagerBuilder.`object`.authenticate(authenticationToken) return jwtTokenProvider.createToken(authentication) } /** * λ‚΄ 정보 쑰회 */ fun searchMyInfo(id: Long): MemberDtoResponse { val member: Member = memberRepository.findByIdOrNull(id) ?: throw InvalidInputException("id", "νšŒμ›λ²ˆν˜Έ(${id})κ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μœ μ €μž…λ‹ˆλ‹€.") return member.toDto() } /** * 멀버 쑰회 */ fun searchMemberInfo(loginId: String): MemberInfoDtoResponse { val member: Member = memberRepository.findByLoginId(loginId) ?: throw InvalidInputException( "id", "νšŒμ› 아이디 (${loginId})κ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μœ μ €μž…λ‹ˆλ‹€." ) return member.toMemberInfoDto() } /** * λ‚΄ 정보 μˆ˜μ • */ fun saveMyInfo(memberDtoRequest: MemberPutDtoRequest): String { val member: Member = memberRepository.findByIdOrNull(memberDtoRequest.id) ?: throw InvalidInputException( "id", "νšŒμ›λ²ˆν˜Έ(${memberDtoRequest.id})κ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μœ μ €μž…λ‹ˆλ‹€." ) member.updateMember(memberDtoRequest) memberRepository.save(member) return "μˆ˜μ •μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€." } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/member/service/MemberService.kt
366599345
package com.example.joinu import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class JoinUApplication fun main(args: Array<String>) { runApplication<JoinUApplication>(*args) }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/JoinUApplication.kt
2062364226
package com.example.joinu.common.dto import com.example.joinu.common.status.ResultCode data class BaseResponse<T>( val resultCode: String = ResultCode.SUCCESS.name, val data: T? = null, val message: String = ResultCode.SUCCESS.msg, )
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/dto/BaseResponse.kt
2783874607
package com.example.joinu.common.dto import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.User class CustomUser( val userId: Long, userName: String, password: String, authorities: Collection<GrantedAuthority> ) : User(userName, password, authorities)
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/dto/CustomUser.kt
3515802878
package com.example.joinu.common.config import com.example.joinu.common.authority.JwtAuthenticationFilter import com.example.joinu.common.authority.JwtTokenProvider import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.factory.PasswordEncoderFactories import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter @Configuration @EnableWebSecurity class SecurityConfig( private val jwtTokenProvider: JwtTokenProvider ) { @Bean fun filterChain(http: HttpSecurity): SecurityFilterChain { http .httpBasic { it.disable() } .csrf { it.disable() } .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } .authorizeHttpRequests { it.requestMatchers("/api/member/signup", "/api/member/login").anonymous() .requestMatchers("/api/member/**").hasRole("MEMBER") .anyRequest().permitAll() } .addFilterBefore( JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter::class.java ) return http.build() } @Bean fun passwordEncoder(): PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder() }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/config/SecurityConfig.kt
4233224312
package com.example.joinu.common.annotation import jakarta.validation.Constraint import jakarta.validation.ConstraintValidator import jakarta.validation.ConstraintValidatorContext import jakarta.validation.Payload import kotlin.reflect.KClass @Target(AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) @MustBeDocumented @Constraint(validatedBy = [ValidEnumValidator::class]) annotation class ValidEnum( val message: String = "Invalid enum value", val groups: Array<KClass<*>> = [], val payload: Array<KClass<out Payload>> = [], val enumClass: KClass<out Enum<*>> ) class ValidEnumValidator : ConstraintValidator<ValidEnum, Any> { private lateinit var enumValues: Array<out Enum<*>> override fun initialize(annotation: ValidEnum) { enumValues = annotation.enumClass.java.enumConstants } override fun isValid(value: Any?, context: ConstraintValidatorContext): Boolean { if (value == null) { return true } return enumValues.any { it.name == value.toString()} } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/annotation/ValidEnum.kt
2436016042
package com.example.joinu.common.status object Const { const val DEFAULT_COLOR = "#1976d2" const val DEFAULT_DISABLED = false const val DEFAULT_EDITABLE = true const val DEFAULT_DELETABLE = true const val DEFAULT_ALL_DAY = false }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/status/Const.kt
2528521838
package com.example.joinu.common.status enum class Gender(val desc: String) { MAN("남"), WOMAN("μ—¬") } enum class ResultCode(val msg: String) { SUCCESS("정상 처리 λ˜μ—ˆμŠ΅λ‹ˆλ‹€."), ERROR("μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.") } enum class ROLE { MEMBER } enum class Category { SCHOOL, SPORT, STUDY, DAILY }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/status/EnumStatus.kt
49584702
package com.example.joinu.common.service import com.example.joinu.common.dto.CustomUser import com.example.joinu.member.entity.Member import com.example.joinu.member.repository.MemberRepository import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service @Service class CustomUserDetailsService( private val memberRepository: MemberRepository, ) : UserDetailsService { override fun loadUserByUsername(username: String): UserDetails = memberRepository.findByLoginId(username) ?.let { createUserDetails(it) } ?: throw UsernameNotFoundException("ν•΄λ‹Ή μœ μ €λŠ” μ—†μŠ΅λ‹ˆλ‹€.") private fun createUserDetails(member: Member): UserDetails = CustomUser( member.id!!, member.loginId, member.password, member.memberRole!!.map { SimpleGrantedAuthority("ROLE_${it.role}") } ) }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/service/CustomUserDetailsService.kt
3608222248
package com.example.joinu.common.authority data class TokenInfo( val grantType: String, val accessToken: String, )
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/authority/TokenInfo.kt
1231018276
package com.example.joinu.common.authority import com.example.joinu.common.dto.CustomUser import io.jsonwebtoken.* import io.jsonwebtoken.io.Decoders import io.jsonwebtoken.security.Keys import org.springframework.beans.factory.annotation.Value import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import java.util.* import kotlin.RuntimeException const val EXPIRATION_MILLISECONDS: Long = 1000 * 60 * 60 * 24 * 5 @Component class JwtTokenProvider { @Value("\${jwt.secretKey}") lateinit var secretKey: String private val key by lazy { Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey)) } /** * Token 생성 */ fun createToken(authentication: Authentication): TokenInfo { val authorities: String = authentication .authorities .joinToString(",", transform = GrantedAuthority::getAuthority) val now = Date() val accessExpiration = Date(now.time + EXPIRATION_MILLISECONDS) // Access Token val accessToken = Jwts .builder() .setSubject(authentication.name) .claim("auth", authorities) .claim("userId", (authentication.principal as CustomUser).userId) .setIssuedAt(now) .setExpiration(accessExpiration) .signWith(key, SignatureAlgorithm.HS256) .compact() return TokenInfo("Bearer", accessToken) } /** * Token 정보 μΆ”μΆœ */ fun getAuthentication(token: String): Authentication { val claims: Claims = getClaims(token) val auth = claims["auth"] ?: throw RuntimeException("잘λͺ»λœ ν† ν°μž…λ‹ˆλ‹€.") val userId = claims["userId"] ?: throw RuntimeException("잘λͺ»λœ ν† ν°μž…λ‹ˆλ‹€.") // κΆŒν•œ 정보 μΆ”μΆœ val authorities: Collection<GrantedAuthority> = (auth as String) .split(",") .map { SimpleGrantedAuthority(it) } val principal: UserDetails = CustomUser(userId.toString().toLong(), claims.subject, "", authorities) return UsernamePasswordAuthenticationToken(principal, "", authorities) } /** * Token 검증 */ fun validateToken(token: String): Boolean { try { getClaims(token) return true } catch (e: Exception) { when (e) { is SecurityException -> {} // Invalid JWT Token is MalformedJwtException -> {} // Invalid JWT Token is ExpiredJwtException -> {} // Expired JWT Token is UnsupportedJwtException -> {} // Unsupported JWT Token is IllegalArgumentException -> {} // JWT claims string is empty else -> {} // else } println(e.message) } return false } private fun getClaims(token: String): Claims = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) .body }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/authority/JwtTokenProvider.kt
3033860212
package com.example.joinu.common.authority import jakarta.servlet.FilterChain import jakarta.servlet.ServletRequest import jakarta.servlet.ServletResponse import jakarta.servlet.http.HttpServletRequest import org.springframework.security.core.context.SecurityContextHolder import org.springframework.util.StringUtils import org.springframework.web.filter.GenericFilterBean class JwtAuthenticationFilter( private val jwtTokenProvider: JwtTokenProvider ) : GenericFilterBean() { override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) { val token = resolveToken(request as HttpServletRequest) if (token != null && jwtTokenProvider.validateToken(token)) { val authentication = jwtTokenProvider.getAuthentication(token) SecurityContextHolder.getContext().authentication = authentication } chain?.doFilter(request, response) } private fun resolveToken(request: HttpServletRequest): String? { val bearerToken = request.getHeader("Authorization") return if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer")) { bearerToken.substring(7) } else { null } } }
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/authority/JwtAuthenticationFilter.kt
1916282962
package com.example.joinu.common.exception class InvalidInputException( val fieldName: String = "", message: String = "Invalid Input" ) : RuntimeException(message)
Joint-Schedule-Service/backend/src/main/kotlin/com/example/joinu/common/exception/InvalidInputException.kt
1348351050