Data Binding with Kotlin in Eventyay Attendee

Databinding is a common and powerful technique in Android Development. Eventyay Attendee has found many situations where data binding comes in as a great solution for our complex UI. Let’s take a look at this technique.

  • Problems without data binding in Android Development
  • Implementing Databinding with Kotlin inside Fragment
  • Implementing Databinding with Kotlin inside RecyclerView/Adapter
  • Results and GIF
  • Conclusions

PROBLEMS WITHOUT DATABINDING IN ANDROID DEVELOPMENT

Getting the data and fetching it to the UI is a basic work in any kind of application. With Android Development, the most common way to do is it to call function like .setText(), isVisible = True/False,.. in your fragment. This can create many long boilerplate codes inside Android classes. Databinding removes them and moves to the UI classes (XML).

IMPLEMENTING DATABINDING IN FRAGMENT VIEW

Step 1: Enabling data binding in the project build.gradle

android {
   dataBinding {
       enabled = true
   }

Step 2: Wrap the current layout with <layout></layout> tag. Inside that, put <data></data> to indicate any variables needed for data binding. For example, this code here display an event variable for our fragment about event details:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:bind="http://schemas.android.com/tools">

   <data>

       <variable
           name="event"
           type="org.fossasia.openevent.general.event.Event" />
   </data>

   <androidx.coordinatorlayout.widget.CoordinatorLayout
       android:id="@+id/eventCoordinatorLayout"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@android:color/white">

Step 3: Bind your data in the XML file and create a Binding Adapter class for better usage

With the setup above, you can start binding your data with “@{<data code here>}”

<TextView
   android:id="@+id/eventName"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_marginLeft="@dimen/layout_margin_large"
   android:layout_marginTop="@dimen/layout_margin_large"
   android:layout_marginRight="@dimen/layout_margin_large"
   android:text="@{event.name}"
   android:fontFamily="sans-serif-light"
   android:textColor="@color/dark_grey"
   android:textSize="@dimen/text_size_extra_large"
   app:layout_constraintEnd_toEndOf="@+id/eventImage"
   app:layout_constraintStart_toStartOf="@+id/eventImage"
   app:layout_constraintTop_toBottomOf="@+id/eventImage"
   tools:text="Open Source Meetup" />

Sometimes, to bind our data normally we need to use a complex function, then creating Binding Adapter class really helps. For example, Eventyay Attendee heavily uses Picasso function to fetch image to ImageView:

@BindingAdapter("eventImage")
fun setEventImage(imageView: ImageView, url: String?) {
   Picasso.get()
       .load(url)
       .placeholder(R.drawable.header)
       .into(imageView)
}
<ImageView
   android:id="@+id/eventImage"
   android:layout_width="@dimen/layout_margin_none"
   android:layout_height="@dimen/layout_margin_none"
   android:scaleType="centerCrop"
   android:transitionName="eventDetailImage"
   app:layout_constraintDimensionRatio="2"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintHorizontal_bias="0.5"
   app:layout_constraintStart_toStartOf="parent"
   app:eventImage="@{event.originalImageUrl}"
   app:layout_constraintTop_toBottomOf="@id/alreadyRegisteredLayout" />

Step 4: Finalize data binding setup in Android classes. We can create a binding variable. The binding root will serve as the root node of the layout. Whenever data is needed to be bind, set the data variable stated to that binding variable and call function executePendingBingdings()

private lateinit var rootView: View
private lateinit var binding: FragmentEventBinding
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_event, container, false)
rootView = binding.root
binding.event = event
binding.executePendingBindings()

SOME NOTES

  • In the example mentioned above, the name of the binding variable class is auto-generated based on the name of XML file + “Binding”. For example, the XML name was fragment_event so the DataBinding classes generated name is FragmentEventBinding.
  • The data binding class is only generated only after compiling the project.
  • Sometimes, compiling the project fails because of some problems due to data binding without any clear log messages, then that’s probably because of error when binding your data in XML class. For example, we encounter a problem when changing the value in Attendee data class from firstname to firstName but XML doesn’t follow the update. So make sure you bind your data correctly
<TextView
   android:id="@+id/name"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginBottom="@dimen/layout_margin_large"
   android:textColor="@color/black"
   android:textSize="@dimen/text_size_expanded_title_large"
   android:text="@{attendee.firstname + ` ` + attendee.lastname}"
   tools:text="@string/name_preview" />

CONCLUSION

Databinding is the way to go when working with a complex UI in Android Development. This helps reducing boilerplate code and to increase the readability of the code and the performance of the UI. One problem with data binding is that sometimes, it is pretty hard to debug with an unhelpful log message. Hopefully, you can empower your UI in your project now with data binding.  

RESOURCES

Eventyay Attendee Android Codebase: https://github.com/fossasia/open-event-android

Eventyay Attendee Android PR: #1961 – feat: Set up data binding for Recycler/Adapter

Documentation: https://developer.android.com/topic/libraries/data-binding

Google Codelab: https://codelabs.developers.google.com/codelabs/android-databinding/#0

Continue ReadingData Binding with Kotlin in Eventyay Attendee

Implementation of Donation Tickets in Open Event

Implementation of donation tickets in Open Event Project

This blog post explains the implementation details of donation tickets in the Open Event Project (Eventyay). Eventyay is the Open Event management solution which allows users to buy & sell tickets, organize events & promote their brand. This was developed at FOSSASIA. 

Prior to the integration of this feature, the organizer had the option to provide only paid and free tickets. These tickets had a fixed price and therefore, imbibing and integrating this into the system was relatively easier. The biggest challenge in the implementation of donation tickets was variable prices. The subtotal, total and validation checks had to updated dynamically and shouldn’t be breaking any of the previous features.  

