Implementing Event Invoice Forms

This blog post elaborates on the recent addition of user billing form in Eventyay which is an open source event management solution which allows users to buy & sell tickets, organize events & promote their brand, developed by FOSSASIA. As this project moves forward with the implementation of event invoices coming up,. In the past few weeks, I have collaborated with fellow developers in planning the integration of event invoice payments and this is a necessary step for the same due to its involvement in order invoice templates. This implementation focuses on event invoices billing ( the calculated amount an event organiser has to pay to the platform for their event’s revenue ). This form includes basic details like contact details, tax ID, billing location and additional information (if any). The following is a specimen of this form : Tax Form Implementation First step of this form creation is to employ the account/billing/payment-info route for serving the relevant model data to the frontend. // app/routes/account/billing/payment-info.jsimport Route from '@ember/routing/route';import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';export default class extends Route.extend(AuthenticatedRouteMixin) { titleToken() {   return this.l10n.t('Payment Info'); }} Since the field additions have been done in the user schema in the server side, the corresponding changes have to made in the ember user model as well. // app/models/user.js/**  * Billing Contact Information  */ billingContactName    : attr('string'), billingPhone          : attr('string'), billingCountry        : attr('string'), company               : attr('string'), billingAddress        : attr('string'), billingCity           : attr('string'), billingZipCode        : attr('string'), billingTaxInfo        : attr('string'), billingAdditionalInfo : attr('string'), billingState          : attr('string'), This form has a speciality. Instead of using the current user information directly, it uses an intermediate object and employs manipulation in current user record only when the submit button is clicked. This has been implemented in the following way :  // app/components/user-payment-info-form.jsexport default class extends Component.extend(FormMixin) { didInsertElement() {   super.didInsertElement(...arguments);   this.set('userBillingInfo', pick(this.authManager.currentUser, ['billingContactName', 'billingCity', 'billingPhone', 'company', 'billingTaxInfo', 'billingCountry', 'billingState', 'billingAddress', 'billingZipCode', 'billingAdditionalInfo'])); } @action submit() {   this.onValid(async() => {     this.set('isLoading', true);     try {       this.authManager.currentUser.setProperties(this.userBillingInfo);       await this.authManager.currentUser.save();       this.notify.success(this.l10n.t('Your billing details has been updated'));     } catch (error) {       this.authManager.currentUser.rollbackAttributes();       this.notify.error(this.l10n.t('An unexpected error occurred'));     }     this.set('isLoading', false);   }); }} The usual form validations are employed as expected in this one too and works well in storing the invoice based information. Resources Flask DocumentationEmber Documetation Related Work and Code Repository Front-End RepositoryAPI Server RepositoryCreating billing order form on frontendField implementations for billing form

Continue ReadingImplementing Event Invoice Forms

Play Your Favourite Music Files on your SUSI Smart Speaker

