Implementing Favorite Event option in the Toolbar of Event Details in the Open Event Android App

The Open Event Android app allows users to favorite any Event. The users can easily see their favorited events in a section called Favorites. This blog will illustrate about how favorite event option has been implemented in the Toolbar of Event Details section of the Open Event Android app.

We will straightaway move onto the code of event_details.xml. We can clearly observe that we need to implement a menu item in the toolbar or action bar. So, to implement that, we first need to add a favorite icon in the support actionbar. To do that, we add a menu item in the event_details.xml file present under the menu folder.

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
  <group android:id="@+id/event_menu">
      ...
  </group>
  
  <item
      android:id="@+id/eventShare"
      android:icon="@drawable/ic_share_white_24dp"
      android:title="@string/event_share"
      app:showAsAction="always"/>

  <item
      android:id="@+id/favoriteEvent"
      android:icon="@drawable/ic_baseline_favorite_border_white_24px"
      android:title="@string/favorite_event"
      app:showAsAction="always"/>
</menu>

We can clearly observe that a menu item having an id of favoriteEvent has been added. We create a vector drawable with a heart shaped having only border. We also create a vector drawable of heart shaped filled with white colour. android:icon is set to the border icon as default.

We have made our desired changes in the xml files. Now we will head onto the code of EventDetailsViewModel. Basically, we want the user to be able to favorite the event. So we add the function setFavoriteEvent to the ViewModel.

fun setFavorite(eventId: Long, favourite: Boolean) {
compositeDisposable.add(eventService.setFavorite(eventId, favourite)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
               Timber.d("Success")
}, {
               Timber.e(it, "Error")
               error.value = "Error"
}))
}

This function utilises eventId, which is of long type and favourite, which is of Boolean type. This function makes an RxAndroid network call to set favorite as false or true to the event having the eventId. Heading onto the code in EventDetailsFragment. In the onOptionsItemSelected function, we add the favoriteEvent item case in the switch statement.

R.id.favoriteEvent -> {
eventViewModel.setFavorite(eventId, !(eventShare.favorite))
if (eventShare.favorite) {
setFavoriteIcon(R.drawable.ic_baseline_favorite_border_white_24px)
} else {
setFavoriteIcon(R.drawable.ic_baseline_favorite_white_24px)
}
return true

}

We clearly observe that we are setting the eventId and boolean fields in the .setFavorite function. There is a function called setFavoriteIcon, present in a conditional which sets the appropriate favorite icon.

Let us head onto the code of the function setFavoriteIcon

private fun setFavoriteIcon(id: Int){
menuActionBar?.findItem(R.id.favoriteEvent)?.icon = context?.let { ContextCompat.getDrawable(it, id) }
}

We observe that the code is quite straight forward, We just replace the menu item icon of id favoriteEvent with id. We add a conditional in the ViewModel observer of event. This conditional helps in setting the correct favorite image icon even after configuration changes.

eventViewModel.event.observe(this, Observer {
if (eventShare.favorite) {
setFavoriteIcon(R.drawable.ic_baseline_favorite_white_24px)
}
})

This is how we have successfully implemented a Favorite Event option in the Toolbar of EventDetailsFragment.

Additional Resources

Continue ReadingImplementing Favorite Event option in the Toolbar of Event Details in the Open Event Android App

Integrating Stripe OAuth in Open Event Frontend

Why is Stripe Oauth needed in frontend? Open event allows organizers to add tickets and accepts payments for tickets through various modes for example, Credit card, Debit card, Netbanking and offline payments. Stripe allows users to accept payments into their linked accounts on various online platforms after they provide client secret and publishable key. So to enable online payments in open event, organizers were required to authenticate their stripe account. This is done through Stripe OAuth.

Flow of OAuth

To allow organizers to link their stripe account admin has to enable stripe under payment gateway in admin settings. Admin provides his client ID and secret key. Admin also sets the redirect URL for his app on the stripe dashboard. After enabling these settings organizer will see an option to link their stripe account to open event when they are creating an event with paid tickets.

