Sunday, January 22, 2023

Set cron for laravel in ngnix server

SSH into your server and navigate to the root directory of your Laravel application.

Run the command crontab -e to open the cron tab editor.

If you want to run cron in every minute then : 

Add the following line to the editor: * * * * * php /path/to/your/laravel/installation/artisan schedule:run >> /dev/null 2>&1

Save and exit the editor.

This will run the Laravel task scheduler every minute.


Note: You should replace the /path/to/your/laravel/installation/ with the actual path of your laravel installation in the server.


Alternatively, you can also add the cron job using the cron command. You can do this by running the following command:


* * * * * cd /path/to/your/laravel/installation && php artisan schedule:run >> /dev/null 2>&1

This will change the current working directory to your laravel installation and runs the schedule:run command every minute.

If you want to run cron in every day: 

0 0 * * * cd /path/to/your/laravel/installation && php artisan schedule:run >> /dev/null 2>&1
This will change the current working directory to your laravel installation and runs the schedule:run command every day at 00:00 (midnight)

You can adjust the time in the cron schedule by modifying the first two fields. The first field is for minutes (0-59), the second field is for hours (0-23), the third field is for day of the month (1-31), the fourth field is for months (1-12) and the fifth field is for day of the week (0-7) (both 0 and 7 mean Sunday).

Make sure that your Nginx server have the correct permissions to execute the cron job, and also make sure that your laravel application have the correct permissions to write to log files, cache and other necessary files.

You can also verify that the cron job is running correctly by checking the logs of the cron jobs, usually located in the /var/log/cron or /var/log/syslog directory. 

It is not necessary to set up a cron job in the cron tab when using Supervisor to manage your Laravel task scheduler.

setup laravel supervisor in ngnix server

 Install Supervisor:


sudo apt-get install supervisor

Create a new configuration file for your Laravel task scheduler in the /etc/supervisor/conf.d/ directory. The file should be named laravel-worker.conf

Add the following configuration to the file:

Copy code