The organizer requires an option to add donation tickets when they create/edit an event by specifying the appropriate minimum price, maximum price and quantity.

                         Organizer View – Donation Tickets

To integrate these features pertaining to donation tickets, fields for minimum and maximum prices had to be introduced into the tickets model. The maximum & minimum prices for free and paid tickets would be the same as the normal price but it’s variant for donations.

  isDonationPriceValid: computed('donationTickets.@each.orderQuantity', 'donationTickets.@each.price', function() {
    for (const donationTicket of this.donationTickets) {
      if (donationTicket.orderQuantity > 0) {
        if (donationTicket.price < donationTicket.minPrice || donationTicket.price > donationTicket.maxPrice) {
          return false;
        }
      }
    }
    return true;
  })

Check for valid donation price

To validate the minimum and maximum prices, ember validations have been implemented which checks whether the min price is lesser than or equal to the max  price to ensure a proper flow. Also, in addition to front-end validations, server side checks have also been implemented to ensure that incorrect data does now propagate through the server.

In addition to that, these checks also had to be integrated in the pre-existing shouldDisableOrderButton computed property. Therefore, if the order has invalid donation tickets, the order button would be disabled.

For the public event page, the donation tickets segment have a section which specifies the price range in which the price must lie in. If the user enters a price out of the valid range, a validation error occurs.

The way in which these validation rules have been implemented was the biggest challenge in this feature as multiple sets of donation tickets might be present. As each set of donation tickets have a different price range, these validation rules had to be generated dynamically using semantic ui validations

  donationTicketsValidation: computed('donationTickets.@each.id', 'donationTickets.@each.minPrice', 'donationTickets.@each.maxPrice', function() {
    const validationRules = {};
    for (let donationTicket of this.donationTickets) {
      validationRules[donationTicket.id] =  {
        identifier : donationTicket.id,
        optional   : true,
        rules      : [
          {
            type   : `integer[${donationTicket.minPrice}..${donationTicket.maxPrice}]`,
            prompt : this.l10n.t(`Please enter a donation amount between ${donationTicket.minPrice} and ${donationTicket.maxPrice}`)
          }
        ]
      };
    }
    return validationRules;
  })

Dynamic validation rule generation for donation tickets

Each donation ticket had to be looped through to add a validation rule corresponding to the donation ticket’s ID. These rules were then returned from a computed property.

Resources:

Related work and code repo:

Tags:

Eventyay, FOSSASIA, Flask, SQLAlchemy, Open Event, Python, JWT

Continue ReadingImplementation of Donation Tickets in Open Event

Implementing Slideshow Servlet in SUSI.AI Skills

Slideshow shown on SUSI.AI homepage helps SUSI.AI client showcase interesting and new features integrated into the platform. It helps to display the capabilities of SUSI.AI and other interesting areas. The slideshow can be configured from the Admin panel of SUSI.AI. 

For storing slideshow data, images, information, redirect to link on slideshow click, we need to implement a servlet to store data on server-side.

The endpoint is of GET type, and accepts:

  • redirect_link(compulsory): redirect link if a user clicks on the slider image
  • image_name(compulsory): The image relative folder path on the server
  • info: Any relevant information about the slider
  • deleteSlide: True, if the user wants to delete slider

Code Integration

For implementing slideshow service, we need to store the image on the backend using uploadImage service and using the uploaded image file path in the backend to store the full slider details using skillSlideshowService service. 

SkillSlideshowService:

For setting the slideshow, the minimum permission required is ADMIN

  @Override
   public UserRole getMinimalUserRole() {
       return UserRole.ADMIN;
   }

   @Override
   public JSONObject getDefaultPermissions(UserRole   baseUserRole) {
       return null;
   }

   @Override
   public String getAPIPath() {
       return "/cms/skillSlideshow.json";
   }

cms/SkillSlideshowService.java

Let’s have a look at how it is implemented, the redirect_link and image_name are necessary parameters and if not passed throws exception. If appropriate parameters are present, get the user query data using query.call. Access the data on the server side through DAO.skillSlideshow, if slideshow key is present in JsonTray skillSlideshow, get JSONObject with key “slideshow”.

If deleteKey is false, create a new JSONObject and put the query call data inside it and add to skillSlideshow object with redirectUrl as the key.

If deleteKey is true, remove the object associated with redirect_link and create a new object and add.

public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization authorization,
           final JsonObjectWithDefault permissions) throws APIException {
       if (call.get("redirect_link", null) == null || call.get("image_name", null) == null) {
           throw new APIException(400, "Bad Request. No enough parameter present");
       }

       String redirectLink = call.get("redirect_link", null);
       String imageName = call.get("image_name", null);
       String info = call.get("info", null);
       boolean deleteSlide = call.get("deleteSlide", false);
       JsonTray skillSlideshow = DAO.skillSlideshow;
       JSONObject result = new JSONObject();
       JSONObject skillSlideshowObj = new JSONObject();
       if (skillSlideshow.has("slideshow")) {
           skillSlideshowObj = skillSlideshow.getJSONObject("slideshow");
       }
       if (!deleteSlide) {
           try {
               JSONObject slideObj = new JSONObject();
               slideObj.put("image_name", imageName);
               slideObj.put("info", info);
               skillSlideshowObj.put(redirectLink, slideObj);
               skillSlideshow.put("slideshow", skillSlideshowObj, true);
               result.put("accepted", true);
               result.put("message", "Added new Slide " + call.get("redirect_link") + " successfully !");
               return new ServiceResponse(result);
           } catch (Exception e) {
               throw new APIException(500,
                       "Failed : Unable to add slide with path " + call.get("redirect_link") + " !");
           }
       } else {
           try {
               skillSlideshowObj.remove(redirectLink);
               skillSlideshow.put("slideshow", skillSlideshowObj, true);
               result.put("accepted", true);
               result.put("message", "Removed Slide with path " + call.get("redirect_link") + " successfully !");
               return new ServiceResponse(result);
           } catch (Exception e) {
               throw new APIException(501,
                       "Failed to remove Slide: " + call.get("redirect_link") + " doesn't exists!");
           }
       }
   }

