Posted on Leave a comment

Creating A Twitter Follow Bot With Node and Twit.js

Automate Your Following With A Twitter Follow Bot

Anyone who follows me on Twitter (if you don’t @mastashake08) knows that I’m pretty active. Currently I’m on my way to 10K followers but sometimes my TL looks kinda dry. One of the best things about Twitter is that I learn alot of new information from the people I follow. Yet I don’t have the time to actively look for new people. Time for a #CodeLife trick.

Filtering Statuses With Twit

If you read my article on Creating a Discord Twitter Bot then alot of this code will look familiar to you. I’m going to stream a list of filtered statuses that use the hashtags #BlackTechTwitter and #CodeLife and whoever sends those tweets I will automatically follow them. So let’s begin by creating a new directory and adding our dependecies

mkdir follow-bot
cd follow-bot && npm install dotenv twit
touch search-follow.js

This will create a new directory, cd into it and install the dotenv and twit dependencies. Dotenv allows us to use a .env file to hold our secret values for our Twitter creditenials safely and twit is the Twitter javascript library. Lastly we created an empty js file where we will hold our code. Open it up and input the following.

require('dotenv').config()
const Twit = require('twit')


var T = new Twit({
  consumer_key:         process.env.TWITTER_CONSUMER_KEY,
  consumer_secret:      process.env.TWITTER_CONSUMER_SECRET,
  access_token:         process.env.TWITTER_ACCESS_TOKEN,
  access_token_secret:  process.env.TWITTER_ACCESS_TOKEN_SECRET,
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  strictSSL:            true,     // optional - requires SSL certificates to be valid.
})
var stream = T.stream('statuses/filter', { track: ['#blacktechtwitter', '#codelife'], language: 'en' })

stream.on('tweet', function (tweet) {
  //...
  var user = tweet.user;
  try {
    T.post('friendships/create', {screen_name: user.screen_name})
    console.log('Followed ' + user.screen_name)
  } catch (error) {
    console.log(error)
    }
  })

The first lines we are requiring our dependencies and after we initialize the Twit object with out Twitter API creds stored in .env

Next we set a stream variable that will hold our filtered statuses tracking the list of hashtags.

Since the stream is event-driven we listen for the ‘tweet’ event which holds our Tweet object. We grab the screen_name of the user who tweeted and make a request to the ‘friendships/create’ endpoint which is what creates the following!

See how simple that was! If you enjoyed this article consider becoming a patron to get exclusive content! Get the source code here.

Posted on Leave a comment

WebTransport Is A Game Changer For Gaming

If You Haven’t Heard Of WebTransport

It is a new standard that provides bidirectional data transport over HTTP/3. In many cases, it can replace WebSocket and WebRTC with less overhead. It has two APIs that come with it, one for sending data unreliably with Datagram API and one reliably with the Stream API. In this article I will explain what WebTransport is, and how it will affect web gaming! If you want access to my member’s only article where I build a HTTP/3 server in Go and WebTransport client become a patron today.

Why Is WebTransport Such A Big Deal?

WebTransport is built on top of HTTP/3 which means it runs over QUIC. Without going into too much technical detail this equates to lower overhead and faster more reliable connections. It is also bidirectional meaning you can read and write data to the server. The cool thing to me though is how you can send data reliably (with streams similar to websockets) AND unreliably via datagrams!

Imagine you are making a multiplayer shooting game with 64 players. In coding terms you need this data to come as fast as possible right? Well at first glance you might think that a reliable data stream would be the best right? After all if all the players are shooting one character you want the damage to come in order right? WRONG! You do that and you are at the behest of the slowest network in the game. By sending datagrams you get best effort delivery (let’s be honest only ~1-5% of traffic is lost in these types of connections) so you won’t block the other connections.

Since WebTransport is Client-Server this is a no brainer for real-time multiplayer web games! Low latency is a must!

What’s Next?

WebTransport is still in it’s early stages but I will be following up with a YouTube video and a follow up blog where I will build a WebTransport server and client application! If you aren’t following me on Twitter do so @mastashake08

Posted on Leave a comment

Are You A Front End Web Developer? Congrats, You Are Also An Android Developer.

front end web developer to android developer

Mobile Development and Web Development Are Merging

Progressive web apps (PWAs) are pretty mainstream now and most web developers are aware of their existence. The Android platform and the Google Play store has been around for going on 13 years and developers are aware of its existence. What many are unaware of is how much the two platforms have been merging in the background. Last year I had the most wonderful epiphany. If you are a front end web developer, then by default you can publish Android applications, making you an Android developer as well.