[program:laravel-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /path/to/your/laravel/installation/artisan schedule:run

autostart=true

autorestart=true

user=www-data

redirect_stderr=true

Replace /path/to/your/laravel/installation/ with the actual path of your Laravel installation.

Update the Supervisor's configuration by running the command:

Copy code

sudo supervisorctl reread

Start the Laravel task scheduler process by running the command:

Copy code

sudo supervisorctl start laravel-worker

With this configuration, Supervisor will start the Laravel task scheduler process when the server boots, and it will automatically restart the process if it crashes. It also keeps track of the process and log any errors that may occur.


You can also use sudo supervisorctl stop laravel-worker to stop the process or sudo supervisorctl status laravel-worker to check the status of the process.


You can also use sudo supervisorctl tail -f laravel-worker to see the logs of the process


Note: Make sure you have supervisor installed in your server and you have the correct permissions to manage the process.


Also, make sure your Nginx server have the correct permissions to execute the cron job, and also make sure that your laravel application have the correct permissions to write to log files, cache and other necessary files.

To restart Supervisor, you can use the following command:

sudo service supervisor restart

Alternatively, you can also use the following command:

sudo systemctl restart supervisor

This command is used to restart the supervisor service on systems that use systemd.

You can also use the following command to check the status of the Supervisor service:

sudo service supervisor status

or

sudo systemctl status supervisor

This command will show you if the service is running or not and if there are any errors.

Please note that after restarting supervisor, you will need to update the process by running the following command:

sudo supervisorctl update

Example for laravel cron job which will send 2 birhtday notification mail to user first is one day before and second is the day when birthday is

In your terminal, navigate to the root directory of your Laravel application.

Run the command crontab -e to open the cron tab editor.

Add the following line to the editor: * * * * * php /path/to/your/laravel/installation/artisan schedule:run >> /dev/null 2>&1

Save and exit the editor.

This will run the Laravel task scheduler every minute.


Next, you can define two new tasks in your app/Console/Kernel.php file that will send birthday notifications to users.


use App\User;

use Carbon\Carbon;

use Illuminate\Console\Scheduling\Schedule;

use Illuminate\Support\Facades\Mail;


class Kernel extends ConsoleKernel

{

    protected function schedule(Schedule $schedule)

    {

        $schedule->call(function () {

            $users = User::all();

            foreach ($users as $user) {

                if($user->birthday->isToday()) {

                    Mail::to($user->email)->send(new BirthdayEmail($user));

                }

                if($user->birthday->isTomorrow()) {

                    Mail::to($user->email)->send(new BirthdayReminderEmail($user));

                }

            }

        })->daily();

    }

}

In model: 

use Carbon\Carbon;


class User extends Authenticatable

{

    // other model properties and methods


    public function isToday()

    {

        return Carbon::today()->isSameDay($this->birthday);

    }

   public function isTomorrow()

    {

        return Carbon::tomorrow()->isSameDay($this->birthday);

    }

    public function isTwoDaysBefore()

    {

        return Carbon::now()->addDays(2)->isSameDay($this->birthday);

    }

}

 

Tuesday, January 17, 2023

show user locations heatmap using google maps api

Steps: 

To get a heatmap of user locations for a Surface Book, you would typically need to collect location data from the device's GPS or other location-tracking feature, and then use a mapping or visualization tool to create the heatmap. Here's an example of a general process you could follow:

  1. Collect location data: You would need to write code that can collect location data from the Surface Book. This could involve using the device's built-in GPS, Wi-Fi triangulation, or other location-tracking features. You would need to decide on the frequency at which you want to collect the data, as well as how long you want to collect it for.
  2. Store the data: Once you have collected the location data, you would need to store it in a database or other data storage system. This could be a local database on the device, or a cloud-based database that can be accessed from anywhere.
  3. Visualize the data: Once you have collected and stored the data, you could use a mapping tool or a visualization library to create a heatmap. There are many options available such as leaflet.js, Google Maps, OpenStreetMap and more. You can use any of them to create a heatmap based on the location data you have collected.
  4. Show the heatmap: You could then create a web page or mobile app that displays the heatmap, allowing users to view the locations where the device has been used.

Keep in mind that this is just a general example, and the specific steps you need to take may vary depending on the tools and technologies you use.

Also, make sure that you comply with the laws and regulations regarding data privacy, and get user's consent before tracking their location data.


Setup cron in vue electron app: 


In an Electron Vue application, you can use a npm package called cron to schedule a cron job for collecting location data at regular intervals of time. Here's an example of how you might use the cron package to schedule a cron job for collecting location data every hour:

  1. Install the cron package: In your Electron Vue project directory, run the following command to install the cron package:


Copy code

npm install cron

  1. Import the cron package: In your JavaScript file where you have the logic for collecting location data, you can import the cron package at the top of the file:


Copy code

import cron from 'cron';

  1. Schedule the cron job: Once you have imported the cron package, you can use the CronJob class to schedule a cron job for collecting location data. For example, you can schedule a cron job to run every hour at the 0th minute of the hour:


Copy code

const job = new cron.CronJob('0 * * * *', function() { /* Code for collecting location data */ }); job.start();

  1. Start the cron job: Once you have scheduled the cron job, you need to start it. you can use the start method of the CronJob instance to start the cron job
  2. Stop the cron job: To stop the cron job, you can use the stop method of the CronJob instance


Copy code

job.stop();

Please keep in mind that it is important to get user's consent before tracking their location data, and also make sure to comply with the laws and regulations regarding data privacy.

You can also schedule the job to run at specific intervals of time by providing a different cron pattern, you can check the cron pattern and examples at https://crontab.guru/

Make sure you have imported the cron library in your code file.


Example code for cron location store in db: 


import { remote } from 'electron'

import cron from 'cron';

import {sequelize, Location} from './models'


const geolocation = remote.geolocation


const job = new cron.CronJob('0 * * * *', function() {

    // Check if geolocation is supported

    if ("geolocation" in geolocation) {

        // Get the current location

        geolocation.getCurrentPosition(function(position) {

            // Log the latitude and longitude

            console.log("Latitude: " + position.coords.latitude);

            console.log("Longitude: " + position.coords.longitude);


            // Store location data in the database

            Location.create({

              latitude: position.coords.latitude,

              longitude: position.coords.longitude,

              captured_at: new Date()

            });

        });

    } else {

        console.log("Geolocation is not supported by this application.");

    }

});


job.start();


Visualize heatmap based on locations: 


here's an example of how you could use the Google Maps JavaScript API to create a heatmap from the location data you previously stored in the database:

    • Get an API key: To use the Google Maps JavaScript API, you will need to get an API key from the Google Cloud Platform console. You can do this by following these steps:
    • Go to the Google Cloud Platform console (https://console.cloud.google.com/)
    • Select or create a project
    • Go to the "Credentials" page
    • Click "Create credentials" and choose "API key"
    • Add the key to your application by adding the following script in your HTML file


Copy code

        

         <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
  1. Initialize the map: To create a Google Map, you will need to initialize it with a DOM element and options. You can do this by creating a div element in your HTML file and give it an id, and then use JavaScript to create a new google.maps.Map object, passing in the id of the div element and options.

<template>

  <div id="map"></div>

</template>


<script>


import { mapGetters } from 'vuex'

import { loadGoogleMapsApi } from 'vue2-google-maps'


export default {


  computed: {

    ...mapGetters(['locations'])

  },

  mounted () {

    loadGoogleMapsApi({

      key: 'YOUR_API_KEY'

    }).then(() => {

      // Get the locations from the store

      const locations = this.locations


      // Create a new map


      const map = new google.maps.Map(document.getElementById('map'), {

        zoom: 8,

        center: new google.maps.LatLng(locations[0].latitude, locations[0].longitude),

        mapTypeId: 'terrain'

      })


      // Create a heatmap data layer


      const heatmapData = locations.map(location => new google.maps.LatLng(location.latitude, location.longitude))

      const heatmap = new google.maps.visualization.HeatmapLayer({

        data: heatmapData

      });


                heatmap.setMap(map);

heatmap.set('radius', 20);

heatmap.set('opacity', 0.8);


const gradient = [

    'rgba(0, 255, 255, 0)',

    'rgba(0, 255, 255, 1)',

    'rgba(0, 191, 255, 1)',

    'rgba(0, 127, 255, 1)',

    'rgba(0, 63, 255, 1)',

    'rgba(0, 0, 255, 1)',

    'rgba(0, 0, 223, 1)',

    'rgba(0, 0, 191, 1)',

    'rgba(0, 0, 159, 1)',

    'rgba(0, 0, 127, 1)',

    'rgba(63, 0, 91, 1)',

    'rgba(127, 0, 63, 1)',

    'rgba(191, 0, 31, 1)',

    'rgba(255, 0, 0, 1)'

]

heatmap.set('gradient', gradient);

 


     











Monday, January 16, 2023

Save file in node js filesystem then upload to server

Save to local filesystem : 

 const fs = require('fs')

// Read the image file as a buffer

const imageBuffer = fs.readFileSync('path/to/image.jpg')

// Encode the image buffer as a base64 string

const imageBase64 = imageBuffer.toString('base64')

// Save the base64 encoded image to a local file

fs.writeFileSync('path/to/local/image.txt', imageBase64)


Upload to server from local filesystem:

const axios = require('axios')

const FormData = require('form-data')


// Read the local image file as a buffer

const imageBuffer = fs.readFileSync('path/to/local/image.txt')


// Decode the base64 encoded image to a buffer

const image = new Buffer.from(imageBuffer.toString(), 'base64')


const formData = new FormData()

formData.append('image', image)

const options = {

  headers: {

    'Content-Type': 'multipart/form-data'

  }

}

axios.post('api_endpoint_url', formData, options)

  .then((response) => {

    console.log(response.data)

  })

  .catch((error) => {

    console.log(error)

  })