cms/SkillSlideshowService.java

GetSkillSlideshow 

For fetching the slideshow data on frontend, GetSkillSlideshow servlet is implemented. The minimum userRole required in ANONYMOUS.

  @Override
   public String getAPIPath() {
       return "/cms/getSkillSlideshow.json";
   }

   @Override
   public UserRole getMinimalUserRole() {
       return UserRole.ANONYMOUS;
   }

   @Override
   public JSONObject getDefaultPermissions(UserRole baseUserRole) {
       return null;
   }

cms/GetSkillSlideshow.java

For fetching the slider data, access DAO.skillSlideshow, and get the JSONObject associated with key slideshow and put it in result response, put accepted key as true and return the response

public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights,
           final JsonObjectWithDefault permissions) throws APIException {

       JsonTray skillSlideshow = DAO.skillSlideshow;
       JSONObject skillSlideshowObj = skillSlideshow.getJSONObject("slideshow");
       JSONObject result = new JSONObject();

       try {
           result.put("accepted", true);
           result.put("slideshow", skillSlideshowObj);
           result.put("message", "Success : Fetched all Skills Slides!");
           return new ServiceResponse(result);
       } catch (Exception e) {
           throw new APIException(500, "Failed : Unable to fetch Skills Slides!");
       }
   }

cms/GetSkillSlideshow.java

3 types of endpoints are required for achieving the slider slideshow functionality. First, when a user creates or edits a slider, the user first needs to upload the image on the server using uploadImage.json service.

Image Suffix is the suffix of the file name stored in SUSI.AI server, susi_icon is the suffix in the image shown below.

Once the image is uploaded on the server, the API returns the relative path to the server location. The path on the server gets filled in ImagePath field on client-side(disabled to users).

With GetSkillSlideshow and SkillSlideshowService implemented, the admins can now manage and control the slideshow shown on the SUSI.AI home page, directly from the admin panel. The client can now easily discover new, exciting features as well.

Resources

Tags