Subscribe to my YouTube for more Tech Talks

What Are The Benefits?

You might be wondering what the benefits of turning your PWA into an installable Android application. Some of the main ones include:

  • Increased visibility
  • Increased revenue
  • Better brand reputation

Increased Visibility

When you turn your progressive web application into an Android application and upload it to the Google Play Store, you are opening yourself to a new realm of SEO called App Store Optimization. This is the search engine that powers the Google Play Store search. Your app will now be available to all Android users (unless otherwise specified). Your app store listing is the gateway to all of these new potential users.

Increased Revenue

When you upload an Android application you can set it to be paid or free. In addition to increased ad revenue (if that is your monetization model) that will grow proportionally with app download and usage; but what about apps that don’t make any money on the web? Those could be one-time paid downloads on the Google Play Store.

Better Brand Reputation

Just by turning your PWA into an Android app, you are increasing your brand reputation! Users trust brands that are on multiple platforms and see it as more established, whether or not this is true for that brand is debatable. Definitely worth the $25 to get a Google developer license.

PWAs and WebAPKs

When Google added PWA support to Chrome on Android they added this cool feature called WebAPK. When a user clicks the “Add To Homescreen” button on the mobile browser, the Android operating system actually creates a special APK on the fly, sign and install it. This feature is powerful and can lead to easy accessibility for web apps now and in the future. When I first heard of this, I immediately went to work converting all of my web applications into progressive web applications. Thinking this is the pinnacle I told myself I bought my Android developer license for nothing I will just push installs this way; but then I found something better.

Android Trusted Web Activities

Android now has this cool new way of working with your PWA inside of your app called Trusted Web Activities. TWAs have a lot of benefits but my top two are:

  1. Content in a Trusted Web activity is trusted — the app and the site it opens are expected to come from the same developer. (This is verified using Digital Asset Links.)
  2. The content rendered in a Trusted Web Activity comes from the web: they’re rendered by the user’s browser, in exactly the same way as a user would see it in their browser except they are run fullscreen. Web content should be accessible and useful in the browser first.

Let’s say you already built your PWA and you need an Android application but you need to do some extra things that are beyond the current scope of web apis but everything else is in the PWA. Using Trusted Web Activites you can interact with your application and the native APIs provided by Android. The PWA has to come from the same developer who is creating the Android application and is done using Digital Asset Links. This is a file proves you are the owner and once you upload this file to your server, Google will verify. This ensures security and that you aren’t ripping off someone eles’s PWA for your own profit. Also by uploading an Android app that is based on your PWA you don’t have to worry about updates (as much). Once you update the PWA, your application will reflect those updates, thus reducing code time.

But wait….doesn’t that require me to first write an Android app that calls the TWA?

Yes however AUTOMATION BABY! There are tools that I use that make generate the source code and the APK so all I have to do is upload it to the Google Play Console as a new app. I never touch any Java/Kotlin code. I created a course that shows you how to take ANY non PWA web application and turn it into a PWA and APK in under 30 minutes! Expand your visibility and earn more income by diversfying your platforms!

Posted on Leave a comment

Create An Online Radio & Podcast Streamer Using Vue and Media Session API

The Media Session API

I love listening to podcasts and online radio. I used to run an online station a fews ago called 90K Radio and I was hooked in the community ever since. Keeping on track with my PWA binge I thought it would be a cool to write a progressive web app that can take in any stream URL and play it. Not only that but I want to be able to control the audio using the native audio commands on Android, iOS and desktop. There is this awesome javascript API called the Media Session API. The Media Session API allows you to customize media notifications and how to handle them. It allows you to control your media without having to be on that specific webpage. This allows for things such as background playing ( a must need feature for online radio PWA). You can even do things like set album artwork and other metadata and have custom handlers for events such as skipping tracks and pausing/playing.

What Are The Benefits?

Primarily I built this because a PWA will load faster. Also no tracking, I don’t have to worry about Google or anyone else tracking my activity, I can just listen in peace. By using the media session API I can listen in the background whilst doing other things which most likely will be every time I use the app. Lastly it’s just an awesome feeling to use your own software 😅.

The Vue Application

I created the vue application using the standard Vue CLI and added Vuetify so that it has some basic responsive styling. The app has one component called Radio.vue which holds all of the logic. The application has some preset radio stations that I can click as well as a text field where I can put in any URL of their choosing for play. It also grabs an RSS feed for a few of my favorite podcasts so I can quickly listen. Everything is done client side including the RSS XML parsing! You can view the live version here and clone the repo here.