Here is what open event frontend does when we click connect to stripe button:

  1. Opens a popup to allow organizer to fill his stripe credentials and authorize open event app to access their secret and publishable key.
  2. Once the organizer fills his credentials and authorizes open event app, open event frontend fetches organizers auth code and saves it to server.
  3. Server on receiving auth code from frontend makes a request to stripe using the auth code to retrieve the publishable key and secret key.
  4. Once these are fetched server saves this information against the event so that all payments for that event can go to the linked stripe account.

Implementing the Frontend portion:

  • Choosing the library:

After looking at various libraries that support OAuth for Ember applications we decided to use Torii. Torii is the library that allows the addition of OAuth for various social apps such as Facebook, Google and Stripe too. It allows writing a custom provider for OAuth in case we do not want to use clients for which torii provides supports by default.

  • Implementing Stripe Provider:

Default provider for stripe given by torii fetched the client ID and redirect URL from environment.js file. But since in open event we have already saved client id of admin in our database so we will extend default stripe provider and modify its client Id so that it fetches client id from server. Code for extending default provider is given here:

import stripeConnect from 'torii/providers/stripe-connect';
import { alias } from '@ember/object/computed';
import { inject } from '@ember/service';
import { configurable } from 'torii/configuration';

function currentUrl() {
 let url = [window.location.protocol,
   '//',
   window.location.host].join('');
 if (url.substr(-1) !== '/') {
   url += '/';
 }
 return url;
}

export default stripeConnect.extend({

 settings: inject(),

 clientId: alias('settings.stripeClientId'),

 redirectUri: configurable('redirectUri', function() {
   return `${currentUrl()}torii/redirect.html`;
 })

});

 

We have fetched clientId from our settings service as alias(‘settings.stripeClientId’).

We have already defined settings in our services so we just need to inject the service here to be able to use it.

By default torii provides redirect url as {currentUrl}/torii/redirect.html. But in open event frontend we allow organizers to edit information on two routes and torii suggests in its docs to use {baseUrl}/torii/redirect.html as the redirect url to avoid potential vulnerability. So we also modified the default redirect url building method.

Saving information to server

Once we get the authorization token from stripe we send it to the server and save it to stripe-authorization model. The logic for the same is given below:

connectStripe() {
     this.get('data.event.stripeAuthorization.content') ? '' : this.set('data.event.stripeAuthorization', this.store.createRecord('stripe-authorization'));
     this.get('torii').open('stripe')
       .then(authorization => {
         this.set('data.event.stripeAuthorization.stripeAuthCode', authorization.authorizationCode);
       })
       .catch(error => {
         this.get('notify').error(this.get('l10n').t(`${error.message}. Please try again`));
       });
   },

 

This action gets called when we click on connect to stripe button. This action calls the stripe provider and opens a popup to enable the organizer to authenticate his stripe account.
Full code for this can be seen here.

In this way we connect the stripe service to open event to allow the organizer to receive payments for his events.

Resources
  • Stripe : Documentation on Stripe-Connect : Link
  • Torii: Library to implement Oauth. : Link
  • Implementation: Link to PR showing its implementation : Link
Continue ReadingIntegrating Stripe OAuth in Open Event Frontend

Improving the JSON file upload structure – Open Event Web app

Open Event Web app generator also allows user to upload JSON file for the event data other than the API endpoint. The generator used the socket connection ID to uniquely identify uploaded files on the server which worked good for a single socket connection but failed for multiple due to overlap of connection IDs which resulted in crashing of web app. The problem is fixed by providing a unique ID to every file uploaded on the server and creating a separate field for uploaded file ID in the request body.

How to add listener for file upload?

A listener for socket ‘file’ event is added in the file app.js, which is triggered when the event namely file is emitted by the socket. The file ID kept unique by introducing a counter for number of files uploaded on the server till now and incrementing the counter subsequently for every new file.