SUSI.AI, FOSSASIA, GSoC`19, SUSI.AI Server

Continue ReadingImplementing Slideshow Servlet in SUSI.AI Skills

How to fix undetected Arduino boards in Android

In the development process of the Neurolab Android app, we needed an Arduino-Android connection. This blog explains how to  establish the connection and getting the Arduino board detected in my Android device

Context-connecting the board and getting it detected

Arduino boards are primarily programmed from the Desktop using the Arduino IDE, but they are not limited to the former. Android devices can be used to program the circuit boards using an application named Arduinodroid.

Arduino is basically a platform for building various types of electronic projects and the best part about it is that, it is open-sourced. Arduino, the company has got two products The physical programmable circuit board (often referred to as a microcontroller). 

Examples of Arduino circuit boards – UNO, UNO CH340G, Mega, etc. Find more here.

Connecting the board and getting it detected

Arduino boards are primarily programmed from the Desktop using the Arduino IDE, but they are not limited to the former. Android devices can be used to program the circuit boards using an application named Arduinodroid.

In this blog, we are going to use Arduinodroid app for establishing a connection between the Arduino board and the Android device, getting the board detected in the Android phone and uploading a sketch to it.

Materials/Gadgets required:-

  1. Arduino board (UNO preferably)
  2. Arduino-USB Cable
  3. OTG Cable
  4. Android device

Now, one of the most frequent issues, while establishing a connection and getting the Arduino board detected with the Android device, is the error message of: “No Arduino boards detected” in the Arduinodroid app. There can be a few core reasons for this –

  1. Your Android mobile device isn’t USB-OTG supported – Probably because it is an old model or it might be a company/brand-specific issue.
  2. Disabled OTG Mode – Be sure to enable USB-OTG mode (only if your device has one) from the Developer options in your Android device settings.

Even after trying and making sure of these above points, if you still continue to get an error while uploading a sketch from the Arduinodroid app like this:

                                                            Figure 1: The Error Message

Follow the steps below carefully and simultaneously one after the other:

  1. Look for any external module attached to your Arduino board using jumper wires. If so, remove those connections completely and press the reset button on the Arduino circuit board. The attached modules can be one of the following: Micro SD Card module, Bluetooth module, etc.
  2. Remove pin connections, if any from the TX and RX pin-slots in the Arduino board. These pre-attached pins can cause unnecessary signal transfers which can hinder and make the actual port of Arduino board busy.
  3. Before connecting the Arduino to the Android device, go to the drop down menu in the app at the top-right corner -> Settings -> Board Type -> Arduino -> UNO
  4. Now, you need to code a sketch and make it ready for compile and upload to the circuit board. We will use a basic example sketch for this case. Feel free to try out your own custom coded Arduino sketches. Go to the drop-down menu -> Sketch -> Examples -> Basics -> AnalogReadSignal
  5. Don’t compile the sketch yet because we haven’t connected any Arduino circuit board to our Android device. So first, connect the Arduino circuit board to the Android device through the OTG cable connected to the Arduino-USB cable.
  6. You should see some LEDs lit up on the circuit board (indicates power is flowing to the board). Go ahead to compile the sketch. Click the ‘lightning’ icon on the top in the toolbar of the app. You should see the code/sketch getting compiled. Once done you should see a toast message saying “Compilation finished”. This signifies that your code/sketch has been verified by the compiler.

                                              Figure 2: Successful Compilation of sketch

This process is inevitable and there is hardly any issue while compiling a sketch.

       7. Upload the sketch: Click on the upload icon from the toolbar in the app. Upload             should start once you get a pop-up dialog like this:

                                           Figure 3: Arduino board detected successfully

Once you click Okay, the upload shall start and if your code is correct and matches the particular Arduino circuit board, you shall get a successful upload, which was not the case earlier for the error : “no Arduino boards found” on clicking the upload button.

So, that’s it then. Hope this blog adds value to your development skills and you can continue working bug free with your Android-Arduino connections.

Resources:

  1. Author – Nick Gamon, Article – Have I bricked my Arduino uno problems with uploading to board, Date – Nov’16 2016, Website – https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board
  2. Author – Arduino Products, Article – Arduino boards, Website – https://www.arduino.cc/en/Main/Boards

3. Author – Anton Smirnov, App name – ArduinoDroid, Website – https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid2&hl=en_IN

Tags: FOSSASIA, Neurolab, GSOC19, Open-source, Arduino, Serial terminal

Continue ReadingHow to fix undetected Arduino boards in Android

Implementing Attendee Forms in Wizard of Open Event Frontend

This blog post illustrates on how the order form is included in the attendee information of the Open Event Frontend form  and enabling the organizer to choosing what information to collect from the attendee apart from the mandatory data i.e. First Name, Last Name and the Email Id during the creation of event itself.

The addition of this feature required alteration in the existing wizard flow to accommodate this extra step. This new wizard flow contains the step :

  • Basic Details : Where organizer fills the basic details regarding the event.
  • Attendee Form : In this step, the organizer can choose what information he/she has to collect from the ticket buyers.
  • Sponsors : This step enables the organizer to fill in the sponsor details
  • Session and Speakers : As the name suggests, this final step enables the organizer to fill in session details to be undertaken during the event.

This essentially condensed the flow to this :

The updated wizard checklist

To implement this, the navigation needed to be altered first in the way that Forward and Previous buttons comply to the status bar steps

// app/controller/create.jsmove() {
    this.saveEventDataAndRedirectTo(
      'events.view.edit.attendee',
      ['tickets', 'socialLinks', 'copyright', 'tax', 'stripeAuthorization']
    );
  }
//app/controller/events/view/edit/sponsorship
move(direction) {
    this.saveEventDataAndRedirectTo(
      direction === 'forwards' ? 'events.view.edit.sessions-speakers' : 'events.view.edit.attendee',
      ['sponsors']
    );
  }

Once the navigation was done, I decided to add the step in the progress bar by simply including the attendees form in the event mixin.

// app/mixins/event-wizard.js
    {
      title     : this.l10n.t('Attendee Form'),
      description : this.l10n.t('Know your audience'),
      icon     : 'list icon',
      route     : 'events.view.edit.attendee'
    }

Now a basic layout for the wizard is prepared, all what is left is setting up the route for this step and including it in the router file. I took my inspiration for setting up the route from events/view/tickets/order-from.js and implemented it like this:

// app/routes/events/view/edit/attendee.js
import Route from '@ember/routing/route';
import CustomFormMixin from 'open-event-frontend/mixins/event-wizard';
import { A } from '@ember/array';
export default Route.extend(CustomFormMixin, {

titleToken() {
  return this.l10n.t('Attendee Form');
},

async model() {
  let filterOptions = [{
    name : 'form',
    op : 'eq',
    val : 'attendee'
  }];

  let data = {
    event: this.modelFor('events.view')
  };
  data.customForms = await data.event.query('customForms', {
    filter       : filterOptions,
    sort         : 'id',
    'page[size]' : 50
  });

  return data;
},
afterModel(data) {
  /**
    * Create the additional custom forms if only the compulsory forms exist.
    */
  if (data.customForms.length === 3) {
    let customForms = A();
    for (const customForm of data.customForms ? data.customForms.toArray() : []) {
      customForms.pushObject(customForm);
    }

    const createdCustomForms = this.getCustomAttendeeForm(data.event);

    for (const customForm of createdCustomForms ? createdCustomForms : []) {
      customForms.pushObject(customForm);
    }

    data.customForms = customForms;
  }
}
});

With the route setup and included in the router, I just need to take care of the form data and pass it to the server. Thankfully, the project was already using EventWizardMixin so all I had to do was utilize these functions (save and move) which saves the event data in the status user decides to save it in i.e. either published or draft state

// app/controllers/events/view/edit/attendee.js
import Controller from '@ember/controller';
import EventWizardMixin from 'open-event-frontend/mixins/event-wizard';

export default Controller.extend(EventWizardMixin, {
async saveForms(data) {
  for (const customForm of data.customForms ? data.customForms.toArray() : []) {
    await customForm.save();
  }
  return data;
},
actions: {
  async save(data) {
    try {
      await this.saveForms(data);
      this.saveEventDataAndRedirectTo(
        'events.view.index',
        []
      );
    } catch (error) {
      this.notify.error(this.l10n.t(error.message));
    }
  },
  async move(direction, data) {
    try {
      await this.saveForms(data);
      this.saveEventDataAndRedirectTo(
        direction === 'forwards' ? 'events.view.edit.sponsors' : 'events.view.edit.basic-details',
        []
      );
    } catch (error) {
      this.notify.error(this.l10n.t(error.message));
    }
  }
}
});

Apart from that, the form design was already there, essentially, I reutilized the form design provided to an event organizer / co-organizer in the ticket section of the event dashboard to make it look like this form :

Basic attendee information collection

In the end, after utilizing the existing template and adding it in the route’s template, the implementation is ready for a test run!

// app/templates/events/view/edit/attendee.hbs
{{forms/wizard/attendee-step data=model move='move' save='save' isLoading=isLoading}}

This is a simple test run of how the attendees form step works as others work fine along with it!

Demonstration of new event submission workflow

Resources

Related Work and Code Repository

Continue ReadingImplementing Attendee Forms in Wizard of Open Event Frontend

Dependency Injection with Kotlin Koin in Eventyay Attendee

Eventyay Attendee Android app contains a lot of shared components between classes that should be reused. Dependency Injection with Koin really comes in as a great problem solver.

Dependency Injection is a common design pattern used in various projects, especially with Android Development. In short, dependency injection helps to create/provide instances to the dependent class, and share it among other classes.

  • Why using Koin?
  • Process of setting up Koin in the application
  • Results
  • Conclusion
  • Resources

Let’s get into the details

WHY USING KOIN?

Before Koin, dependency injection in Android Development was mainly used with other support libraries like Dagger or Guice. Koin is a lightweight alternative that was developed for Kotlin developers. Here are some of the major things that Koin can do for your project:

  • Modularizing your project by declaring modules
  • Injecting class instances into Android classes
  • Injecting class instance by the constructor
  • Supporting with Android Architecture Component and Kotlin
  • Testing easily

SETTING UP KOIN IN THE ANDROID APPLICATION

Adding the dependencies to build.gradle

// Koin
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"

Create a folder to manage all the dependent classes.

Inside this Modules class, we define modules and create “dependency” class instances/singletons that can be reused or injected. For Eventyay Attendee, we define 5 modules: commonModule, apiModule, viewModelModule, networkModule, databaseModule. This saves a lot of time as we can make changes like adding/removing/editing the dependency in one place.

Let’s take a look at what is inside some of the modules:

DatabaseModule

val databaseModule = module {

   single {
       Room.databaseBuilder(androidApplication(),
           OpenEventDatabase::class.java, "open_event_database")
           .fallbackToDestructiveMigration()
           .build()
   }

   factory {
       val database: OpenEventDatabase = get()
       database.eventDao()
   }

   factory {
       val database: OpenEventDatabase = get()
       database.sessionDao()
   }

CommonModule

val commonModule = module {
   single { Preference() }
   single { Network() }
   single { Resource() }
   factory { MutableConnectionLiveData() }
   factory<LocationService> { LocationServiceImpl(androidContext()) }
}

ApiModule

val apiModule = module {
   single {
       val retrofit: Retrofit = get()
       retrofit.create(EventApi::class.java)
   }
   single {
       val retrofit: Retrofit = get()
       retrofit.create(AuthApi::class.java)
   }

NetworkModule

single {
   val connectTimeout = 15 // 15s
   val readTimeout = 15 // 15s

   val builder = OkHttpClient().newBuilder()
       .connectTimeout(connectTimeout.toLong(), TimeUnit.SECONDS)
       .readTimeout(readTimeout.toLong(), TimeUnit.SECONDS)
       .addInterceptor(HostSelectionInterceptor(get()))
       .addInterceptor(RequestAuthenticator(get()))
       .addNetworkInterceptor(StethoInterceptor())

   if (BuildConfig.DEBUG) {
       val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
       builder.addInterceptor(httpLoggingInterceptor)
   }
   builder.build()
}

single {
   val baseUrl = BuildConfig.DEFAULT_BASE_URL
   val objectMapper: ObjectMapper = get()
   val onlineApiResourceConverter = ResourceConverter(
       objectMapper, Event::class.java, User::class.java,
       SignUp::class.java, Ticket::class.java, SocialLink::class.java, EventId::class.java,
       EventTopic::class.java, Attendee::class.java, TicketId::class.java, Order::class.java,
       AttendeeId::class.java, Charge::class.java, Paypal::class.java, ConfirmOrder::class.java,
       CustomForm::class.java, EventLocation::class.java, EventType::class.java,
       EventSubTopic::class.java, Feedback::class.java, Speaker::class.java, FavoriteEvent::class.java,
       Session::class.java, SessionType::class.java, MicroLocation::class.java, SpeakersCall::class.java,
       Sponsor::class.java, EventFAQ::class.java, Notification::class.java, Track::class.java,
       DiscountCode::class.java, Settings::class.java, Proposal::class.java)

   Retrofit.Builder()
       .client(get())
       .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
       .addConverterFactory(JSONAPIConverterFactory(onlineApiResourceConverter))
       .addConverterFactory(JacksonConverterFactory.create(objectMapper))
       .baseUrl(baseUrl)
       .build()
}

As described in the code, Koin support single for creating a singleton object, factory for creating a new instance every time an object is injected.

With all the modules created, it is really simple to get Koin running in the project with the function startKoin() and a few lines of code. We use it inside the application class:

startKoin {
   androidLogger()
   androidContext(this@OpenEventGeneral)
   modules(listOf(
       commonModule,
       apiModule,
       viewModelModule,
       networkModule,
       databaseModule
   ))
}

Injecting created instances defined in the modules can be used in two way, directly inside a constructor or injecting into Android classes.  

Here is an example of dependency injection to the constructor that we used for a ViewModel class and injecting that ViewModel class into the Fragment:

class EventsViewModel(
   private val eventService: EventService,
   private val preference: Preference,
   private val resource: Resource,
   private val mutableConnectionLiveData: MutableConnectionLiveData,
   private val config: PagedList.Config,
   private val authHolder: AuthHolder
) : ViewModel() {
class EventsFragment : Fragment(), BottomIconDoubleClick {
   private val eventsViewModel by viewModel<EventsViewModel>()
   private val startupViewModel by viewModel<StartupViewModel>()

For testing, it is also really easy with support library from Koin.

@Test
fun testDependencies() {
   koinApplication {
       androidContext(mock(Application::class.java))
       modules(listOf(commonModule, apiModule, databaseModule, networkModule, viewModelModule))
   }.checkModules()
}

CONCLUSION

Koin is really easy to use and integrate into Kotlin Android project. Apart from some of the basic functionalities mention above, Koin also supports other helpful features like Scoping or Logging with well-written documentation and examples. Even though it is only developed a short time ago, Koin has proved to be a great use in the Android community. So the more complicated your project is, the more likely it is that dependency injection with Koin will be a good idea.

RESOURCES 

Documentation: https://insert-koin.io/

Eventyay Attendee Android Codebase: https://github.com/fossasia/open-event-android

Continue ReadingDependency Injection with Kotlin Koin in Eventyay Attendee

Adding GetReportedSkill API on SUSI.AI Server

The GetReportedSkill API was implemented for Admins to view the reported feedback given by users, admin can then monitor skills, which are working fine and in which users are having problems. This can help in deleting buggy/erroneous skills directly from the reported skills tab in the admin panel.

The endpoint is of GET type, and accept 2 parameters: 

  • access_token(compulsory): It is the access token of the logged-in user. It is of a string data type.
  • search: It is a string param that helps us to fetch a list of feedback related to the search term

The minimal role is set to OPERATOR as Admin section access is required for reported skill list.

API Development

Here is a sample response from api:

{
  “session”: {“identity”: {
    “type”: “host”,
    “name”: “0:0:0:0:0:0:0:1_d9aaded8”,
    “anonymous”: true
  }},
  “accepted”: true,
  “list”: [
    {
      “feedback”: “test”,
      “skill_name”: “GSOC”,
      “email”: “shubhamsuperpro@gmail.com”,
      “timestamp”: “2019-06-15 03:25:29.425”
    },
    {
      “feedback”: “test101”,
      “skill_name”: “GSOC”,
      “email”: “shubham@gmail.com”,
      “timestamp”: “2019-06-15 12:18:33.641”
    }
  ],
  “message”: “Success: Fetched all Reported Skills”
}

The reported skills are stored in DAO under reportedSkills, for fetching the list we need to traverse it’s JSONObject.

JsonTray reportedSkills = DAO.reportedSkills;
JSONObject reportedSkillsListObj = reportedSkills.toJSON();

api/cms/GetReportSkillService.java

Code

For creating a list we need to access each property of JSONObject of reportedSkill, in the following order:

Model → Group → Language → Skill Name → Reported feedback list

for (String key:JSONObject.getNames(reportedSkillsListObj)) {
  modelName = reportedSkillsListObj.getJSONObject(key);
      if (reportedSkillsListObj.has(key)) {
        for (String group_name : JSONObject.getNames(modelName)) {
          groupName = modelName.getJSONObject(group_name);
          if (modelName.has(group_name)) {
            for (String language_name : JSONObject.getNames(groupName)) {
              languageName = groupName.getJSONObject(language_name);
              if (groupName.has(language_name)) {

api/cms/GetReportSkillService.java

If search parameter is passed, check if skillName matches with search parameter, if both strings are equal, create a new reportedObject and append it to reportList, which is a list of reported skills

if (call.get("search", null) != null) {
  String skill_name = call.get("search", null);
    if (languageName.has(skill_name)) {
      skillName = languageName.getJSONObject(skill_name);
      reports = skillName.getJSONArray("reports");
      for (int i = 0; i < reports.length(); i++) {
        JSONObject reportObject = new JSONObject();
        reportObject = reports.getJSONObject(i);
        reportObject.put("skill_name", skill_name);
        reportList.add(reportObject);

api/cms/GetReportSkillService.java

If search parameter is not passed, traversed all reported skills and append it to array(reportList).

getNames returns an array of keys as string stored in JSONObject, we traverse the array and put all the reported skill name, feedback, email and timestamp in reportObject and add it to reportList

} else {
   for (String skill_name : JSONObject.getNames(languageName)) {
      skillName = languageName.getJSONObject(skill_name);
      if (languageName.has(skill_name)) {
        reports = skillName.getJSONArray("reports");
           for (int i = 0; i < reports.length(); i++) {
             JSONObject reportObject = new JSONObject();
   reportObject = reports.getJSONObject(i);
   reportObject.put("skill_name", skill_name);    reportList.add(reportObject);
                 }
            }
       }
  }

api/cms/GetReportSkillService.java

Once we have the list of reported skills reportList return the service response

try {
   result.put("list", reportList);
   result.put("accepted", true);
   result.put("message", "Success: Fetched all Reported  Skills");
   return new ServiceResponse(result);
  } catch (Exception e) {
       throw new APIException(500, "Failed to fetch the requested list!");}

api/cms/GetReportSkillService.java

To conclude, the Admin’s now can take decisions based on reports submitted by the user to delete a skill or ignore the feedback.

Link to PR: https://github.com/fossasia/susi_server/pull/1274

Resources

Tags

SUSI.AI, FOSSASIA, GSoC`19, API Development, SUSI Server, SUSI Skills