Let’s Get Coding

As I stated above, I created a new Vue application using the vue-cli and added vuetify using the vue add vuetify command. For brevity I will skip that part and only talk about the Radio.vue component which holds all of the logic. This component will grab the preset stations and turn those into buttons. The favorited podcast RSS feeds it will grab, parse the XML and play said podcast. There is a URL text input that the user can manually put an audio stream URL in. Finally I set the Media Session metadata to show the cover art and info of whatever is playing and if I don’t have it show a default image, artist and album.

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12">
        <v-img
          :src="require('../assets/logo.png')"
          class="my-3"
          contain
          height="200"
        />
      </v-col>

      <v-col class="mb-4">
        <h1 class="display-2 font-weight-bold mb-3">
          Welcome to PWA Radio
        </h1>

        <p class="subheading font-weight-regular text-center">
          <v-text-field type="url" placeholder="Enter stream URL" v-model="url" label="Stream URL" />
        </p>
        <v-row class="text-center">
          <v-btn v-on:click="playAudio" v-if="!isPlaying">Play</v-btn>
          <v-btn v-on:click="stopAudio" v-else color="red">Stop</v-btn>
        </v-row>
      </v-col>
    </v-row>
    <v-row class="text-center">
      <v-btn class="pa-md-4 mx-lg-auto" v-for="x in presets" v-on:click="setAudio(x)" :key="x.name" :color="x.color"> {{x.name}} </v-btn>
    </v-row>
    <v-row class="text-center">
      <v-select
          v-model="currentPodcast"
          :hint="`${currentPodcast.name}, ${currentPodcast.author}`"
          :items="favoritePodcasts"
          item-text="name"
          item-value="url"
          label="Favorite Podcasts"
          persistent-hint
          return-object
          single-line
          @change="playPodcast"
        ></v-select>
    </v-row>
  </v-container>
</template>

<script>
  export default {
    name: 'Radio',

    data: () => ({
      isPlaying: false,
      audio: {},
      url : '',
      currentPodcast: {},
      selectedEpisode: {},
      presets : [
        {
          name: 'WEKU-NPR',
          url : 'https://playerservices.streamtheworld.com/api/livestream-redirect/WEKUFM.mp3',
          color: "green",
          author: 'NPR'
        },
        {
          name: 'WEKU-Classical',
          url: 'https://playerservices.streamtheworld.com/api/livestream-redirect/WEKUHD2.mp3',
          color: 'orange',
          author: 'NPR'
        },
        {
          name: 'Vocalo Radio',
          url: 'https://stream.wbez.org/vocalo128',
          color: 'blue',
          author: 'NPR'
        },
        {
          name: 'WFPK',
          url: 'https://lpm.streamguys1.com/wfpk-popup',
          color: 'yellow',
          author: 'NPR'
        },
        {
          name: 'KEXP',
          url: 'https://kexp-mp3-128.streamguys1.com/kexp128.mp3?listenerid=8044407b7410ad01f8210fd508279708&awparams=companionAds%3Atrue',
          color: '#cb349a',
          author: 'NPR'
        }
      ],
      favoritePodcasts: [],

      podcastURLS: [
        { url: 'https://anchor.fm/s/fdc3ac0/podcast/rss', name: 'Code Life' },
        { url: 'https://anchor.fm/s/42d5fca4/podcast/rss' , name: 'Intimate Spaces' },
        { url: 'https://feeds.npr.org/510289/podcast.xml', name: 'Project Money'}

      ]
    }),
    methods: {
      setMediaControls: function () {
        if ('mediaSession' in navigator) {
          navigator.mediaSession.metadata = new window.MediaMetadata({
            title: 'Pocket Radio',
            artist: 'J Computer Solutions LLC',
            album: 'Pocket Radio',
            artwork: [
              { src: 'https://radio.jcompsolu.com/images/logo-96.png',   sizes: '96x96',   type: 'image/png' },
              { src: 'https://radio.jcompsolu.com/images/logo-128.png', sizes: '128x128', type: 'image/png' },
              { src: 'https://radio.jcompsolu.com/images/logo-192.png', sizes: '192x192', type: 'image/png' },
              { src: 'https://radio.jcompsolu.com/images/logo-256.png', sizes: '256x256', type: 'image/png' },
              { src: 'https://radio.jcompsolu.com/images/logo-384.png', sizes: '384x384', type: 'image/png' },
              { src: 'https://radio.jcompsolu.com/images/logo-512.png', sizes: '512x512', type: 'image/png' },
            ]
          });

          navigator.mediaSession.setActionHandler('play', this.playAudio());
          navigator.mediaSession.setActionHandler('pause', this.pauseAudio());
          navigator.mediaSession.setActionHandler('stop', this.stopAudio());
          navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ });
          navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ });
          navigator.mediaSession.setActionHandler('seekto', function() { /* Code excerpted. */ });
          navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });
          navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ });
        }
      },
      playPodcast: function () {
        this.setAudio(this.currentPodcast)
        this.playAudio()
      },
      playAudio: function () {
        if(this.isPlaying){
          this.isPlaying = false
          this.audio.pause()
          this.audio = {}
        }
        this.audio = new Audio(this.url)
        this.isPlaying = true
        this.audio.play()
          .then(()=> {
        }).catch(error => { console.log(error) });
      },
      pauseAudio: function () {
        this.audio.pause()
        this.isPlaying = false
      },
      stopAudio: function () {
        this.audio.pause()
        this.audio = {}
        this.isPlaying = false
      },
      setAudio: function(preset) {
        this.url = preset.url
        navigator.mediaSession.metadata.title = preset.name
        navigator.mediaSession.metadata.artist = preset.author
        if(preset.image) {
          navigator.mediaSession.metadata.artwork = [
            { src: preset.image }
          ]
        }
        this.playAudio()
      }
    },
    mounted () {
      this.setMediaControls()
    },
    created () {
      this.podcastURLS.forEach(pod => {
        fetch(pod.url)
        .then(response => response.text())
        .then(str => new window.DOMParser().parseFromString(str, "text/xml"))
        .then(data => {
          const items = data.querySelectorAll("item");
          for (let i = 0; i < items.length; i++) {
            let item = items[i];
            console.log(item)
            let image = item.getElementsByTagName("itunes:image")[0].getAttribute("href")
            let title = item.querySelector("title").innerHTML.replace("<![CDATA[", "").replace("]]>", "")
            let author = item.getElementsByTagName("dc:creator")[0].innerHTML.replace("<![CDATA[", "").replace("]]>", "")
            let url = item.querySelector("enclosure").getAttribute("url")
            let podcast = { name: title, url: url, image: image, author: author }
            this.favoritePodcasts.push(podcast)
          }
        })
      })
    }
  }
