Implementing the Feedback section on Skills CMS

In this blog post, we are going to implement the Skill feedback system on the Skills CMS. The features that are added by this implementation are displaying all the comments/feedbacks of the user, ability to add new feedback and also option to edit a previous feedback that was added.

The UI interacts with the back-end server via two APIs –

Detailed explanation of the implementation

  • The first task was to create a separate component for the feedback section – SkillFeedbackCard.js, along with the CSS file SkillFeedbackCard.css
  • Create ES6 function to get all the Feedbacks of a skill,namely getFeedback(), on the parent component, i.e, SkillListing.js
getFeedback = () => {
    let getFeedbackUrl = `${urls.API_URL}/cms/getSkillFeedback.json`;
    let modelValue = 'general';
    this.groupValue = this.props.location.pathname.split('/')[1];
    this.languageValue = this.props.location.pathname.split('/')[3];
    getFeedbackUrl = getFeedbackUrl + '?model=' + modelValue + '&group=' + this.groupValue + '&language=' + this.languageValue + '&skill=' + this.name;

    let self = this;
    // Get skill feedback of the visited skill
    $.ajax({
        url: getFeedbackUrl,
        dataType: 'jsonp',
       crossDomain: true,
        jsonp: 'callback',
        success: function (data) {
            self.saveSkillFeedback(data.feedback);
        },
        error: function(e) {
            console.log(e);
        }
    });
};

saveSkillFeedback = (feedback = []) => {
    this.setState({
        skill_feedback: feedback
    })
}

 

  • This above code contains the function getFeedback(), that makes an API call to the server for getting all the feedbacks. On successfully getting the response, the feedback array of the response is then passed to a function, saveSkillFeedback(), which in turn updates the skill_feedback state, which was declared in the constructor. This re-renders the components and displays the feedback in the UI.
{
  "feedback": [
    {
      "feedback": "Awesome skill!",
      "email": "coolakshat24@gmail.com",
      "timestamp": "2018-06-12 19:28:39.297"
    },
    {
      "feedback": "Awesome skill!",
      "email": "akshatnitd@gmail.com",
      "timestamp": "2018-06-12 21:35:53.048"
    }
  ],
  "session": {"identity": {
    "type": "host",
    "name": "141.101.98.18_a7ab9c4d",
    "anonymous": true
  }},
  "skill_name": "aboutsusi",
  "accepted": true,
  "message": "Skill feedback fetched"
}

 

  • Then, we go ahead and create the function that is responsible for posting new feedback and editing them as well.
postFeedback = (newFeedback) => {

    let baseUrl = urls.API_URL + '/cms/feedbackSkill.json';
    let modelValue = 'general';
    this.groupValue = this.props.location.pathname.split('/')[1];
    this.languageValue = this.props.location.pathname.split('/')[3];
    let postFeedbackUrl = baseUrl + '?model=' + modelValue + '&group=' + this.groupValue + '&language=' + this.languageValue + '&skill=' + this.name + '&feedback=' + newFeedback + '&access_token='+cookies.get('loggedIn');

    let self = this;
    $.ajax({
        url: postFeedbackUrl,
        dataType: 'jsonp',
        jsonp: 'callback',
        crossDomain: true,
        success: function (data) {
            self.getFeedback()
        },
        error: function(e) {
            console.log(e);
        }
    });
};

 

  • This above code snippet contains the function postFeedback(newFeedback), that takes the user feedback and make an API call to update it on the server.
  • All the required functions are ready. Now we add the SkillFeedbackCard.js component on the SkillListing.js component and pass useful data in the props.
<SkillFeedbackCard
    skill_name={this.state.skill_name}
    skill_feedback={this.state.skill_feedback}
    postFeedback={this.postFeedback}
/>
  • The next step is creating the UI for the SkillFeedbackCard.js component. We have used standard Material-UI components for creating the UI, that includes List, ListItem, Divider, IconButton, etc.
  • Code snippet for the Feedback ListItem  –
<ListItem
    key={index}
    leftAvatar={<CircleImage name={data.email.toUpperCase()} size='40' />}
    primaryText={data.email}
    secondaryText={<p> {data.feedback} </p>}