ss(socket).on('file', function(stream, file) {
 generator.startZipUpload(count, socket);
 console.log(file);
 filename = path.join(__dirname, '..', 'uploads/connection-' +    count.toString()) + '/upload.zip';
 count += 1;
 stream.pipe(fs.createWriteStream(filename));
});

 

The procedure named startZipUpload in generator.js is executed when the zip file upload starts which further calls the helper function to make uploads directory on the server.

exports.startZipUpload = function(id, socket) {
 console.log('========================ZIP UPLOAD START\n\n');
 distHelper.makeUploadsDir(id, socket);
 distHelper.cleanUploads(id);
};

Creating uploads directory

Uploads directory is created in the root directory using the file system interfaces, the ID passed as parameter ensures that the file names do not overlap.

makeUploadsDir: function(id, socket) {
 fs.mkdirpSync(uploadsPath + '/connection-' + id.toString());
 socket.emit('uploadsId', id);
}

Embedding uploads ID with the data

After the successful creation of uploads directory and the file, the socket emits the ID of uploaded file through the event uploadsID. The value of ID thus received is embedded in the object namely data along with the other entries in the form.

socket.on('uploadsId', function(data) {
 initialValue = data;
});

function getData(initValue) {
 const data = initValue;
 const formData = $('#form').serializeArray();

 formData.forEach(function(field) {
   if (field.name === 'email') {
     data.email = field.value;
   }
   ....
   ....
   ....
   ....
 
   if (field.name === 'apiVersion') {
     data.apiVersion = field.value;
   }
 });

Resources

 

Continue ReadingImproving the JSON file upload structure – Open Event Web app

Open Event Server – Export Event as an iCalendar File

FOSSASIA‘s Open Event Server is the REST API backend for the event management platform, Open Event. Here, the event organizers can create their events, add tickets for it and manage all aspects from the schedule to the speakers. Also, once he makes his event public, others can view it and buy tickets if interested.

To make event promotion easier, we also provide the event organizer to export his event as an iCalendar file. Going by the Wikipedia definition, iCalendar is a computer file format which allows Internet users to send meeting requests and tasks to other Internet users by sharing or sending files in this format through various methods. The files usually have an extension of .ics. With supporting software, such as an email reader or calendar application, recipients of an iCalendar data file can respond to the sender easily or counter propose another meeting date/time. The file format is specified in a proposed internet standard (RFC 5545) for calendar data exchange.

Server side – generating the iCal file

Here we will be using the icalendar package for Python as the file writer.

from icalendar import Calendar, vCalAddress, vText
  • We define a class ICalExporter which has a static method export(event_id).
  • Query the event using the event_id passed and start forming the calendar:
event = EventModel.query.get(event_id)

cal = Calendar()
cal.add('prodid', '-//fossasia//open-event//EN')
cal.add('version', '2.0')
cal.add('x-wr-calname', event.name)
cal.add('x-wr-caldesc', "Schedule for sessions at " + event.name)
  • We query for the accepted sessions of the event and store it in sessions.
sessions = Session.query \
   .filter_by(event_id=event_id) \
   .filter_by(state='accepted') \
   .filter(Session.deleted_at.is_(None)) \
   .order_by(asc(Session.starts_at)).all()
  • We then iterate through all the sessions in sessions.
  • If it is a valid session, we instantiate an icalendar event and store required details.
event_component = icalendar.Event()
event_component.add('summary', session.title)
event_component.add('uid', str(session.id) + "-" + event.identifier)
event_component.add('geo', (event.latitude, event.longitude))
event_component.add('location', session.microlocation.name or '' + " " + event.location_name)
event_component.add('dtstart', tz.localize(session.starts_at))
event_component.add('dtend', tz.localize(session.ends_at))
event_component.add('email', event.email)
event_component.add('description', session.short_abstract)
event_component.add('url', url_for('event_detail.display_event_detail_home',
                                  identifier=event.identifier, _external=True))
  • We then loop through all the speakers in that particular session and add it to the iCal Event object as well.
for speaker in session.speakers:
   # Ref: http://icalendar.readthedocs.io/en/latest/usage.html#file-structure
   # can use speaker.email below but privacy reasons
   attendee = vCalAddress('MAILTO:' + event.email if event.email else 'undefined@email.com')
   attendee.params['cn'] = vText(speaker.name)
   event_component.add('attendee', attendee)
  • This event_component is then added to the cal object that we created in the beginning.
cal.add_component(event_component)
  • And finally, the cal.to_ical() is returned. This is the iCalendar file contents. This can be directly written to a file.
return cal.to_ical()

Obtaining the iCal file:

Firstly, we have an API endpoint which starts the task on the server.

GET - /v1/events/{event_identifier}/export/ical

Here, event_identifier is the unique ID of the event. This endpoint starts a celery task on the server to export the event as an iCal file. It returns the task of the URL to get the status of the export task. A sample response is as follows:

{
  "task_url": "/v1/tasks/b7ca7088-876e-4c29-a0ee-b8029a64849a"
}

The user can go to the above returned URL and check the status of his Celery task. If the task completed successfully he will get the download URL. The endpoint to check the status of the task is:

and the corresponding response from the server –

{
  "result": {
    "download_url": "/v1/events/1/exports/http://localhost/static/media/exports/1/zip/OGpMM0w2RH/event1.zip"
  },
  "state": "SUCCESS"
}

The file can be downloaded from the above mentioned URL.

Hence, now the event can be added to any scheduling app which recognizes the ics format.

References

Continue ReadingOpen Event Server – Export Event as an iCalendar File

Meilix Blank Screen

Meilix has recently faced a blank screen issue where while booting the system, it leads to a screen as follows:

We thought it to be virtual machine issue, and build the Meilix ISO in local system from scratch. But it still coming up with the same error.

Then we started to search for the commit which seems to be breaking the ISO. There is no such commit which actually breaks the ISO. So we can’t remove/revert to any particular commit.

Then we started searching in the history to search for the latest working ISO and found that this commit actually gives a working ISO 6f287ea and below this commit, none of the others are giving an ISO which works.

So we started to look into the particular commit to find the code which is breaking the system, but actually none of them actually seems to do so. It raises more unobvious issue.

If I searched for the error, it doesn’t seems to be error from the ISO side.Even I tried building the ISO locally and test it, it is giving the same result.

It looks like it’s more than a hardware error than the error on the iso side. I tried different qemu, virtualbox, VMware on different machines.

Another Idea tried for working of the ISO

  1. initramfs is a small linux shell. please use ls and cd to find the file containing the file system filesystem.squashfs. in this black shell (initramfs)
  2. try to mount the ISO file manually

I local mount using:

sudo mount -o loop /home/meilix.iso /home/user
sudo umount /home/user

 

I mount the March 18 (good) and the closest April (bad)l ISO image and run a diff between both directories. the result is possibly large.

Finally tabesin made a commit dce3b08 which resolves the issue. It just the removal of language pack.

We can find the ISO link: https://github.com/fossasia/meilix/releases/tag/untagged-e337428be18400673be6

References:

USB Boot Issue

Initramfs error

Continue ReadingMeilix Blank Screen

Building Drop-Down Menu

Meilix Generator has a dropdown menu which consists of links to code, issues and different FOSSASIA projects. The drop down menu appears after clicking on 3×3 dots present on the top right corner. The menu gets closed while clicking on the same dots. We want the menu to close close when we click somewhere else on the screen.

The problem statement is to close the menu bar while clicking anywhere on the white screen of the web app.

Solution:

For that I have to add a listener to the rest of the body to add class “hidden”.

We first remove the old onclick listener from the body tag which open the pop-up to show up the option. We replace it with its class.

<div onclick="document.getElementsByClassName('custom-menu-cont')[0].classList.toggle('hidden')" class="custom-menubutton">
      <i class="glyphicon glyphicon-th" style="font-size:20px;"></i>
    </div>

 

<div class="custom-menubutton">
      <i class="glyphicon glyphicon-th" style="font-size:20px;"></i>
    </div>

 

Then the dropdown menu doesn’t open while clicking on the dots also. So we added a script outside the body tag to

  • Open the dropdown menu pop-up on clicking on the 3×3 dots.
  • Close the pop-up while clicking on that dots or anywhere on the white screen of the webapp.

<script type="text/javascript">
	function hideDiv(){
        document.getElementsByClassName('custom-menu-cont')[0].classList.toggle('hidden')
}
document.addEventListener("click", hideDiv);	
</script>

 

We are working in html so we have to add the type of the script. We add the function hideDiv to open and close the pop-up while clicking on dots.

We then add the eventListener to hide the pop-up while clicking anywhere on the screen.

Reference:

Stackoverflow Pop-up closing

Adding JS in HTML W3School

 

 

Continue ReadingBuilding Drop-Down Menu

Build Button Resolution in Meilix

Meilix Generator is a webapp which has a build button and after clicking the button it triggers the travis of Meilix repository. You can even generate ISO from your phone. But while opening the web app on a phone, we came to see that the build button is not properly visible. Footer of the page hide the build button. This blog shows the way to identify the build button issue and to make it responsive for all screen sizes.

Error Rectification

There are two elements that need correction:

  • Build button
  • Footer

Build Button

<input class="btn btn-info mx-auto btn-block" id="file-upload" value="Build" required="" type="submit">

 

Here build button act as a input submit button.

class="form-group"> class="btn btn-info mx-auto btn-block" id="file-upload" value="Build" required="" type="submit" style="height: 50px; width: 360px; border-radius: 500px;"/>

 

We first added the group to include the button in that form. Then we add the build button property to give the button certain look.

But now also the footer overlap the button. So now we need to work on footer part.

Footer

<footer class="footer">

 

We remove footer class and made a new div tag with the id = “deployment”. Then we set the css for the deployment id to customise its appearance.

     #deployment {
      position: absolute;
      text-align: center;
      width: 100%;
      padding: 10px;
      bottom: 0px;
      border-top: 1px solid #bfbfbf;
      background-color: #f9f9f9;
    }

 