</script>

Conclusion

This was a fun and easy PWA to make and I will turn it into an Android application to put on the Google Play Store (learn how with my PWA to APK course). Some features I will add will include:

  • save favorites locally using indexDB
  • create queue that can be skipped
  • download podcast episodes
  • Have everything play via the WebAudio API and add visualizations.
Posted on Leave a comment

Building A Twitter Discord Bot In Node.JS

Discord Is Awesome, So Is Twitter

I have a discord server and I have a pretty decent sized Twitter following. I wanted to add a bot that followed my tweets and sent them as messages in my #twitter channel on my server. I refuse to pay for software and I have a hyper distrust of other’s software so I wrote my own. In this node.js script I have one file main.js that uses 3 dependencies: twit (for Twitter streaming API), Discord.js (for well….Discord) and dotenv (to load environment variables). The script is ~30 lines long and is available on my Github.

Create a Discord Bot using the Twitter Streaming API

Main.js

require('dotenv').config()
const Twit = require('twit')
const Discord = require('discord.js');
const client = new Discord.Client();
var T = new Twit({
  consumer_key:         process.env.TWITTER_CONSUMER_KEY,
  consumer_secret:      process.env.TWITTER_CONSUMER_SECRET,
  access_token:         process.env.TWITTER_ACCESS_TOKEN,
  access_token_secret:  process.env.TWITTER_ACCESS_TOKEN_SECRET,
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  strictSSL:            true,     // optional - requires SSL certificates to be valid.
})
client.login(process.env.DISCORD_TOKEN);
client.once('ready', () => {
  var stream = T.stream('statuses/filter', { follow: [process.env.TWITTER_USER_ID] })
  stream.on('tweet', function (tweet) {
    //...
    var url = "https://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id_str;
    try {
        let channel = client.channels.fetch(process.env.DISCORD_CHANNEL_ID).then(channel => {
          channel.send(url)
        }).catch(err => {
          console.log(err)
        })
    } catch (error) {
            console.error(error);
    }
  })
})

.env file to load variables.

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=
TWITTER_USER_ID=
DISCORD_TOKEN=
DISCORD_CHANNEL_ID=