Continue ReadingAdding GetReportedSkill API on SUSI.AI Server

Add PayPal Payment integration in Open Event Attendee Application

The open event attendee is an android app which allows users to discover events happening around the world using the Open Event Platform. It consumes the APIs of the open event server to get a list of available events and can get detailed information about them.

PayPal is a very common method to pay for anything throughout the world. It is a highly popular platform and it’s only right that there should be an option to pay through PayPal on Eventyay attendee for tickets. This blog will explain how and why I added PayPal payment feature in the application with a sandbox account.

  • Why PayPal?
  • Get API key for a sandbox account
  • Integration with Android Studio
  • Conclusion
  • Resources

Let’s analyze every step in detail.

Advantages of using PayPal Payment integration

  1. Provide UI to gather payment information from the user
  2. Get your credentials, which identify your PayPal account as the payment receiver. Specifically, obtain a client ID and secret.
  3. Returns a proof of payment to your app.
  4. Provides the user their goods or services.

Setup Sandbox account and get the API key

Go to https://developer.paypal.com/ and sign up for a developer account:

After Sign up, go to the dashboard and create an app: 

Now in app credentials go to sandbox accounts. Here you can find your API key.

Now, Create a new sandbox account with entering some amount of money for testing purposes:

PayPal SDK integration in the application