The SUSI smart speaker supports playing local music from any USB device connected to the smart speaker. To play your favourite music directly from files, just put them in a thumb drive and plug it into any one of the four USB ports on the smart speaker. SUSI can either play all songs from the USB device or songs from a specific artist, genre or album. Working The first thing that needs to be done is to automount the thumb drive in the smart speaker, for this the usbmount package is used. Further, after the mount is done local skills are created which are then used by the SUSI server to interpret voice commands related to offline music playback. Breakdown The code which enables the above functionality is :  Add dependency - https://github.com/fossasia/susi_installer/blob/1a2950b0eb1f88d4ecbd5b3c348d9b67ac2f4705/install.sh#L287 # usbmount is needed to automount usb drives on susibian(raspbian lite)if [ $targetSystem = raspi ] ; then DEBDEPS="$DEBDEPS hostapd dnsmasq usbmount"fi USB mount is added to the dependency list if the installer is running on a Raspberry Enable offline skills - https://github.com/fossasia/susi_installer/blob/1a2950b0eb1f88d4ecbd5b3c348d9b67ac2f4705/install.sh#L881 mkdir -p $WORKDIR/susi_server_data/generic_skills/media_discoverytouch $WORKDIR/susi_server_data/generic_skills/media_discovery/custom_skill.txtmkdir -p $WORKDIR/susi_server_data/settingsecho "local.mode = true" > $WORKDIR/susi_server_data/settings/customized_config.properties Enable the server to work with offline skills stored on the device. The new skills related to offline music playback are stored in /susi_server_data/generic_skills/media_discovery in a file named custom_skill.txt. Creating on the fly skills - https://github.com/fossasia/susi_installer/blob/1a2950b0eb1f88d4ecbd5b3c348d9b67ac2f4705/install.sh#L758 echo "Preparing USB automount"# systemd-udevd creates its own filesystem namespace, so mount is done, but it is not visible in the principal namespace.sudo mkdir /etc/systemd/system/systemd-udevd.service.d/echo -e "[Service]\nPrivateMounts=no" | sudo tee /etc/systemd/system/systemd-udevd.service.d/udev-service-override.conf# readonly mount for external USB drivessudo sed -i -e '/^MOUNTOPTIONS/ s/sync/ro/' /etc/usbmount/usbmount.confsudo cp $INSTALLERDIR/raspi/media_daemon/01_create_skill /etc/usbmount/mount.d/sudo cp $INSTALLERDIR/raspi/media_daemon/01_remove_auto_skill /etc/usbmount/umount.d/ First an override rule is added, which changes `PrivateMounts` rule’s value to `no` in /lib/systemd/system/systemd-udevd.service.  PrivateMounts if set to yes, the processes of this unit will be run in their own private file system (mount) namespace with all mount propagation from the processes towards the host's main file system namespace turned off. This means any file system mount points established or removed by the unit's processes will be private to them and not be visible to the host. To learn more about mount namespaces read - http://man7.org/linux/man-pages/man7/mount_namespaces.7.html  Next, whenever a device is mounted the 01_create_skill file is executed which contains the following instruction: python3 /home/pi/SUSI.AI/susi_installer/raspi/media_daemon/auto_skills.py "$UM_MOUNTPOINT" This calls the auto_skills.py file with the mount point of the storage device. The auto_skills.py file is used to generate audio skills for the USB drive. It scans for all the files in the USB thumb drive and creates relevant skills. Whenever the thumb drive is removed it calls out the 01_remove_auto_skill script which has the following instruction - echo -n > /home/pi/SUSI.AI/susi_server_data/generic_skills/media_discovery/custom_skill.txt This cleans out the custom_skills.txt file i.e. all the offline skills that were created for music playback are removed and the server no longer responds those skills. USAGE Play all music on the USB device Usage: SUSI, Play Audio This will play all audio from the USB device connected to the speaker. SUSI Smart speaker currently supports the following…

Continue ReadingPlay Your Favourite Music Files on your SUSI Smart Speaker

Control Your Susi Smart Speaker

The SUSI Smart Speaker is an AI assistant device which runs SUS.AI. To learn to set up your own smart speaker, head up to SUSI Installer. One of the new features of the smart speaker is the ability to control it via a webpage, the smarts speaker now allows the user to control various playback features such play/pause music directly via their mobile phones or laptops which are in the same network. The web page is served via the sound server running locally on the Raspberry Pi. The soundserver provides various methods of the vlcplayer as endpoints. The webpage uses these endpoints to control the smart speaker. Also, an external application such as an android/ios app can use these endpoints(or the webpage) to control the music playback on the device. Making the Front-end The front end is served via the flask server on ‘ / ’ endpoint and on the port 7070. Currently, the Front End contains the volume control slider and various buttons to control the audio playback of the device. The responses are sent to the server via javascript. Bootstrap is used for the CSS framework and Fontawesome is used for various icon support. Since the smart speaker should be able to run offline, CDN links for Bootstrap and Fontawesome are not used and the required files are served via the flask server on /static.  Adding required frameworks:     <link href="{{ url_for('static', filename='bootstrap.min.css') }}" rel="stylesheet">    <script type="text/javascript" src="{{       url_for('static',filename='fontawesome.min.js')    }}"></script> Web Page front-end <div class="form-signin">      <img class="mb-4" src="{{ url_for('static',       filename='SUSI.AI_Icon_2017a.svg') }}" alt="" width="256"       height="256">      {SUSI.AI Icon}      <h1 class="h3 mb-3 font-weight-normal">Smart Speaker Control</h1>        <div class="form-group">          <fieldset class="the-fieldset">              <legend class="text-left w-auto">Volume Control</legend>              <span class="font-weight-bold">0</span>              <i class="fas fa-volume-down"></i>              <input id="vol-control" class="slider" type="range" min="0"                  max="100" value="100" step="1" oninput="SetVolume(this.value)"               onchange="SetVolume(this.value)"></input>              {Volume Control Slider}              <i class="fas fa-volume-up"></i>              <span class="font-weight-bold">100</span>          </fieldset>          <fieldset class="the-fieldset">              <legend class="text-left w-auto">Playback Control</legend>          <button onclick="control('pause')"                   class="btn btn-outline-primary m-2">          Pause          <i class="fas fa-pause"></i>          </button>                  {pause control button}             {similar to the pause button other required buttons are added}          </fieldset>          <button onclick="window.location.href = '/set_password';"            class="btn btn-warning m-2">            Set or Change Password            <i class="fa fa-key"></i>          </button>        </div>    </div> Sending Response to Server Since this is a control webpage, on sending of a response, the webpage should not reload. To accomplish this all the buttons point to a javascript function which then sends out an HTTP POST request to the server. For this purpose XMLHttpRequest Object is used. The XMLHttpRequest…