Now all you have to do is run it using the following command

node main.js

Don’t forget to get your application keys from the Discord developer portal and the Twitter developer portal. I made a Youtube video showing the process in detail. Want to start making money and living a #CodeLife? Join the group today!

Posted on 1 Comment

How I Wrote And Deployed A Mobile App Using Nativescript & Vue

Nativescript Is Awesome!

Two days ago I put out Relaxing Sounds. RS is a android(soon to be iOS) productivity application that plays various white noise sounds like thunderstorms and ocean waves. I wrote this app using Nativescript and Vue.js in a matter of 3 hours. Now keep in mind:

  1.  This is a simple app.
  2.  I just wanted to get my hands dirty with the core framework and have something to show for it.

I integrated admob and created a free and a pro version with plans to update the application to include a relaxing sounds livestream for 24 hr continuous new calming content. I was blown away by how fast I was able to transition from the DOM to Nativescript XML. If you don’t know anything about Nativescript then check out my blog post about it.

How Did I Write It So Fast?

Well once I understood the Nativescript system (which in itself only took a couple hours to understand and master) it was just a simple matter of how well do I know Vue.js? That’s the beauty of Nativescript! It abstracts the headache of interacting with the native hardware so your mind can stay in a purely web development mode. If you can write a PWA with Vue.js then you can write a truly native mobile application with Vue.js there really isn’t any excuse. Couple Nativescript with Vue.js and Laravel for your backend API and you can be a one man (or woman) code army.

Why Did I Write Relaxing Sounds?

I have always been a fan of using calming distracting audio; Whether it be while I code, sleep, meditate or study. I have downloaded apps in the past that have provided that functionality but for one reason or another I deleted them. So to remedy the problem I just wrote my own application. 

What Are My Future Plans For RS?

Really after my next release to add the livestream I don’t plan on giving it much attention development wise. I will study the analytics and create a marketing campaign if the data says it is worth it. Otherwise it is just another notch on my project belt and I will continue to use for my own personal enjoyment. If you want to support me then please download my application and rate it with comments! If you really enjoy it then I ask that you purchase the pro version for $1.99.

Posted on 1 Comment

An Introduction To Nativescript with Vue

What Is Nativescript?

Nativescript is a new javascript framework that allows you to create TRULY native mobile apps using the V8 engine and JavascriptCore engine for Android and iOS respectively. Using Nativescript you can create the mobile app of your dreams using the web technologies you already know and love. 

How Did You Hear About It?

It’s funny actually. Last year I was reading documentation on Laravel’s website and saw an ad for Nativescript. It intrigued me so I decided to click the ad and instantly was glad I did. Although the project looked very promising, the Vue.js integration wasn’t complete yet and I wasn’t interested in going back to Angular so I left it alone. A few months later nativescript-vue was released and I came running back.

What Are The Advantages To Using Nativescript?

  1. Well the first one is that you actually get native performance. This isn’t like Ionic or Cordova where your web app is hosted in a WebView running inside an app container. This is actual transpiled code from web technologies to mobile technologies.
  2. Low learning curve. Since you can develop using Vue and all Vue extensions there is no extra learning curve as far as syntax is concerned. Just setup the environment and you are ready to turn your web applications into native mobile applications. If you want an intro to Vue.js check out my video course.
  3. Extensive marketplace. The Nativescript ecosystem allows developers to create packages and are managed by npm. Easily extend the functionality of your mobile applications.
  4. It’s FREE. Nativescript is free and open source to use for free and commercial use and has an Apache 2 license.

Want A More In Depth Explanation?

Watch my Youtube video and learn more about the power of Nativescript and even start on an example mobile application! Don’t forget to like and share the video and subscribe to my channel!

Posted on Leave a comment

Create An Encryption Based Anonymous Messenger

Secure Your Messages With Laravel Encryption

Encryption is the best tool in this fight for your right to privacy. Now more than anytime in history privacy is of the essence. In today’s tutorial I will show you how to create a simple messenger service in Laravel and Vue.js; however they will be password protected and encrypted therefore the receiver must know the password beforehand to read the message. All code can be found on my Github repo.

Setting Up The Backend

The application itself has only one model and that is the Message model. It has 3 properties: content, email and passphrase. The content stores the encrypted message. The email is the email address of who is receiving the message. Finally the passphrase is the password that protects the message from being opened by anybody.
php artisan make:model -m Message
Open the Message.php file and make it Notifiable and change the $fillable