This set the footer and build button appropriate to become responsive for all sizes.

Reference:

HTML form tag

Input type Submit tag

Continue ReadingBuild Button Resolution in Meilix

Update of Python Runtime in Meilix

Meilix Generator is a webapp uses flask with Python, Werkzeug, and Jinja 2. It triggers Travis to release in an ISO. It is deployed on Heroku. An older python version caused the webapp to load very slowly and it also become unsupported so there was a need to update the python version. In this blog post we walk through the update of Python in the project.

We can specify an explicit version of Python to be used to run your application. For example, if you require Python 2, add the following to your Pipfile:

[requires]
Python_version = "2.7"

 

Then run $ pipnv lock to generate Pipfile.lock and push to Heroku.

Another way:

If we are using pip, we can supply a runtime.txt file.

$ cat runtime.txt
python-3.6.1

 

Building of the webapp (Example)

The webapp build in Heroku and provide us a log. The log presents the packages installed and its version. Log also shows if any newer version is present for the package.

While building webapp, we get this as a log:

-----> Python app detected
! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.1, which is unsupported).
! We recommend upgrading by specifying the latest version (python-3.6.5).

 

This confirms that we need to update python version and so thus we edited the runtime.txt

Now building the same webapp, we get:

Python app detected
-----> Found python-3.6.1, removing
-----> Installing python-3.6.5
-----> Installing pip

 