Continue ReadingControl Your Susi Smart Speaker

Rating session in Open Event Frontend

This blog post will showcase an option which can be used by organizers to rate a session in Open Event Frontend. Let’s start by understanding why this feature is important for organizers. Consider a situation where an event can have hundreds of session submissions. It’ll be hard for organizers/co-organizers to keep track of the session they have already evaluated and which session is better than other. Here, session rating comes to the rescue. After evaluating a particular session, the organizer/co-organizer can simply rate the session out of 5 stars. We have a column Average Rating and No. of ratings which can be used to pick up the top rated sessions and so the organizer/co-organizers need not worry to keep track of evaluated sessions. We start by adding the three columns - Rating, Average Rating and No. of ratings to session controller along with actions createRating and updateRating to create and update session rating respectively. Code snippet to add the three mentioned columns to session controller - @computed() get columns() { return [ { ... }, { name : 'Rating', valuePath : 'id', extraValuePaths : ['rating', 'feedbacks'], cellComponent : 'ui-table/cell/events/view/sessions/cell-rating', options : { ratedSessions: this.ratedSessions }, actions: { updateRating : this.updateRating.bind(this), addRating : this.addRating.bind(this) } }, { name : 'Avg Rating', valuePath : 'averageRating', isSortable : true, headerComponent : 'tables/headers/sort' }, { name : 'No. of ratings', valuePath : 'feedbacks.length', isSortable : true, headerComponent : 'tables/headers/sort' }, { ... } ]; } The code snippet to add the two actions createRating and updateRating to the session controller - @action async updateRating(rating, feedback) { try { this.set('isLoading', true); if (rating) { feedback.set('rating', rating); await feedback.save(); } else { await feedback.destroyRecord(); } this.notify.success(this.l10n.t('Session feedback has been updated successfully.')); } catch (error) { this.notify.error(this.l10n.t(error.message)); } this.send('refreshRoute'); this.set('isLoading', false); } The action updateRating in the above code snippet takes rating and the feedback to be updated as parameters. If rating param is 0, the feedback is simply destroyed because it means that user removes his/her feedback from the session. @action async addRating(rating, session_id) { try { let session = this.store.peekRecord('session', session_id, { backgroundReload: false }); this.set('isLoading', true); let feedback = await this.store.createRecord('feedback', { rating, session, comment : '', user : this.authManager.currentUser }); await feedback.save(); this.notify.success(this.l10n.t('Session feedback has been created successfully.')); } catch (error) { this.notify.error(this.l10n.t(error.message)); } this.send('refreshRoute'); this.set('isLoading', false); } And the action addRating takes rating and the id of the session being rated as an input and then create a new feedback record with the info. Now the main challenge was to retrieve rating corresponding to a session and display it on the frontend. I tackled this by fetching all the feedback related to any session which is itself related to the event. Then I mapped the feedback to the id of the session they were related to. Code snippet fetching the feedback and mapping them to session id - let queryObject = { include : 'session', filter : [ { name : 'session', op : 'has', val : { name : 'event', op…

Continue ReadingRating session in Open Event Frontend

Implement Order Confirmation Feature in Eventyay

This post elaborates on the details of an endpoint which can be used to explicatively used to resend order confirmations. In the current implementation of the open event project, if the order has been confirmed, the ticket holders and buyers get an email each regarding their order confirmation. But in case that email has been accidentally deleted by any of the attendees, the event organizer / owner should have the power to resend the confirmations. The first step to the implementation was to create the appropriate endpoint for the server to be pinged. I utilized the existing blueprint being used for serving tickets on eventyay frontend project and created a new endpoint on the route : orders/resend-email [POST] # app/api/auth.py@ticket_blueprint.route('/orders/resend-email', methods=['POST'])@limiter.limit(   '5/minute', key_func=lambda: request.json['data']['user'], error_message='Limit for this action exceeded')@limiter.limit(   '60/minute', key_func=get_remote_address, error_message='Limit for this action exceeded')def resend_emails():   """   Sends confirmation email for pending and completed orders on organizer request   :param order_identifier:   :return: JSON response if the email was succesfully sent   """   order_identifier = request.json['data']['order']   order = safe_query(db, Order, 'identifier', order_identifier, 'identifier')   if (has_access('is_coorganizer', event_id=order.event_id)):       if order.status == 'completed' or order.status == 'placed':           # fetch tickets attachment           order_identifier = order.identifier           key = UPLOAD_PATHS['pdf']['tickets_all'].format(identifier=order_identifier)           ticket_path = 'generated/tickets/{}/{}/'.format(key, generate_hash(key)) + order_identifier + '.pdf'           key = UPLOAD_PATHS['pdf']['order'].format(identifier=order_identifier)           invoice_path = 'generated/invoices/{}/{}/'.format(key, generate_hash(key)) + order_identifier + '.pdf'           # send email.           send_email_to_attendees(order=order, purchaser_id=current_user.id, attachments=[ticket_path, invoice_path])           return jsonify(status=True, message="Verification emails for order : {} has been sent succesfully".                          format(order_identifier))       else:           return UnprocessableEntityError({'source': 'data/order'},                                           "Only placed and completed orders have confirmation").respond()   else:       return ForbiddenError({'source': ''}, "Co-Organizer Access Required").respond() I utilized exiting send_email_to_attendees for the email purpose but for security reasons, the endpoint was limited to make sure that an organizer can request only 5 order confrimations to be resent each minute (implemented using flask limiter). This was all for server implementation, to implement this on the front end, I just created a new action named as resendConfirmation implemented as given. // app/controllers/events/view/tickets/orders/list.jsasync resendConfirmation(order) {     let payload = {};     try {       payload = {         'data': {           'order' : order.identifier,           'user'  : this.authManager.currentUser.email         }       };       await this.loader.post('orders/resend-email', payload);       this.notify.success(this.l10n.t('Email confirmation has been sent to attendees successfully'));     } catch (error) {       if (error.status === 429) {        …

Continue ReadingImplement Order Confirmation Feature in Eventyay

Implementation of Organizer Invoicing in Open Event

This blog post emphasizes on the workflow of event invoicing for organizers in Open Event. The Open Event Project, popularly known as Eventyay is an event management solution which provides a robust platform to manage events, schedules multi-track sessions and supports many other features. Organizer invoicing in layman terms is the fee paid by an organizer for hosting an event on the platform. This is calculated every month and respective emails/notifications are sent to the user. An event invoice in the form a PDF is generated monthly based on the sales generated. The organizer can pay the invoice via a credit/debit card through PayPal. This feature was divided into a set of sub-features namely: Integration of ember tables for event invoicesImplementing the review route & corresponding logicCreating a compatible paypal component to work with invoice workflowCreation of a payment completion page on successful invoice payments Navigating to Account > Billing Info > Invoices, we are presented with a table of all the invoices which are due, paid & upcoming. You can review your due invoices and pay them. Adding to that, you can also view any past invoices which were paid or the upcoming ones which would have a draft status with the information about the current sales.                                                           Event Invoice Overview - Organizers For an invoice which is due, an organizer will be able to navigate to the review route by clicking on the Review Payment Action. In this route, details pertaining to Admin billing details, User billing details, total number of tickets sold and total invoice amount will be depicted. The Organizer can have a look at the total invoice amount here.                                               Review Route - Invoice Payment The Invoice details and Billing Info components were built using ui segments.  After reviewing the information, the organizer can click on pay via PayPal to initiate the transaction process via PayPal. The challenge here was the lack of proper API routing(sandbox/live) present in the system. To overcome this, the env variable in the PayPal component was given the value of the current environment enabled. def send_monthly_event_invoice(): from app import current_app as app with app.app_context(): events = Event.query.filter_by(deleted_at=None, state='published').all() for event in events: # calculate net & gross revenues user = event.owner admin_info = get_settings() currency = event.payment_currency ticket_fee_object = db.session.query(TicketFees).filter_by(currency=currency).one() ticket_fee_percentage = ticket_fee_object.service_fee ticket_fee_maximum = ticket_fee_object.maximum_fee orders = Order.query.filter_by(event=event).all() gross_revenue = event.calc_monthly_revenue() ticket_fees = event.tickets_sold * (ticket_fee_percentage / 100) if ticket_fees > ticket_fee_maximum: ticket_fees = ticket_fee_maximum net_revenue = gross_revenue - ticket_fees payment_details = { 'tickets_sold': event.tickets_sold, 'gross_revenue': gross_revenue, 'net_revenue': net_revenue, 'amount_payable': ticket_fees } # save invoice as pdf pdf = create_save_pdf(render_template('pdf/event_invoice.html', orders=orders, user=user, admin_info=admin_info, currency=currency, event=event, ticket_fee_object=ticket_fee_object, payment_details=payment_details, net_revenue=net_revenue), UPLOAD_PATHS['pdf']['event_invoice'], dir_path='/static/uploads/pdf/event_invoices/', identifier=event.identifier) # save event_invoice info to DB event_invoice = EventInvoice(amount=net_revenue, invoice_pdf_url=pdf, event_id=event.id) save_to_db(event_invoice)                                 Invoice generation and calculation logic as a cron job The event invoice PDFs along with the amount calculation was done on the server side by taking the product of the number of tickets multiplied by eventyay fees. The invoice generation, amount calculation and the task of marking invoices…

Continue ReadingImplementation of Organizer Invoicing in Open Event

Implementation of Event Invoice view using Ember Tables

This blog post emphasizes the power of ember tables and how it was leveraged to implement the event invoice view for eventyay. Event Invoices can be defined as the fee given by the organizer for hosting the event on the platform.  Eventyay is the outstanding Open Event management solution using standardized event formats developed at FOSSASIA. Porting from v1 to v2, event invoices are an integral part in the process.  Initially, throughout the whole project, plain HTML tables were utilized to render data pertaining to sales, tickets info etc. This in turn made the task of rendering data a cumbersome one. To implement clean & ubiquitous tables with in-built search & pagination functionalities, the ember addon ember-table has been used in Eventyay v2. To integrate ember tables, the HTML tables had to be replaced with the ember-table component which was created in the Open Event Project.  To utilize this component, column names for upcoming, paid and due invoices are required. These are stored in Plain Old Javascript Objects (POJOs) in the controller logic passed to the appropriate ember-table component. In the template logic, we check for the params i.e invoice status in this case and render the ember table through a component. Certain parameters such as the searchQuery, metaData, filterOptions etc. were to be passed in for total control of the table. @computed() get columns() { let columns = []; if (this.model.params.invoice_status === 'upcoming') { columns = [ { name : 'Invoice ID', valuePath : 'identifier' }, { name : 'Event Name', valuePath : 'event', cellComponent : 'ui-table/cell/events/cell-event-invoice' }, { name : 'Date Issued', valuePath : 'createdAt' }, { name : 'Outstanding Amount', valuePath : 'amount', extraValuePaths : ['event'], cellComponent : 'ui-table/cell/events/cell-amount' }, { name : 'View Invoice', valuePath : 'invoicePdfUrl' } ]; } else if (this.model.params.invoice_status === 'paid') { columns = [ { name : 'Invoice ID', valuePath : 'identifier' }, { name : 'Event Name', valuePath : 'event', cellComponent : 'ui-table/cell/events/cell-event-invoice' }, { name : 'Date Issued', valuePath : 'createdAt' }, { name : 'Amount', valuePath : 'amount', extraValuePaths : ['event'], cellComponent : 'ui-table/cell/events/cell-amount' }, { name : 'Date Paid', valuePath : 'completedAt' }, { name : 'View Invoice', valuePath : 'invoicePdfUrl' }, { name : 'Action', valuePath : 'identifier', extraValuePaths : ['status'], cellComponent : 'ui-table/cell/events/cell-action' } ]; } else if (this.model.params.invoice_status === 'due') { columns = [ { name : 'Invoice ID', valuePath : 'identifier' }, { name : 'Event Name', valuePath : 'event', cellComponent : 'ui-table/cell/events/cell-event-invoice' }, { name : 'Date Issued', valuePath : 'createdAt' }, { name : 'Amount Due', valuePath : 'amount', extraValuePaths : ['event'], cellComponent : 'ui-table/cell/events/cell-amount' }, { name : 'View Invoice', valuePath : 'invoicePdfUrl' }, { name : 'Action', valuePath : 'identifier', extraValuePaths : ['status'], cellComponent : 'ui-table/cell/events/cell-action' } ]; } else if (this.model.params.invoice_status === 'all') { columns = [ { name : 'Invoice ID', valuePath : 'identifier' }, { name : 'Event Name', valuePath : 'event', cellComponent : 'ui-table/cell/events/cell-event-invoice' }, { name : 'Amount', valuePath : 'amount', extraValuePaths : ['event'],…

Continue ReadingImplementation of Event Invoice view using Ember Tables

Enhancing Network Requests by Chaining or Zipping with RxJava

In Eventyay Attendee, making HTTP requests to fetch data from the API is one of the most basic techniques used. RxJava comes in as a great method to help us making asynchronous requests and optimize the code a lot. This blog post will deliver some advanced RxJava used in Eventyay Attendee. Why using RxJava?Advanced RxJava Technique – Chaining network calls with RxJavaAdvanced RxJava Technique – Merging network calls with RxJavaConclusionsResources WHY USING RXJAVA? There are many reasons why RxJava is a great API in Android Development. RxJava is an elegant solution to control data flow in programming, where developers can cache data, get data, update the UI after getting the data, handle asynchronous tasks. RxJava also works really well with MVVM architectural pattern. CHAINING NETWORK CALLS WITH RXJAVA Chaining RxJava is a technique using flatMap() operator of Rxjava. It will use the result from one network call in order to make the next network call.  In Eventyay Attendee, this technique is used when we want to update the user profile image. First, we need to upload the new profile image to the server in order to get the image URL, and then we use that URL to update the user profile compositeDisposable += authService.uploadImage(UploadImage(encodedImage)).flatMap { authService.updateUser(user.copy(avatarUrl = it.url)) }.withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true } .doFinally { mutableProgress.value = false } .subscribe({ mutableMessage.value = resource.getString(R.string.user_update_success_message) Timber.d("User updated") }) { mutableMessage.value = resource.getString(R.string.user_update_error_message) Timber.e(it, "Error updating user!") } In conclusion, zipping RxJava helps to make HTTP requests more continuous and reduce unnecessary codes.  ZIPPING NETWORK CALLS WITH RXJAVA Zipping RxJava is a technique using zip() operator of Rxjava. It will wait for items from two or more Observables to arrive and then merge them together for emitting. This technique would be useful when two observables emit the same type of data. In Eventyay Attendee, this technique is used when fetching similar events by merging events in the same location and merging events in the same event type. var similarEventsFlowable = eventService.getEventsByLocationPaged(location, requestedPage, 3) if (topicId != -1L) { similarEventsFlowable = similarEventsFlowable .zipWith(eventService.getSimilarEventsPaged(topicId, requestedPage, 3), BiFunction { firstList: List<Event>, secondList: List<Event> -> val similarList = mutableSetOf<Event>() similarList.addAll(firstList + secondList) similarList.toList() }) } compositeDisposable += similarEventsFlowable .take(1) .withDefaultSchedulers() .subscribe({ response -> ... }, { error -> ... }) In conclusion, zipping RxJava helps running all the tasks in parallel and return all of the results in a single callback. CONCLUSION Even though RxJava is pretty hard to understand and master, it is a really powerful tool in Android Development and MVVM models. These techniques above are really simple to implement and they could improve the app by r RESOURCES Eventyay Attendee Source Code:  https://github.com/fossasia/open-event-attendee-android/pull/2010 https://github.com/fossasia/open-event-attendee-android/pull/2117 RxJava Documentation: http://reactivex.io/documentation

Continue ReadingEnhancing Network Requests by Chaining or Zipping with RxJava

Building PSLab Desktop Apps using JavaScript, Python  and Electron

So before we get started let me quickly show you what we accomplished over a period of 2 and a half months building the Pocket Science Lab desktop app using the very technology I am going to talk about. The UI of PSLab Desktop The PSLab desktop app was originally written using pyQt. The UI of the python stack looked really outdated and maintaining it was becoming a problem due to poor developer support. So, after a lot of discussion and experimentation, we finally decided to re-implement the whole app in electronJS. There are three major benefits of writing an app with Electron: You can re-use your HTML, CSS knowledge to write the UI part in no time.You can re-use your JavaScript knowledge to write the business logic of the app.It works… Why? Before we even dive down to why use X and why use Y, let us try to answer a very basic question, The reason I had to invest a massive amount of time trying to experiment with different combinations and config parameters is because most of the blogs on the internet just wrote about “How to get started”, nobody talked about how to complete the build. And that is what I am going to cover. Anyone can figure out how to start out but  the real grind only begins when you get to the details of the app. But I hope to hit the escape velocity with my take on the subject. The Tech Stack — Why we chose Electron for PSLab Desktop app Now let’s talk about why we need React or Python in an Electron App. 1. React It is perfectly fine to use everything minimal, plain old HTML, CSS and JS will do just fine for your UI, but for how long? React opens up so many possibilities and makes the code logic flow naturally through a very well designed UI language. The state management system is also brilliant and the most crucial thing that will definitely make your life easier is the life cycle methods offered by React class components. Making use of react also lets you take advantage of well known React oriented libraries like Material UI React, and Styled-Components. These things are game changers and can transform your UI to an absolute gem that your users will enjoy. Oh, by the way, React UI is blazing fast… But that is not the best part, we will not configure React on our own, but rather let the crowd favorite CRA do it for us. CRA (Create-React-App) will not only abstract out all the webpack config files, but will also make sure your react dependencies stay updated. This will help in keeping your code up to date in the long run. 2. Python The task that is being performed by Python in our case was inevitable and could not be performed by JavaScript because PSLab only had Python libraries. We did not have the time to write everything again for JS so we figured a…

Continue ReadingBuilding PSLab Desktop Apps using JavaScript, Python  and Electron

Two flavors of PSLab Android App to support Google Maps (in Play Store flavor) and Open Street maps (in Fdroid flavor)

What are the flavors of an App? And why are they needed in PSLab Android App? While working on the PSLab Android Project, I ran into the need to create different variants of the app with different dependencies. In this blog, I have tried to explain the process of creating various flavors of the app in the easiest way possible.  Android Allows Developers to create different variants of the same app with the same code base but having some functionalities different across the variants. These functionalities may include some special/pro features, some different dependencies, etc. Such variants are called flavors of the App. Most common flavors are Paid and Free version of the app. In the PSLab Android Application, we needed to generate flavors, when we required to use Google Maps in the App. The app is also published on the Fdroid, which doesn’t allow dependencies of Google Maps. Hence 2 flavors of the app have been created,  Play Store Flavor (With Google Maps)F-Droid Flavor (With Open Street Maps) Declaring Flavors in the build.gradle File In order to create flavors of the app, first, we need to declare flavors in the Gradle file. In PSLab Android app we are creating 2 flavors, which are declared in the build.gradle file as under flavorDimensions 'default' productFlavors { fdroid { dimension = 'default' } playstore { dimension = 'default' } } flavorDimensions is used to package flavors if there are many flavors for an App. Since we have only two flavors fdroid and playstore, hence we are using single dimension default for both the flavors. Once this has been added to the build.gradle file we need to sync the gradle.  After the Sync is complete, if we open the Build Variants tab from the left corner of the Android Studio, it would look something like this:  (Figure 1: Build Variant Window of Android Studio) As can be seen in the screenshot above, once the gradle is successfully synced, Android Studio automatically creates debug and release build variants for each flavor and we can easily toggle between variants and build/ run / make apk for each variant. Congratulations! We have successfully finished the first step towards creating flavors of an app. Directory Structure after creating Flavors Apart from creating the build variants of different flavors, Android studio also creates src/<flavor name> folders for us. Now if we want to add new activities and classes to these flavors we can create java, res, values folders inside this folder. We can define separate Manifest file as well for each flavor individually. The directory structure of the PSLab Android project after creating required packages inside the automatically generated src/fdroid and src/playstore folders looks like below,   (Figure 2: Directory structure after creating flavors) Defining Flavor specific dependencies We can have some dependencies for one app flavor and some for others. For example, in PSLab Android app, we need Google Maps dependencies only in playstore flavor and Open Street Maps dependencies only in fdroid flavor. We can easily define…

Continue ReadingTwo flavors of PSLab Android App to support Google Maps (in Play Store flavor) and Open Street maps (in Fdroid flavor)