<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
use Notifiable;
//
public $fillable = ['content','passphrase','email'];
}

 
Next open up the migration file that was created with the model and add the following:


<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->longText('content');
$table->string('passphrase');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}

Next create the controller. This controller will be RESTful with an extra method for decrypting the messages.


php artisan make:controller --resource MessageController

Open the file and fill in the methods store(), show() and decrypt()


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Notifications\MessageCreated;
use Illuminate\Contracts\Encryption\DecryptException;
class MessageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$message = Message::Create([
'content' => encrypt($request->content),
'passphrase' => encrypt($request->password),
'email' => $request->email
]);
$message->notify(new MessageCreated($message));
return response()->json($message);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
$message = Message::findOrFail($id);
return view('message')->with([
'message' => $message
]);
}
public function decrypt(Request $request, $id){
try{
$message = Message::findOrFail($id);
if($request->password == decrypt($message->passphrase)){
$message = decrypt($message->content);
$with = [
'message' => $message
];
return response()->json($with);
}
}
catch (DecryptException $e){
return response()->json($e);
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

 
As you can see there is a call to a notification that has not been created yet so create it


php artisan make:notification MessageCreated

 
Open that up and replace it with the following which will call the toMail method and alert the recipient they have a new message to view


<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class MessageCreated extends Notification
{
use Queueable;
public $message;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(\App\Message $message)
{
//
$this->message = $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('You have a new encrypted message.')
->line('You should have been given the passphrase')
->action('Decrypt and Read Now!', url('/message/'.$this->message->id))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}

Lastly the api and web routes need to be updated
In web.php


<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('home');
});
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/message/{id}','MessageController@show');

In api.php


<?php
use Illuminate\Http\Request;
/* |-------------------------------------------------------------------------- | API Routes Fr */
Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });
Route::resource('/message','MessageController');
Route::post('/decrypt-message/{id}','MessageController@decrypt');

Lastly let’s create the view files. As a shortcut I scaffold authentication even though we aren’t using it to get the bootstrap layouts and the home.blade.php file. Copy the home.blade.php file to another file called message.blade.php.
In home.blade.php


@extends('layouts.app')
@section('content')
<send-message></send-message>
@endsection

 
In message.blade.php


@extends('layouts.app')
@section('content')
<read-message v-bind:message="{{$message}}"></read-message>
@endsection

That’s it, the back end is complete!
 

Front End

The Vue.js side of things is pretty simple there are two components a MessageSend and a MessageRead. Create a file in your resources/assets/js/components folder called MessageSend.vue and MessageRead.vue.
 
In MessageSend.vue


<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Send Encrypted Message</div>
<div class="card-body">
<div class="form-group">
<input type="email" placeholder="Enter email address" class="form-control" v-model="message.email">
</div>
<div class="form-group">
<input type="password" placeholder="Enter passphrase" class="form-control" v-model="message.password">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Enter Message" v-model="message.content"></textarea>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary" v-on:click="send()">Send Message</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
message: {}
}
},
methods: {
send: function(){
axios.post('/api/message',this.message).then(data =>{
console.log(data);
alert('Message Sent!');
}).catch(err => {
console.log(err);
})
}
}
}
</script>

 
In MessageRead.vue


<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Read Encrypted Message</div>
<div class="card-body">
<div class="form-group">
<input type="password" placeholder="Enter passphrase" class="form-control" v-model="password">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Enter Message" v-model="msg.content"></textarea>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary" v-on:click="decrypt()">Decrypt Message</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
password: '',
msg : this.message
}
},
props: ['message'],
created(){
},
methods: {
decrypt: function(){
var that = this;
axios.post('/api/decrypt-message/'+this.message.id,{password:this.password}).then(data =>{
that.message.content = data.data.message;
}).catch(err => {
console.log(err);
})
}
}
}
</script>

In your resources/assets/js/app.js file don’t forget to add your components


/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('send-message', require('./components/MessageSend.vue'));
Vue.component('read-message', require('./components/MessageRead.vue'));
const app = new Vue({
el: '#app'
});

 

Posted on Leave a comment

Create A Point Of Sales System With Laravel, Vue and Stripe – Part 4

Stripe Subscriptions

In part 4 we add recurring billing to our point of sales system by utilizing Stipe Subscriptions. Subscriptions in conjunction with our customers created in part 3 allows for easy tracking of expenses and opens the way for residual income. Next up we add inventory management to the system! For the source code click here and don’t forget to subscribe to the YouTube channel!