It already using older python, so it need first to remove the older version and then it install the latest one.

The same implementation can be seen in the history.

Reference:

Flask – The Microframework

Heroku Python Runtime

Continue ReadingUpdate of Python Runtime in Meilix

Meilix Build Process

Meilix is an operating system developed in FOSSASIA. It has the capability to be easily customize which makes it different from other operating systems.

It is of 32 bit right now.

It is all started with build.sh script.

And the basic idea is:

  • Declaring the mirror, version, and language to use.
  • Referring to the source file
  • Download and updating required packages
  • Create chroot
  • Using chroot to execute script

At the very beginning, the webapp Meilix Generator trigger Travis with the input provided in the form with the event name as the tag name of the Travis build. This will help to distinguish between the releases.

Then the travis script .travis.yml executes build.sh script after changing its permission.

  - chmod +x ./build.sh
  - ./build.sh |& tee log.txt

 

Let’s get into the build.sh script and look into it.

arch=${1:-i386}

 

First we select the bit version of the OS which we need to build.

datafiles="image-${arch}.tar.lzma sources.list"

 

This provides necessary data files required to build the OS. The tar.lzma contains exactly the same file which are there in an ISO of a OS. So it gives us the capability to make changes into the system files.

Then it starts to download the required packages which will help during the process.