Add PayPal SDK in build.gradle dependencies:

//PayPal
compile 'com.paypal.sdk:paypal-android-sdk:2.16.0'

Store the API key in the android manifest file:

<meta-data
            android:name="com.paypal.android.API_KEY"
            android:value="${PAYPAL_CLIENT_ID}"/>

Get the API key in the fragment where PayPal payment is required:

private lateinit var PAYPAL_API_KEY: String
PAYPAL_API_KEY = activity?.packageManager?.getApplicati<meta-data
            android:name="com.paypal.android.API_KEY"
            android:value="${PAYPAL_CLIENT_ID}"/>onInfo(activity?.packageName, PackageManager.GET_META_DATA)
            ?.metaData?.getString(PAYPAL_KEY).toString()

Start PayPal services on create view:

val payPalConfiguration = PayPalConfiguration()
            .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX) 
            .clientId(PAYPAL_API_KEY)val intent = Intent(context, PaymentActivity::class.java)intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, payPalConfiguration)activity?.startService(intent)

Now start the Payment conditionally with same intent: 

val payment = PayPalPayment(BigDecimal(amount.toString()), "USD", "Pay for tickets", PayPalPayment.PAYMENT_INTENT_SALE)
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment)
startActivityForResult(intent, PAYPAL_REQUEST_CODE)