/>

 

  • The next part of the UI implementation creating option to edit and post feedback.
  • Code snippet for the Post feedback section  –
className=“feedback-textbox”> id=“post-feedback” hintText=“Skill Feedback” defaultValue=“” errorText={this.state.errorText} multiLine={true} fullWidth={true} /> label=“Post” primary={true} backgroundColor={‘#4285f4’} style={{ margin: 10 }} onClick={this.postFeedback} />

 


 

  • For the edit section, I have used a Dialog box for it. Code snippet for the Edit feedback section  –
<Dialog
    title="Edit Feedback"
    actions={actions}
    modal={false}
    open={this.state.openDialog}
    onRequestClose={this.handleClose}
>
    <TextField
        id="edit-feedback"
        hintText="Skill Feedback"
        defaultValue={userFeedback}
        errorText={this.state.errorText}
        multiLine={true}
        fullWidth={true}
    />
</Dialog>

 

This was the implementation for the Skill Feedback System on the Skills CMS and I hope, you found the blog helpful in making the understanding of the implementation better.

Resources

 

Continue ReadingImplementing the Feedback section on Skills CMS

Creating the View Route for Sessions in Open Event Frontend

This blog article will illustrate how the creation of the view route for sessions is done and how the sessions API is integrated with it on Open Event Frontend, which allows for the sessions and their associated data to be displayed. Also, it illustrates how the template for my-sessions is modified to make it possible to reuse it for the view route with desired changes.

The primary end point of Open Event API with which we are concerned with for fetching the the session details is

GET /v1/sessions/{session_identifier}

For displaying the complete session information on the view route, the session type,  speakers and session track are also required. All of these extra attributes have a relationship with a given session and hence can be fetched in a single query. Thus the model for the route is defined as follows:

model(params) {
return this.store.findRecord(‘session’, params.session_id, {
include: ‘session-type,speakers,track’
});

The view route is located at app/routes/my-sessions/view and the parent route, app/routes/my-sessions has another sub route within it called list. The list route shows upcoming and past sessions to the user based on the params passed to it. Thus a navigation is required to alternate between those two routes. However, this navigation should not be present in the view route. Thus the template my-sessions.hbs is modified as follows:

{{#if (and (not-includes session.currentRouteName ‘my-sessions.view’))}}
<h1 class=”ui header”>{{t ‘My Sessions’}}</h1>

{{#tabbed-navigation}}
{{#link-to ‘my-sessions.list’ ‘upcoming’ class=’item’}}
{{t ‘Upcomming Sessions’}}
{{/link-to}}
{{#link-to ‘my-sessions.list’ ‘past’ class=’item’}}
{{t ‘Past Sessions’}}
{{/link-to}}
{{/tabbed-navigation}}

</div>
{{outlet}}
</div>
{{else}}
{{outlet}}
{{/if}}

The session.currentRouteName property allows conditional rendering of the navigation component.

Finally the template for the view route is created:

   

{{#if (eq model.state ‘accepted’)}}

{{t ‘Accepted’}}

{{else if (eq model.state ‘pending’)}}

{{t ‘Pending’}}

{{else if (eq model.state ‘rejected’)}}

{{t ‘Rejected’}}

{{/if}}
</div>

{{t ‘From ‘}}{{moment-format model.startAt ‘ddd, MMM DD HH:mm A’}}{{t ‘ to ‘}}{{moment-format model.endsAt ‘ddd, MMM DD HH:mm A’}}

</div>

{{#if model.shortAbstract}}
<p> <i>{{model.shortAbstract}}</i> </p>
{{/if}}
{{#if model.sessionType.name}}
<h3 class=”ui left aligned header”>Session Type</h3>
<p>{{model.sessionType.name}}</p>
{{/if}}
{{#if model.track.name}}
<h3 class=”ui left aligned header”>Track</h3>
<p>{{model.track.name}}</p>
{{/if}}
{{#if model.slidesUrl}}
<h3 class=”ui left aligned header”>Slide</h3>
<a href=”{{model.slidesUrl}}”>{{t ‘Download’}}</a>
{{/if}}
</div>

Based on the state property of the session, the label displaying the status is appropriately coloured wherein green, yellow and red colours denote accepted, pending and rejected sessions respectively. Since most of the fields of the session model are optional in nature, all of the them are subjected to conditional checks for existence.

Resources

 

Continue ReadingCreating the View Route for Sessions in Open Event Frontend

How does live preview work on SUSI AI chatbot wizard

Live preview is an important feature for the chatbot building process in SUSI.AI botbuilder. It tells the bot creator how the bot looks and behaves at any time.

We use iframe for creating a live preview.

What is iframe?

Frames allow browser window to be split into separate segments. All these segments can be used for displaying a different webpage within the browser window.

is an HTML tag. iframe stands for “inline frame”. It places another HTML document in a frame. The content of the element is used as an alternative text to be displayed if the browser does not support inline frames.

This was first introduced by Microsoft Internet Explorer in 1997, standardized in HTML 4.0 transitional and allowed in HTML5.

Syntax:

<iframe src=”URL”></iframe>

Some attributes:

  • Height
  • Width
  • Name
  • Id

Code used for preview of chatbot screen:

<iframe title="botPreview" name="frame-1" id="frame-1" src={locationBot} height="600px" style={styles.iframe}></iframe>

Code used for preview of chatbot avatar:

<iframe title="botAvatarPreview" name="frame-2" id="frame-2" src={locationAvatar} height="100px" style={styles.iframe}></iframe>

Preview bot fetches the current theme status and skill status from SUSI server and then applies it to the chatbot. Now, this details will be unique to the user logged in. Hence, we need to somehow identify the person logged in. This is done using access token stored in the cookies which is accessed through cookies.get(‘loggedIn’).

How to pass access token to iframe?

This is the major issue faced when creating preview using iframe because even though the HTML window in iframe is rendered on the same parent page, we can not access the elements of HTML page inside iframe. This is because iframe loads dynamically. There are few solutions for this problem.

One of them is to create a script in iframe that would run when iframe is loaded. Now this script can access the elements of parent window (the one containing iframe) using window.parent.document.getElementById(‘#target’)

The best solution is however to pass the access token in the URL of the source of iframe. Then this can be accessed by HTML page in frame using location.href .

Code sample to pass access token in url:

src = '/BotPreview.html?access='+cookies.get('loggedIn')

Now, we have to split this URL and get the access token. This can be easily done using the following script.

var url = location.href.split(‘?’)[1].split(‘=’);
var access_token = url[1];

Here in this example, the url variable firstly splits the URL at ‘?’. This creates an array with two elements.

[‘url.com/BotPreview.html’, ‘access=abcdef123’]

Then we access the element on index 1, i.e. ‘access=abcdef123’ and split it at the ‘=’. This further creates an array of two elements.

[‘access’, ‘abcdef123’]

Now, we can access the access token which is at index 1 in this array.

References

Continue ReadingHow does live preview work on SUSI AI chatbot wizard

Displaying skill rating for each skill on skill page of SUSI SKILL CMS

SUSI exhibits several skills which are managed by the SUSI Skill CMS, it essentially is a client which allows users to create/update skills conveniently since for each skill it is important to have the functionality of rating system so developers can get to know which skills are performing better than the rest and consequently improve them, thus a skill rating system which allows the users to give positive or negative feedback for each skill is implemented on the server.

Fetching skill_rating from the server

  1. Fetch skill data for which ratings are to be displayed through ajax calls
    API Endpoint –

    /cms/getSkillMetadata.json?
    

  2. Parse the received metadata object to get positive and negative ratings for that skill
  3. if(skillData.skill_rating) {
           	let positive_rating = skillData.skill_rating.positive;
            	let negative_rating = skillData.skill_rating.negative;
    }
    

    Sample API response

    {
      "skill_metadata": {
        "model": "general",
        "group": "Knowledge",
        "language": "en",
        "developer_privacy_policy": null,
        "descriptions": "Want to know about fossasia, just ask susi to tell that, Susi tells about the SUSI.AI creators",
        "image": "images/creator_info.png",
        "author": "madhav rathi",
        "author_url": "https://github.com/madhavrathi",
        "author_email": null,
        "skill_name": "Creator Info",
        "terms_of_use": null,
        "dynamic_content": false,
        "examples": [
          "Who created you?",
          "what is fossasia?"
        ],
        "skill_rating": {
          "negative": "0",
          "positive": "0",
          "stars": {
            "one_star": 0,
            "four_star": 0,
            "five_star": 0,
            "total_star": 0,
            "three_star": 0,
            "avg_star": 0,
            "two_star": 0
          },
          "feedback_count": 0
        },
        "creationTime": "2018-03-17T16:38:29Z",
        "lastAccessTime": "2018-06-15T15:51:50Z",
        "lastModifiedTime": "2018-03-17T16:38:29Z"
      },
      "accepted": true,
      "message": "Success: Fetched Skill's Metadata",
      "session": {"identity": {
        "type": "host",
        "name": "162.158.166.37_d80fb5c9",
        "anonymous": true
      }}
    }
    

  4. Set the react state of the component to store positive and negative rating.
  5. this.setState({
      positive_rating,
      negative_rating
    })
    

  6. Use react-icons to fetch like and dislike icon components from font-awesome.
  7. npm i -S react-icons
    

  8. Import the corresponding icons in the SkillPage component
  9. import { FaThumbsOUp, FaThumbsODown } from 'react-icons/lib/fa/'
    

  10. Display the rating count along with their icons
  11. <div className="rating">
        <div className="positive">
             <FaThumbsOUp />
             {this.state.positive_rating}
         </div>
           <div className="negative">
                 <FaThumbsODown />
                 {this.state.negative_rating}
             </div>
    </div>
    

Example

References

Continue ReadingDisplaying skill rating for each skill on skill page of SUSI SKILL CMS

Use of Flux Architecture in SUSI.AI

SUSI Web Chat is based on Flux, a React.js Architecture. It provides a simple way for implementing many features in SUSI Web Chat. This blog post explains how Flux Architecture works, and also how it is used in SUSI Web Chat to implement the feature of switching between Light and Dark themes.

What is Flux?

Flux is a micro-architecture for software application development. It is the application architecture that Facebook uses for building client-side web applications. It complements React’s composable view components by utilizing a unidirectional data flow.

Flux Overview

As can be seen from the above diagram, Flux has four main components:

Component Description
Actions Helper methods that pass data to the Dispatcher.
Dispatcher Receives these Actions and broadcast payloads to registered callbacks.
Stores The Stores that are registered to the Dispatcher will update the Views accordingly.
Views  Views are actually React Components that grab the state from the stores and then pass it down to the child components.

How these 4 components work together?

  • Application Initialisation:
    1. Stores let the registered Dispatcher know that they want to be notified whenever an action comes in.
    2. Then the controller views ask the stores for the latest state.
    3. When the stores give the state to the controller views, they pass that state along to their child views to render.
    4. The controller views also ask the stores to keep them notified when state changes so that they can re-render accordingly.
  • The Data Flow:

Once the setup is done, the application is ready to accept user input. So let us trigger an action by having the user make a change.

    1. The view tells the action creator to prepare an action.
    2. The action creator formats the action and sends it off to the Dispatcher.
    3. The Dispatcher dispatches the action off to all of the stores in sequence. Then the store decides whether it cares about this action or not, and changes the state accordingly.
    4. Once it’s done changing state, the store lets its subscribed view controllers know.
    5. Those view controllers will then ask the store to give them the updated state.
    6. After the store gives it the state, the view controller will tell its child views to re-render based on the new state.

So this is how Flux works. Now let us see an example of Flux being used in SUSI Web Chat.

Use of Flux Architecture to Switch Between Themes in SUSI Web Chat

Different Flux components used in SUSI Web Chat:

  1. Actions – Settings.actions.js
  2. Dispatcher – ChatAppDispatcher.js
  3. Store – UserPreferencesStore.js
  4. View – MessageSection.react.js

Let us now see in detail how we are able to switch themes:
In the MessageSection.react.js file, we have the following functions to handle theme change:

handleThemeChanger = () => {
    //code
    this.applyLightTheme();
}

applyLightTheme = () =>{
    //code
    Actions.settingsChanged(settingsChanged);
}

 
Hence, the view tells the action creator to prepare an action.
Now, the settingsChanged() function in Settings.actions.js file is called as follows:

export function settingsChanged(settings) {
    ChatAppDispatcher.dispatch({
    type: ActionTypes.SETTINGS_CHANGED,
    settings
});
    //code
}

 
Hence, the process of invoking the callbacks is initiated through the dispatch() method, which takes a data payload object as its sole argument.

Now, as the UserPreferencesStore is registered with the ChatAppDispatcher, it receives the actions dispatched by the Dispatcher. It checks for the type of action, and with the help of switch cases, executes the code for the corresponding action type accordingly. In this case, the states inside the Store are updated with the new state which the User wants to switch to.

UserPreferencesStore.dispatchToken = ChatAppDispatcher.register(action => {
    switch (action.type) {
        //code
        case ActionTypes.SETTINGS_CHANGED: {
            let settings = action.settings;
            //code
            UserPreferencesStore.emitChange();
            break;
        }
        //code
    }
});

 
This is how Flux Architecture is facilitating the switching of themes in SUSI Web Chat.

Resources

 

Continue ReadingUse of Flux Architecture in SUSI.AI

Displaying all the images from storage at once in Phimpme Android Application

In the Phimpme Android application, the images are displayed in the albums in which they are indexed in the device’s storage. However, there is also an “All photos” section in the application where all the images present in the device’s storage are displayed at once irrespective of the folder they’re indexed in. So in this post, I will be discussing how we achieved the “All Photos”  functionality.

Android framework provides developers with a media content provider class called MediaStore. It contains metadata for all available media on both internal and external storage devices. With the help of particular methods we can obtain metadata for all the images stored in the device’s storage.

Step 1

So First we need to get the Uri from MediaStore content provider pointing to the media(here media refers to the photos stored on the device). This can be done by the following snippet of code.

Uri uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

Step 2

Now retrieving a cursor object containing the data column for the image media is required to be performed. The data column will contain the path to the particular image files on the disk. This can be done by querying the MediaColumns table of the MediaStore class, which can be performed by the use of the content resolver query method. The mentioned functionality can be achieved by the following lines of code.

String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = activity.getContentResolver().query(uri, projection, null, null, null);

Step 3

In the final step, we would retrieve the path of all the images by iterating through the cursor object obtained in the previous step and keep adding those paths to an ArrayList<String>. Creating Media objects passing in the image path and concurrently adding those Media objects to an ArrayList<Media> to be done thereafter. Finally, the dataset(ArrayList<Media> in this case) containing Media objects for all the images is required to be passed to the Media Adapter in order to display all the photos in the UI. The code snippets used for the final steps are provided below.

while (cursor.moveToNext()) {
  absolutePathOfImage = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));
  listOfAllImages.add(absolutePathOfImage);
}
ArrayList<Media> list = new ArrayList<>();

for (String path : listOfAllImages) {
  list.add(new Media(new File(path)));
}
return list;

This is how we achieved the functionality to display all the images from the storage on a single screen(at once) in the Phimpme Android application. To get the full source code, please refer to the Phimpme Android Github repository listed in the resource section below.

The screenshot for displaying the “All photos” section is provided below.

Resources

1.Android Developer Guide – https://developer.android.com/reference/android/provider/MediaStore

2.Github-Phimpme Android Repository – https://github.com/fossasia/phimpme-android/

3.Displaying all the images from gallery in android – https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/

Continue ReadingDisplaying all the images from storage at once in Phimpme Android Application

Adding System Image for Event Categories

The Open Event Server is using the JSON 1.0 Specification and build on top of Flask Rest Json API (for building Rest APIs) and Marshmallow (for Schema). In this blog, we will talk about how to add feature of System Image for Event Categories on Open Event Server. The focus is on Model updation, Schema updation and migrating the Database.

Model Updation

For adding System Image, we’ll update our Model EventTopic.

In this feature, we are providing rights to the Admin to add a system image for each Event Category so that if no image is given by a organizer of event on event creation then it will use the system image of that Event Category as event image by default.

Here we are adding a Column named system_image_url which is of type String. This value cannot be nullable and having a default value.

Migrating the Database

For the migrating the Database we will use simple commands.

This command runs migrations. If it cause problems naming Multiple Migration Head, then you need to run

This problem is caused when two developers push a migration file without merging two heads to achieve one head.

The above command will give us ids of two migration heads.

This command is merging two migration heads.

This command is upgrading the migrations.

Finally, we migrate the Database using above command.

Schema Updation

For the system image, we’ll update the Schema EventTopicSchema as follows

In this feature, to provide system image for each Event Category we’ll add a field named system_image_url in the Schema.

Here we are adding a field named system_image_url which is of marshmallow field type URL. This value cannot be none.

Validating the Event Image and using System Image by default

In this step, we’ll check if a event image is provided by organizer. If that is not provided then we’ll use system image of Event Category as Event Image.

Here, we will first take the event topic of event as added by the organizer. Then we will fetch the the database row in Event Topic model which has id == event_topic_id . Then we will return the system image url of that event topic to the event image.

So we saw how we could provide a default image for any event.

Resources

Continue ReadingAdding System Image for Event Categories

Adding option to Unfavourite image in Phimp.Me

This blog is in accordance with the P.R #1900. Here I have implemented the option to unfavourite image in the Phimp.Me android application.

Implementation

In the Phimp.Me app there are the following modes present:

1. all_photos:

All the photos are displayed in this mode irrespective of where they are saved.

2. fav_photos:

The photos which are added to favourites are displayed in the fav_photos.

3. Albums_mode:

All the albums which are present in the app are displayed in the albums_mode.

The main idea here is to find whether the selected image is already FAVOURITE or not. If it is already FAVORITED then it can be removed from that mode by removing its path form the Realm Database. If it isn’t already FAVORITED then the image is ignored and the next image is taken into consideration.

The process of removing the images from favourites can be an expensive one as the user can select myriad images which would ultimately block the Main UI. So it is better handled asynchronously and is implemented using the AsyncTask.

Whenever the user adds an image to the FAVOURITES, it gets added to the Realm Database where the model class being used is the FavouriteImagesModel.The selected media in the all_photos and fav_photos mode can be accessed via by selectedMedia.size()  and the number of selected media in the albums_mode can be accessed by getAlbum().getSelectedCount().

So in the execute method of doInBackground() a condition check is initially made and then 2 separate loops are run depending upon the mode in which the selected images exist.

Initially it is checked whether the selected image is already a FAVOURITE one or not by the following code. If it belongs to the favourite mode then the size of the favouriteImageModels would become 1.

RealmResults<FavouriteImagesModel> favouriteImagesModels = realm.where
                                               (FavouriteImagesModel.class).equalTo(“path”, selectedMedias.get(i).getPath( )).findAll( );

If ( favouriteImagesModels.size( ) == 1) {
            favouriteImagePresent = true;
             imagesUnfavourited++;
   }

Now as the image belongs to the favourite mode we ultimately use the following code to remove the image from FAVOURITES.

 favouriteImagesModels.deleteAllFromRealm();

The full code which handle the option to unfavourite an image is shown below.

@Override
                   protected Boolean doInBackground(String arg0) {
                    

        if ( all_photos || fav_photos )   {


                           realm = Realm.getDefaultInstance();
                           realm.executeTransaction ( new Realm.Transaction( ) {
                               

                               @Override
                               public void execute (Realm realm)  {
                                   for (int i = 0 ;  i < selectedMedias.size( ) ;  i++) {
                                       RealmResults<FavouriteImagesModel> favouriteImagesModels = realm.where
                                               (FavouriteImagesModel.class).equalTo(“path”, selectedMedias.get(i).getPath( )).findAll( );
                                       If ( favouriteImagesModels.size( ) == 1) {
                                           favouriteImagePresent = true;
                                           imagesUnfavourited++;
                                       }


                                       favouriteImagesModels.deleteAllFromRealm();
                                   }
                               }
                           });
                       }

         else if ( !fav_photos && !albumsMode ) {
                           realm = Realm.getDefaultInstance();
                           realm.executeTransaction(new Realm.Transaction() {
                           

                              @Override
                               public void execute(Realm realm) {
                                   for (int i = 0;  i < getAlbum().getSelectedCount();  i++) {
                                       RealmResults<FavouriteImagesModel> favouriteImagesModels = realm.where
                                               (FavouriteImagesModel.class).equalTo(“path”, getAlbum( ).getSelectedMedia(i).getPath( ) ).findAll( );
                                       If ( favouriteImagesModels.size() == 1) {
                                           favouriteImagePresent = true;
                                           imagesUnfavourited++;
                                       }
                                       favouriteImagesModels.deleteAllFromRealm();
                                   }
                               }
                   }

After the doInBackground( ) method has been executed the onPostExecute( ) comes into play and some other UI related changes are done such as a SnackBar message is shown if the image is removed from favourites.

Resources

  • Realm for Android

https://realm.io/blog/realm-for-android/

  • Asynchronous Transactions in Realm

https://realm.io/docs/java/latest/#working-with-realmobjects

 

Tags: GSoC18, FOSSASIA, Phimp.Me, Unfavourite image, Realm  

Continue ReadingAdding option to Unfavourite image in Phimp.Me

Using a Git repo as a Storage & Managing skills through susi_skill_cms

In this post, I’ll be talking about SUSI’s skill management and the workflow of creating new skills

The SUSI skills are maintained in a separate github repository susi_skill_data which provides the features of version controlling and the ability to rollback to a previous version implemented in SUSI Server.

The workflow is as explained in the featured image of this blog, SUSI CMS provides the user with a GUI through which user can talk to the SUSI Server and using it’s api calls, it can manipulate the susi skills present/stored on the susi_skill_data repository.

When the user opts to create a new skill, a new createSkill component is loaded with an editor to define rules of the skill. Once the form is submitted, an AJAX POST request is made to the server which actually commits the skill data to the repository and thus it is visible in the CMS from that point on.

Grab the skill details within the editor and put them in a form which is to be sent via the POST request.

let form = new FormData();
form.append('model', 'general');
form.append('group', this.state.groupValue);
form.append('language', this.state.languageValue);
form.append('skill', this.state.expertValue.trim().replace(/\s/g,'_'));
form.append('image', this.state.file);
form.append('content', this.state.code);
form.append('image_name', this.state.imageUrl.replace('images/',''));
form.append('access_token', cookies.get('loggedIn'));


Configure POST request settings object

let settings = {
   'async': true,
   'crossDomain': true,
   'url': urls.API_URL + '/cms/createSkill.json',
   'method': 'POST',
   'processData': false,
   'contentType': false,
   'mimeType': 'multipart/form-data',
   'data': form
};


Make an AJAX request using the settings above to upload the skill to the server and send a notification when the request is successful.

$.ajax(settings)
   .done(function (response) {
   self.setState({
          loading:false
   });
notification.open({
    message: 'Accepted',
    description: 'Your Skill has been uploaded to the server',
    icon: <Icon type='check-circle' style={{ color: '#00C853' }}       />,
});


Parse the received response as JSON and if the accept key in the response is true, we push the new skill data to the history API and set relevant states.

let data = JSON.parse(response);
if(data.accepted===true){
  self.props.history.push({
	pathname: '/' + self.state.groupValue  +
  	'/' + self.state.expertValue.trim().replace(/\s/g,'_') +
  	'/' + self.state.languageValue,
	state: {
  	from_upload: true,
  	expertValue:  self.state.expertValue,
  	groupValue: self.state.groupValue ,
  	languageValue: self.state.languageValue,
}});


If the accepted key of the server response is not true, display a notification.

else{
	self.setState({
  		loading:false
	});
	notification.open({
	  	message: 'Error Processing your Request',
	  	description: String(data.message),
	  	icon: <Icon type='close-circle' style={{ color: '#f44336' }} />,
	});
}})


Handle cases when AJAX request fails and send a corresponding notification

.fail(function (jqXHR, textStatus) {
 ...
  notification.open({
    message: 'Error Processing your Request',
    description: String(textStatus),
    icon: <Icon type='close-circle' style={{ color: '#f44336' }} />,
  });
});


I hope after reading this post, the objectives of susi_skill_data are more clear and you understood how CMS handles the creation of skills.

Resources

1.AJAX Jquery – AJAX request using Jquery
2. React State – Read about React states and lifecycle hooks.

Continue ReadingUsing a Git repo as a Storage & Managing skills through susi_skill_cms

How to deploy SUSI AI bots on ngrok for debugging

For production purposes, bots can be deployed in cloud services such as HerokuGoogle App Engine or Amazon Web Services – or in their own data center infrastructure.

However, for development purposes you can use ngrok to provide access to your bot running in your local network. Ngrok is easy to setup and use. To learn more about it, you can refer to its documentation.

Ngrok is a handy tool and service that allows you tunnel requests from the wide open Internet to your local machine when it’s behind a NAT or firewall. It’s commonly used to develop web services and webhooks.

In this blog, you’ll learn how to deploy SUSI AI bots on ngrok. We’re going to demonstrate the process for SUSI AI Kik bot. However it is the same for rest of the bots as well.

First of all, you need to configure a bot on Kik. To configure a Kik bot, follow the first few steps of this blog post till you get an API key for the bot that you created using Botsworth. Now, follow these steps:

  1. In order to run SUSI AI kik bot on ngrok, you have to make some changes to the index.js file after forking susi_kikbot repository and cloning it to your local machine.
  2. Open index.js and change the information in ‘bot’ object. Write username of your kik bot in front of username and api key that you got for your bot in front of apiKey in quotations and leave the baseUrl blank for now. It will look like this: (Don’t copy the API key shown below. It’s invalid and only for demonstration purposes.)
var bot = new Bot({
    username: 'susi.ai',
    apiKey: 'b5a5238b-b764-45fe-a4c5-629fsd1851bd',
    baseUrl: ''
});
  1. Now save the file. No need to commit it.
  2. Go to https://ngrok.com/ and sign up.
  3. Next, you’ll be redirected to the setup and installation page. Follow the instructions there to setup ngrok on your local machine.
  4. Now open terminal and use ‘cd’ command to go to the susi_kikbot directory.
  5. While deploying on ngrok, we set the port for listening to http requests. Hence remove “process.env.PORT” from index.js or else this will cause an error in the next step. After removing, it should look like this: (Now save the index.js file)
http.createServer(bot.incoming()).listen(8080);

Also, comment out setInterval function in index.js.

  1. Now type the command ngrok http 8080 in terminal. In case ‘ngrok’ command doesn’t run, copy the ngrok file that you downloaded in step 5 and paste it in the susi_kikbot directory. Then enter ./ngrok http 8080 in terminal.
  2. When it launches, you’ll see a screen similar to the following:

  1. Copy the “forwarding” address (https://d36f0add.ngrok.io), and paste it in front of ‘baseUrl’ in the ‘bot’ object in index.js file. Add “/incoming” after it and save it. Now the ‘bot’ object should look similar to this:
var bot = new Bot({
    username: 'susi.ai',
    apiKey: 'b5a5238b-b764-45fe-a4c5-629fsd1851bd',
    baseUrl: 'https://d36f0add.ngrok.io/incoming'
});
  1. Launch another terminal window and cd into the susi_kikbot directory in your local machine. Then type node index.js command.

Congratulations! You’ve successfully deployed SUSI AI Kik bot on ngrok. Now try sending a message to your SUSI AI Kik bot.

References

Continue ReadingHow to deploy SUSI AI bots on ngrok for debugging