Then runs a debuild script which debuilds the metapackages.

chmod +x ./scripts/debuild.sh
./scripts/debuild.sh

 

The debuild script actually repacks the meilix-default-setting metapackages with the required settings. Meilix-default-settings metapackage is fully explained here. Debuilding process is explained here.

Then Meilix goes on installing required packages and deleting the unrequired files.

Meilix build script is well commented to help to understand the whole process line by line.

Then Travis release a Meilix ISO in github release and mail the user with the log in the attachment.

Special Features:

Meilix has some special features which makes it fully customizable:

  • Meilix-default-setting metapackages, it contains the home folder and the changes made inside it can be seen in the OS.
  • Metapackages in the Meilix are very helpful in installing any required package.
  • Meilix System Lock helps to clean the system and get back to a fixed time.

Reference:

Flask Web Forms- Generator

Shell Scripting- Meilix

chroot – Debian Wiki

 

Continue ReadingMeilix Build Process

Adding Features into Meilix Generator Webapp

Meilix Generator is a webapp generated in FOSSASIA which takes input from user and send it to Meilix to trigger a build. Then a release is made whose link is emailed to the user. The webapp contains a form where there are fields for installing a particular packages, etc. In the following we will discuss about the ways to achieve the configurations in Meilix ISO without even touching the Meilix repo.

For adding an option in the webapp:

Editing the frontend

We need to edit this line in the index.html with this line:

<input name = "GENERATOR_package_vlc" type = "checkbox" value = "vlc" id = "vlc">

 

Making the script

Then we have to add a script in the script folder. This script is called by Meilix build script. This script contains the variable “GENERATOR_package_vlc”.

We name this file vlc-package.sh

Content:

#!/bin/bash
if echo "$GENERATOR_package_vlc" | grep -q vlc; then 
sudo apt-get install -q -y vlc; fi

 

Line 2 checks that the vlc is checked in the checkbox or not, if it is checked then the other next line gets executed otherwise not.

Calling the script from Meilix (needs to be done only once)

We will add a line in the Meililx build script to call those script present in the Meilix Generator repo.

SCRIPT_URL=https://www.github.com/fossasia/meilix-generator/archive/master.zip
wget -O $scripts.zip $SCRIPT_URL
unzip scripts.zip
SCRIPTS_FOLDER_IN_ZIP="meilix-generator-master/scripts"
ls $SCRIPTS_FOLDER_IN_ZIP; do
$SCRIPTS_FOLDER_IN_ZIP/script; done			#execute all scripts

 

Setting the URL via travis build config post to get all the values starting with GENERATOR_

GENERATOR_ = request.form['GENERATOR_']

 

So overall the abstract of the idea is:

  1. Getting the variables from html to travis as environment variable
  2. Cloning the meilix repo
  3. Executing all the scripts present.

References:

Request HTTP Python

Online Installation media

 

Continue ReadingAdding Features into Meilix Generator Webapp