Handle the result after payment is done:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == PAYPAL_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val paymentConfirmation = data?.getParcelableExtra<PaymentConfirmation>(PaymentActivity.EXTRA_RESULT_CONFIRMATION)
                if (paymentConfirmation != null) {
                    val paymentInfo = paymentConfirmation.toJSONObject()
                    val tokenId = paymentInfo.getJSONObject("response").getString("id")
                    Timber.d(paymentInfo.toString(4))
                    // Send the token to server
                    val charge = Charge(attendeeViewModel.getId().toInt(), tokenId, null)
                    attendeeViewModel.completeOrder(charge)
                }
            } else if (resultCode == Activity.RESULT_CANCELED)
                Toast.makeText(context, "Payment canceled!", Toast.LENGTH_SHORT).show()
            else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
                Toast.makeText(context, "Invalid Payment Configuration", Toast.LENGTH_SHORT).show()
        }
    }

GIF

In a nutshell

With almost 250 million users worldwide, PayPal is an extremely popular platform for monetary transactions and it’s quite essential that every application an option to use it. Given the nature of Eventyay attendee and its pan-world appeal, I have added PayPal as a payment system for tickets to any event.

Resources

  1. PayPal Android SDK guide: PayPal Android SDK
  2. PayPal SDK repo: PayPal-Android-SDK

Tags

PayPal, Android, Payments, FOSSASIA, GSoC, AndroidPayments, Kotlin

Continue ReadingAdd PayPal Payment integration in Open Event Attendee Application

Allow organizers to lock/unlock a session in Open Event Frontend

This blog post will showcase an option which can be used by organizers to lock/unlock a session in Open Event Frontend. Let’s start by understanding what this feature means and why is it important for organizers. If a session is locked by an organizer, it cannot be edited by the session creator. 

Suppose an event organizer wants final session submission by a particular date so that he/she can shortlist the sessions based on final submission, but the user goes on editing the session event after final date of submission. This is a situation where this feature will help the organizer to prohibit the user from further modification of session.

If a session is unlocked, then unlock icon is shown:

Unlocked Session

However, if a session is locked, lock icon is shown:

Locked Session

Snippet to toggle locked/unlocked icon:

{{#if record.isLocked}}
  {{#ui-popup content=(t 'Unlock Session') class='ui basic Button' click=(action unlockSession record) position='left center'}}
    <i class="lock icon"></i>   
  {{/ui-popup}}
{{else}}
  {{#ui-popup content=(t 'Lock Session') class='ui basic Button' click=(action lockSession record) position='left center'}}
    <i class="unlock icon"></i>   
  {{/ui-popup}}
{{/if}}

On clicking these icon buttons, corresponding action is triggered which updates the status of is-locked attribute of the session. When an organizer clicks on lock icon button, unlockSession action is triggered which sets is-locked property of session to false. However if unlock icon button is clicked, lockSession action is triggered which sets the is-locked property of session to true.

Snippet to lock a session:

lockSession(session) {
     session.set('isLocked', true);
     this.set('isLoading', true);
     session.save()
       .then(() => {
         this.notify.success(this.l10n.t('Session has been locked successfully.'));
         this.send('refreshRoute');
       })
       .catch(() => {
         this.notify.error(this.l10n.t('An unexpected error has occurred.'));
       })
       .finally(() => {
         this.set('isLoading', false);
       });
   }

Snippet to unlock a session:

unlockSession(session) {
     session.set('isLocked', false);
     this.set('isLoading', true);
     session.save()
       .then(() => {
         this.notify.success(this.l10n.t('Session has been unlocked successfully.'));
         this.send('refreshRoute');
       })
       .catch(() => {
         this.notify.error(this.l10n.t('An unexpected error has occurred.'));
       })
       .finally(() => {
         this.set('isLoading', false);
       });
   }

These changes required few server checks so that only a person with admin or organizer access can update the value of is-locked attribute of session. Also, any try to edit a locked session via API call must be rejected.

Server checks related to locking/unlocking a session:

def before_update_object(self, session, data, view_kwargs):
       """
       before update method to verify if session is locked before updating
       session object
       :param event:
       :param data:
       :param view_kwargs:
       :return:
       """
       if data.get('is_locked') != session.is_locked:
           if not (has_access('is_admin') or has_access('is_organizer')):
               raise ForbiddenException({'source': '/data/attributes/is-locked'}, "You don't have enough permissions to change this property")

       if session.is_locked and data.get('is_locked') == session.is_locked:
           raise ForbiddenException({'source': '/data/attributes/is-locked'}, "Locked sessions cannot be edited")

Resources:

Related work and code repo:

Continue ReadingAllow organizers to lock/unlock a session in Open Event Frontend

Omise Integration in Open Event Frontend

This blog post will elaborate on how omise has been integrated into the Open Event Frontend project. Omise is Thailand’s leading online payment gateway offering a wide range of processing solutions for this project and integrating it as a payment option widens the possibilities for user base and ease of payment workflow.

Similar to Paypal, Omise offers two alternatives for using their gateway, Test mode and Live mode, where the former is generally favoured for usage in Development and Testing phase while the latter is used in actual production for capturing live payments. Both these modes require a Public key and Secret key each and are only update-able on the admin route.

This was implemented by introducing appropriate fields in the settings model.

// app/models/setting.js
omiseMode            : attr('string'),
omiseTestPublic      : attr('string'),
omiseTestSecret      : attr('string'),
omiseLivePublic      : attr('string'),
omiseLiveSecret      : attr('string')

Once your Omise credentials are configured, you can go ahead and include the options in your event creation form. You will see an option to include Omise in your payment options if you have configured your keys correctly and if the gateway supports the currency your event is dealing with, for example, even if your keys are correctly configured, you will not get the option to use omise gateway for money collection if the currency is INR.

For showing omise option in the template, a simple computed property did the trick canAcceptOmise  in the form’s component file and the template as follows:

// app/components/forms/wizard/basic-details-step.js
canAcceptOmise: computed('data.event.paymentCurrency', 'settings.isOmiseActivated', function() {
  return this.get('settings.isOmiseActivated') && find(paymentCurrencies, ['code', this.get('data.event.paymentCurrency')]).omise;
})
// app/templates/components/forms/wizard/basic-details-step.js
{{#
if canAcceptOmise}}
      <
label>{{t 'Payment with Omise'}}</label>
      <
div class="field payments">
        <
div class="ui checkbox">
          {{input type='checkbox' id='payment_by_omise' checked=data.event.canPayByOmise}}
          <
label for="payment_by_omise">
            {{t 'Yes, accept payment through Omise Gateway'}}
            <
div class="ui hidden divider"></div>
            <
span class="text muted">
              {{t 'Omise can accept Credit and Debit Cards , Net-Banking and AliPay. Find more details '}}
              <
a href="https://www.omise.co/payment-methods" target="_blank" rel="noopener noreferrer">{{t 'here'}}</a>.
            </
span>
          </
label>
        </
div>
      </
div>
      {{#
if data.event.canPayByOmise}}
        <
label>{{t 'Omise Gateway has been successfully activated'}}</label>
      {{/
if}}
    {{/
if}}

Once the event has the payment option enabled, an attendee has chosen the option to pay up using omise, they will encounter this screen on their pending order page 

On entering the credentials correctly, they will be forwarded to order completion page. On clicking the “Pay” button, the omise cdn used hits the server with a POST request to the order endpoint  and is implemented as follows :

//controllers/orders/pending.js
isOmise: computed('model.order.paymentMode', function() {
  return this.get('model.order.paymentMode') === 'omise';
}),

publicKeyOmise: computed('settings.omiseLivePublic', 'settings.omiseLivePublic', function() {
  return this.get('settings.omiseLivePublic') || this.get('settings.omiseTestPublic');
}),

omiseFormAction: computed('model.order.identifier', function() {
  let identifier = this.get('model.order.identifier');
  return `${ENV.APP.apiHost}/v1/orders/${identifier}/omise-checkout`;
})
// app/templates/orders/pending.hbs
    {{#
if isOmise}}
      <
div>
        <
form class="checkout-form" name="checkoutForm" method='POST' action={{omiseFormAction}}>
          <
script type="text/javascript" src="https://cdn.omise.co/omise.js"
                  data-key="{{publicKeyOmise}}"
                  data-amount="{{paymentAmount}}"
                  data-currency="{{model.order.event.paymentCurrency}}"
                  data-default-payment-method="credit_card">
          </
script>
        </
form>
      </
div>
    {{/
if}}

Thus primarily using Omise.js CDN and introducing the omise workflow, the project now has accessibility to Omise payment gateway service and the organiser can see his successful charge.

Resources

Related Work and Code Repository

Continue ReadingOmise Integration in Open Event Frontend