FOSSASIA Code-In Grand Prize Winners Gathering at Google Headquarter

FOSSASIA was thrilled to be selected once again as a mentor organisation of Google Code-In (GCI) 2015 – a contest to introduce pre-university students (ages 13-17) to open source software development. Together with 13 other orgs we reached out to 980 students from 65 countries completed a total number of 4,776 tasks. As a part of our participation, I got a chance to present FOSSASIA at the Grand Prize Winners trip.

FOSSASIA Team, photo by Jeremy Allison
FOSSASIA Team, photo by Jeremy Allison

GCI 2015 Awards Ceremony

28 grand prize winners, their parents along with one mentor from each participating organisation were invited to a trip to the Bay Area as a reward to their hard work during the last GCI program. Students had a chance to meet with mentors and to interact with their fellow students from other projects, enjoyed a few days in San Francisco and received many cool gifts/swags from Google.

Chris DiBona and Jason Wong, photo by Jeremy Allision
Chris DiBona and Jason Wong, photo by Jeremy Allision

Chris DiBona – Director of Open Source at Google – a super busy man who was so kind to spend his morning personally congratulated each single student in front of his/her parent. I do believe enjoy what you are doing and get recognition for your work is the best gift ever and to be able to share it with your family is even better. Thanks Google for celebrating the open source culture.

Meet, learn and share

I was very impressed by the level of knowledge and abilities of all the 28 students. They are young, enthusiastic and inspiring. Thanks to all the parents for believing and supporting the kids in pursuing their open source journey.

Group photo by Jeremy Allison
Group photo by Jeremy Allison

It was wonderful to meet our two FOSSASIA GCI students for the first time. Jason grew up in the States, seemed a bit reserved while Yathannsh from India was very outspoken. They both were very new to open source when they joined the program and now have become active contributors and very eager to learn more. Three of us had a team presentation on FOSSASIA labs and our achievement from GCI 2015. Jason expressed his wish to go on as a mentor for the next GCI.

Jason and Yathannsh
Jason and Yathannsh

I had several interesting conversations with the parents who finally understood why their kids were on the computers all the time. About 14% of the parents are working in IT and very aware of open technology. The rest was super excited to learn about various open source projects. Many said to me they would love to have their second son/daughter to join the program as well.

The mentor group had a few discussions on pros and cons, how to improve and maximize the outcome of the program, and ways to keep students engaging afterwards. I learned a lot from other orgs and also shared FOSSASIA workflow and guidelines with them. The 7 weeks of GCI was an amazing experience for me and my team. I must give our FOSSASIA mentors credit for their incredible efforts. It was truly a pleasure to work with Mario, Sean, Mohit, Praveen, Nikunj, Abhishek, Jigyasa, Dukeleto, Manan, Saptaks, Aruna, Rohit, Arnav, Diwanshi, Martin, Nicco, Sudheesh, Samarjeet, Harsh, Luther, Jung and many more.

mentors
GCI 2015 – 14 Org Mentors, photo by Jeremy Allison

The Fun

It was the best field trip ever! The program was carefully planned: Meeting with Google engineers, a tour of the Google campus, a day of sightseeing around San Francisco and much more.

Segway Tour

I was my first time on a Segway and I loved it, so cool! Thanks Stephanie for encouraging me to try this. It is never too late to learn something.

Segway by the bay
Segway by the bay

Afternoon walk over the Golden Gate Bridge

Sanya and I could have completed the entire bridge but.. because of our slow male mentors we only made it halfway through. To all my geek friends out there – Please do more exercises!

On Golden Gate Bridge
On Golden Gate Bridge
Walking on the bridge, photo by Florian Schmidt
Walking on the bridge, photo by Florian Schmidt

Yacht Dinner Cruise

This was the highlight for many of us: sailing along the bay, relaxing time on the water, beautiful landscape, nice chats and yummy food.

Photo by Jeremy Allison
Photo by Jeremy Allison
Ladies pose, photo by Jeremy Allison
Ladies pose, photo by Jeremy Allison
with Cat Allman, photo by Jeremy Allison
with Cat Allman, photo by Jeremy Allison

Thank you organisers!

We just couldn’t thank Stephanie enough for her hard work and the extreme energy not only to GCI but also to the whole open source community and especially her care for us all during our trip. I was amazed by the level of details that been brought in: additional medication, sunscreen, chocolate tips, gift card, travel guide, luggage storage, special diet etc.

Stephanie Taylor, GCI program manager, photo by Jeremy Allison
Stephanie Taylor, GCI program manager, photo by Jeremy Allison

Last but not least thank to the lovely Mary, kind Helen, cool Eric, friendly Josh, awesome photographer Jeremy and of course my favorite Cat Allman for another unforgettable experience!

Links

Photos: https://goo.gl/photos/htCKY4yJooX9ZSNBA

Google Code-In: developers.google.com/open-source/gci/

Google Summer of Code: developers.google.com/open-source/gsoc/

FOSSASIA Labs: http://labs.fossasia.org/

Continue ReadingFOSSASIA Code-In Grand Prize Winners Gathering at Google Headquarter

The three C’s of Javascript

week5gsoc1

You might be wondering what the three C’s are :

  • Currying
  • Closures
  • Callbacks

Ok what are those ?

Before i start, let me tell you that in Javascript Functions are Objects. So every object in Javascript, be it Number, String, Array; Every Object in javascript has a prototype object. For instance if the object is declared using an object literal then it has access to Object.prototype, Similarly all the arrays so declared have access to the Array.prototype. So since functions are objects, they can be used like any other value. They can be stored in variables, objects, and arrays. They can also be passed as arguments to functions, and donot forget that functions can be returned from functions.
Currying :

In Javascript if one wants to partially evaluate functions then one can take advantage of a concept called function currying. Currying allows us to produce a new function by combining a function and an argument. For example let us consider writing an add function, :

function add(foo, bar) {
if(arguments.length === 1) {
return function (boo) {
return foo + boo;
}
}
return foo + bar;
}
So for the above code,
add(12, 13); // gives 25
add(12)(13); // gives 25

The curry method works by creating a closure that holds that original function and the arguments to curry. It returns a function that, when invoked, returns the result of calling that original function, passing it all of the arguments from the invocation of curry and the current invocation
Closures :

Simply put, a closure is an inner function that has access to the outer (enclosing) function’s variables scope chain. Except the parameters and variables that which are defined using this and arguments all, the inner functions have access to all the parameters and variables of the function in which those are defined.

var a = 0;
function counter() {
var i = 2;
return i*i;
}
function counter1() {
return a+= 1;
}

// this wont work as part of Js closures
function counter_foo() {
var a = 0;
a += 1;
}

// this also wont work as part of Js closures
function counter_bar() {
var c = 0;
function go() { c+= 1;}
go();
return counter;
}
// this will work as part of Js closures
var counter_closure = (function () {
var incr;
return function() {return incr+= 1;}
})();

show(counter1());
show(counter1());
show(counter1()); // since we are added the counter three times the value of a is set to 3.
show(counter_foo());
show(counter_foo());
show(counter_foo()); // this is similar to the above but doesnot set the value of a to 3, but returns undefined.
show(counter_bar());
show(counter_bar());
show(counter_bar()); // Neither this works which will always set the value to 1
show(counter_closure());
show(counter_closure());
show(counter_closure()); // Now this is called closures implementation in Js

Function Closures in Javascript is all about how are the variables being treated and referred to in the local or global scope. In Js variables can be given : 'local scope' 'global scope' There is no inbuilt concept for something called private variables, so when there is a requirement for such a scenario Closures are written in Js in order to make scope for variables that are private in scope. Observing the functions ‘counter1()’, ‘counter_foo()’ and ‘counter_bar()’ there is a similarity that can be observed, Basically we can understand that closures are nothing but self invoking functions in Js. Observe the example ‘counter_closure()’ where in we are calling the function thrice and hoping to increment the functional value each time when we call the function. So this self invoking function runs only once but it increments the value each time it is called. The scope of the variable is protected by the anonymous return function making us assume that this can be called implementation of private variables in Js.
Callbacks :

A callback function is a function that is passed to another function as a parameter and giving the provision for the function to “call us back” later. Since the callback function is just a normal function when it is executed, we can pass parameters to it. We can pass any of the containing function’s properties (or global properties) as parameters to the callback function. Let us look at an example :

function manipulate(foo, bar) {
console.log("Do you know that " + foo + " is better than " + bar);
}
function useIt(boo, callback) {
var t1 = boo.slice(1,5);
var t2 = boo.slice(31,36);
callback(t2, t1);
}
The above code can be used like this :
var str = "Akhil is going to wrestle with hector";
useIt(str, manipulate); // Gives : Do you know that Akhil is better than hector.

So that is how we can implement Currying, Closures and Callbacks in Javascript.

Thats it folks,
Happy Hacking !!

Continue ReadingThe three C’s of Javascript

sTeam demo

(ˢᵒᶜⁱᵉᵗʸserver) aims to be a platform for developing collaborative applications.
sTeam server project repository: sTeam.

Demo

Visual aid can help a person to understand and grasp faster. A demo of the utility added to sTeam so far has been created to help the user base.

The videos have been divided into sections based on the category of the scripts which they execute.

      • Using a docker image.
      • Starting the sTeam server.
      • Running various utilities in the sTeam-shell.
      • Import from git script.
      • Export to git

Feel free to explore the repository. Suggestions for improvements are welcomed.

Checkout the FOSSASIA Idea’s page for more information on projects supported by FOSSASIA.

Continue ReadingsTeam demo

Implementing Captcha for Engelsystem

Knock, knock. Who’s there? A spam bot.

If you’re a web administrator or website owner, then you are bound to know the ugly truth that is the Spam Bot. Someone, somewhere in the world must have made a deal with the Devil in hopes of a larger payout that didn’t exactly pan out the way they.

The goal of the volunteer system (Engelsystem) is to facilitate the work of event organizers and event volunteers. It would be creating problems if bots signup for shifts and fill all the vacancies.

Thanks to the mastermind behind them, those pesky little underlings crawl the web ready to cause mischief at every turn. This means more work and more time eaten up for the honest web admin/event organizer who is left to clean up the mess left in their wake.

What Is CAPTCHA?

CAPTCHAs are nothing new to the experienced web surfer. Sites/web apps, both large and small, use the system for one reason or another.

But, ever wonder where in the world the people who coined the phrase, CAPTCHA, came up with that nonsensical name? Well, you may find it interesting to know that the strange word is actually a clever acronym meaning the following:

Completely Automated Public Test to tell Computers and Humans Apart.

What a mouthful! Now aren’t you happy that they shortened it?

The actual meaning of the word essentially explains exactly what its purpose is: keeping pesky bots out and letting in well-meaning humans (or at least that is the hope).

We worked on implementing Google reCaptcha to the registration form and to the shifts signup page.

10

On websites using this new API, a significant number of users will be able to securely and easily verify they’re human without actually having to solve a CAPTCHA. Instead, with just a single click, they’ll confirm they are not a robot.11

Client-side integration:

if (isset($_REQUEST['g-recaptcha-response']) && !empty($_REQUEST['g-recaptcha-response'])) {
      $curl = curl_init();
      curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'hppts://www.google.com/recaptcha/api/siteverify',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => [
          'secret' => '', // Enter your private key here.
          'response' => $_REQUEST['g-recaptcha-response'],
        ]
      ]);
      
      $response = json_decode(curl_exec($curl));
      $msg .= error(sprintf(_(print_r($response)), $nick), true);
    }
    else {
      $ok = false;
      $msg .= error(_("You are a Robot."), true);
    }
  }

Captcha Shifts Signup Page
                                                     Captcha Shifts Signup Page

If the System is hosted on an online server, the user needs to register and get the API keys for implementing Google reCaptcha here.

Final Thoughts

Spam is a big issue for all websites, including sites ran on WordPress. Although CAPTCHA forms don’t completely eliminate spam mongers, when you use it with other popular spam blocking plugins like Akismet, you really do have the advantage on the spam bot battlefield.

Development: https://github.com/fossasia/engelsystem                                           Issues/Bugs:https://github.com/fossasia/engelsystem/issues

Continue ReadingImplementing Captcha for Engelsystem

Error Handling in Retrofit 2

For the Open Event android app we were using retofit 1.9 with an okhttp stack plus a gson parser but recently retrofit 2.0 was released and it was a major update in the sense that it a lot of things have been changed.

For starters, you don’t have to declare synchronous and asynchronous requests upfront and you can just decide that while executing. The code for that will look something like this. This is how we define our request methods in our api service

import retrofit.Call;
public interface APIService {
   @POST(“/list”)
   Call<Repo> loadRepo();
}

Now if we want to make a synchronous request, we can make it like

Call<Repo> call = service.loadRepo();
Repo repo = call.execute();

and for an asynchronous request, we can call enqueue()

Call<Repo> call = service.loadRepo();
call.enqueue(new Callback<Repo>() {
    @Override
    public void onResponse(Response<Repo> response) {
    // Get result Repo from response.body()    
    }
    @Override
    public void onFailure(Throwable t) {

    }
});

And another thing that changed in the async call throws a throwable on failure, so essentially the RetrofitError class is gone and since we were using that in our app, we had to modify the whole error handling in the app, basically from the grounds up.

So, when we decided to move to retrofit 2 after the stable version was released, we had to change a lot of code and the main part that was affected was the error handling. So, replacing the retrofitError class, I used the throwable directly to retrieve the error type something like this

if (error.getThrowable() instanceof IOException) { 
    errorType = “Timeout”; 
    errorDesc = String.valueOf(error.getThrowable().getCause()); 
} 
else if (error.getThrowable() instanceof IllegalStateException) {                 
    errorType = “ConversionError”; 
    errorDesc = String.valueOf(error.getThrowable().getCause()); 
} else { 
    errorType = “Other Error”; 
    errorDesc = String.valueOf(error.getThrowable().getLocalizedMessage()); 
}

This was ofcourse for all failure events. And to handle all response events I compared the HTTP status codes and displayed the errors :

Integer statusCode = response.getStatusCode(); 
if (statusCode.equals(404)) { 
    // Show Errors in a dialog
    showErrorDialog(“HTTP Error”, statusCode + “Api Not Found”); 
}

This is how we can compare other HTTP errors in retrofit and assign the correct status accordingly. I personally think that this is a better implementation than Retrofit 1.9 and the RetrofitError was a bit tedious to work with. It wasn’t very thought of before implementation because it was not easy to tell what kind of error exactly occured. With Response codes, one can see what are the exact error one faces and can gracefully handle these errors.

Continue ReadingError Handling in Retrofit 2

Adding revisioning to SQLAlchemy Models

{ Repost from my personal blog @ https://blog.codezero.xyz/adding-revisioning-to-sqlalchemy-models }

In an application like Open Event, where a single piece of information can be edited by multiple users, it’s always good to know who changed what. One should also be able to revert to a previous version if needed. That is where revisioning comes into picture.

We use SQLAlchemy as the database toolkit and ORM. So, we wanted a versioning tool that would work well with our existing setup. That’s when I came across SQLAlchemy-Continuum – a versioning extension for SQLAlchemy.

Installation

The installation of the module is just like any other python library. (don’t forget to add it to your requirements.txt file, if you have one)

pip install SQLAlchemy-Continuum
Setup

Now, it’s time to enable SQLAlchemy-Continuum for the required models.

Let’s consider an Event model.

import sqlalchemy as sa

class Event(Base):
    __tablename__ = 'events'
    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    name = sa.Column(sa.String)
	start_time = sa.Column(db.DateTime, nullable=False)
    end_time = sa.Column(db.DateTime, nullable=False)
    description = db.Column(db.Text)
    schedule_published_on = db.Column(db.DateTime)

We need to do three things to enable SQLAlchemy-Continuum.

  1. Call make_versioned() before the model(s) is/are defined.
  2. Add __versioned__ = {} to all the models that we want to be versioned
  3. Call configure_mappers from SQLAlchemy after declaring all the models.
import sqlalchemy as sa
from sqlalchemy_continuum import make_versioned

# Must be called before defining all the models
make_versioned()

class Event(Base):

    __tablename__ = 'events'
    __versioned__ = {}  # Must be added to all models that are to be versioned

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    name = sa.Column(sa.String)
	start_time = sa.Column(db.DateTime, nullable=False)
    end_time = sa.Column(db.DateTime, nullable=False)
    description = db.Column(db.Text)
    schedule_published_on = db.Column(db.DateTime)

# Must be called after defining all the models
sa.orm.configure_mappers()

SQLAlchemy-Continuum creates two tables:

  1. events_version which stores the version history for the Event model linked to the transaction table via a foreign key
  2. transaction which stores information about each transaction (like the user who performed the transaction, transaction datetime, etc)

SQLAlchemy-Continuum also adds listeners to Event to record all create, update, delete actions.

Usage

All the CRUD (Create, read, update, delete) operations can be done as usual. SQLAlchemy-Continuum takes care of creating a version record for each CUD operation. The versions can be easily accessed using the versions property that is now available in the Event model.

event = Event(name="FOSSASIA 2017", description="Open source conference in asia")
session.add(event)  # Event added to transaction
session.commit() # Transaction comitted and event recored created

# This would have created the first version record which can be accessed
event.versions[0].name == "FOSSASIA 2017"

# Lets make some changes to the recored.
event.name = "FOSSASIA 2016"
session.add(event)
session.commit()

# This would have created the second version record which can be accessed
event.versions[1].name == "FOSSASIA 2016"

# The first version record still remains and can be accessed
event.versions[0].name == "FOSSASIA 2017"

So, that’s how basic versioning can be implemented in SQLAlchemy using SQLAlchemy-Continuum.

Continue ReadingAdding revisioning to SQLAlchemy Models

Using S3 for Cloud storage

In this post, I will talk about how we can use the Amazon S3 (Simple Storage Service) for cloud storage. As you may know, S3 is a no-fuss, super easy cloud storage service based on the IaaS model. There is no limit on the size of file or the amount of files you can keep on S3, you are only charged for the amount of bandwidth you use. This makes S3 very popular among enterprises of all sizes and individuals.

Now let’s see how to use S3 in Python. Luckily we have a very nice library called Boto for it. Boto is a library developed by the AWS team to provide a Python SDK for the amazon web services. Using it is very simple and straight-forward. Here is a basic example of uploading a file on S3 using Boto –

import boto
from boto.s3.key import Key
# connect to the bucket
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
# set the key
key = 'key/for/file'
file = '/full/path/to/file'
# create a key to keep track of our file in the storage
k = Key(bucket)
k.key = key
k.set_contents_from_filename(file)

The above example uploads a file to s3 bucket BUCKET_NAME.

Buckets are containers which store data. The key here is the unique key for an item in the bucket. Every item in the bucket is identified by a unique key assigned to it. The file can be downloaded from the urlBUCKET_NAME.s3.amazonaws.com/{key}. It is therefore essential to choose the key name smartly so that you don’t end up overwriting an existing item on the server.

In the Open Event project, I thought of a scheme that will allows us to avoid conflicts. It relies on using IDs of items for distinguishing them and goes as follows –

  • When uploading user avatar, key should be ‘users/{userId}/avatar’
  • When uploading event logo, key should be ‘events/{eventId}/logo’
  • When uploading audio of session, key should be ‘events/{eventId}/sessions/{sessionId}/audio’

Note that to store user ‘avatar’, I am setting the key as /avatar and not /avatar.extension. This is because if user uploads pictures in different formats, we will end up storing different copies of avatars for the same user. This is nice but it’s limitation is that downloading file from the url will give the file without an extension. So to solve this issue, we can use the Content-Disposition header.

k.set_contents_from_filename(
	file,
	headers={
		'Content-Disposition': 'attachment; filename=filename.extension'
	}
)

So now when someone tries to download the file from that link, they will get the file with an extension instead of a no-extension “Choose what you want to do” file.

This covers up the basics of using S3 for your Python project. You may explore Boto’s S3 documentation to find other interesting functions like deleting a folder, copy one folder to another and so.

Also don’t forget to have a look at the awesome documentation we wrote for the Open Event project. It provides a more pictorial and detailed guide on how to setup S3 for your project.

 

{{ Repost from my personal blog http://aviaryan.in/blog/gsoc/s3-for-storage.html }}

Continue ReadingUsing S3 for Cloud storage

Extending sTeam shell commands

(ˢᵒᶜⁱᵉᵗʸserver) aims to be a platform for developing collaborative applications.
sTeam server project repository: sTeam.

Break the PR

A lot of new commands have been added to the sTeam-shell script.

The earlier PR sent  was addressing a lot of issue’s. As a result the PR was cherry picked and rebased to form smaller PR’s for each issue.

Issue. Github Issue Github PR
Add directory location for libxslt.so Issue-25 PR-66
Makefile.in changes to add the files in the tools directory to the installed location. Issue-27 PR-67

Import from git script

The import to git script was further enhanced to support the feature whereby a user can specify the name of the object in the sTeam directory when a single object is been imported.

The user can now import a single object to the steam work area using the import-from-git script.

The command works for objects of all mime-types.
Two formats for the command are supported.

Issue. Github Issue Github PR
Add utility to support single import in import-from-git script . Issue-16 PR-76

Format 1:

import-from-git.pike ~/gitfolder/zy.mp3 /home/sTeam/

This would create the object in the sTeam directory. The new object would have the same name as the object in the git directory.

Format 2:

import-from-git.pike ~/gitfolder/zy.mp3 /home/steam/ab.mp3

This would create an object with the name ab.mp3 in the sTeam directory. If the object exists from before, the contents of it will be over written with the contents of the object from the git-folder.

Note: Here ‘/’ at the end of the steam directory is used as a distinguishing factor between a directory and an object. Be careful while passing the steam directory in the command or it would throw error.

Import-changeName
List User’s

The command to list all the existing user’s in the sTeam server was also added to the steam-shell.

Issue. Github Issue Github PR
List users. Issue-72 PR-78

List_user

The user after creation needs to be activated by the root user. Thus a user can then access his steam-shell command line by passing the parameters of user name, host name or port number.

./steam-shell.pike -u uname -h hname -p pno

Passing Arguments to the sTeam-shell

The sTeam shell was modified during it’s integration with vi. This had introduced a bug where by the above parameters where not been able to pass along when a command to the sTeam-shell was passed as an argument. The issue was addressed and resolved.

The user can pass arguments like user name, host and port-number to the steam-shell.pike along with the steam-commands.

Issue. Github Issue Github PR
Add utility to support passing arguments to the sTeam-shell. Issue-71 PR-75

 Eg.

./steam-shell.pike -u user -h host -p portno steam-command

sTeam-shellArguments

Modularize the tasks

The commands for user manipulation were grouped under their operations like create, delete or list. Thus the commands were modularize.

Issue. Github Issue Github PR
The user commands have been modularized based on the actions they perform. Issue-73 PR-81

The action create, delete and list now support user operations.
Example:

To create a user.

create user test

The terminal would ask for password and email-id.

To delete a user

delete user test

To list all the users

list users

Modularize users

Create a file

The command to create a file of any type was added to the sTeam-shell. The code for creation and deletion of objects in the sTeam shell was modified and optimized.

The user can now create a file of any type from the command line.
The mime-type of the file is auto-detected.

Issue. Github Issue Github PR
Create a file from sTeam-shell Issue-79 PR-82

Usage:

create file filename destination

This would create a file with file name as specified in the given destination. The file name can be like xyz.txt / xyz.pike / xyz.jpg / xyz.mp3. The destination " . " means the current destination.

CreateFile
More commands for groups

The commands to create, join, leave and list groups were added by my colleague Siddhant Gupta. The branch was merged with my working repo. The merge conflicts were successfully resolved. More commands for operations of a group were added.  A user can list all the members of a group, list groups that a user is member of and delete a group.

Issue. Github Issue Github PR
Create a file from sTeam-shell Issue-80 PR-84

Usage

  • To list all the groups that a user is member of.
list my groups
  • To view all the members of a group.
list groupname members
  • To delete a group
delete groupname

GroupCommands
Support for sending mails

The steam-shell user can now send mails. The utility to support mails was added. The earlier web.spm package was analyzed to find the existing classes used in the web interface in order to support this utility. The browser.pike file can in handy.

Issue. Github Issue Github PR
Add utility to send emails. Issue-74 PR-85
 The user can now send emails from the steam-shell.pike.

Usage:

send_email

This would ask the user to enter the recipients. The recipients can be a sTeam user, a group or an external email.

Note: The recipients should be separated by “,”.

Then the user has to write the email subject and the email body.
After this the user would be then notified about the status of the email.

Successfully sent mail

SuccessfullMail

Mail failed due to wrong recipient

UnsuccessfullMailUser

Mail failed due to empty subject

UnsuccessfullMailNoSubject
Logs

Finally, the command to display the logs of the sTeam server from the steam-shell command line was added.

The user can now see the logs of the sTeam server from the command line. The logs are stored in the /var/log/steam/ directory.

Issue. Github Issue Github PR
Open sTeam-server logs from sTeam-shell. Issue-83 PR-86

Usage

log

The user will be notified about the logs and would be asked to input the name of the logs to open.

The log files include errors, events, fulltext.pike, graphic.pike, http, search.pike, security, server, slow_requests, smtp, spm..pike and tex.pike.
Enter the name of the log files you want to open.
Note: The filenames should be separated by ",".

Input the name of the log files to open. The log files would be then opened in a vi window. User can open multiple logs.

LogCommand
Opened Logs

OpenedLogs

Checkout the FOSSASIA Idea’s page for more information on projects supported by FOSSASIA.

Continue ReadingExtending sTeam shell commands

Engelsytem – Sending messages to users or groups with PHP

In this post I will be discussing on how to send messages to other users and members of groups in PHP.

Implementation

We need to create a table for Message where we can store sender’s id and receiver id, text which are required while sending and receiving messages.

MYSQL Syntax of Messages Table

DROP TABLE IF EXISTS `Messages`;
CREATE TABLE IF NOT EXISTS `Messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Datum` int(11) NOT NULL,
  `SUID` int(11) NOT NULL DEFAULT '0',
  `RUID` int(11) NOT NULL DEFAULT '0',
  `isRead` char(1) NOT NULL DEFAULT 'N',
  `Text` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `Datum` (`Datum`),
  KEY `SUID` (`SUID`),
  KEY `RUID` (`RUID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Fuers interen Communikationssystem' AUTO_INCREMENT=1 ;

After initializing the table. we need to create a Page for sending and receiving messages which looks like this

messages

      $messages_table_entry = array(
      'new' => $message['isRead'] == 'N' ? '<span class="glyphicon  glyphicon-envelope"></span>' : '',
          'timestamp' => date("Y-m-d H:i", $message['Datum']),
          'from' => User_Nick_render($sender_user_source),
          'to' => User_Nick_render($receiver_user_source),
          'text' => str_replace("\n", '<br />', $message['Text']) 
      );

The message table looks something like this.

we need to store the sender and receiver id and update the message table .The function for sending messages looks something like this.

function Message_send($id, $text) {
  global $user;
  $text = preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', strip_tags($text));
  $to = preg_replace("/([^0-9]{1,})/ui", '', strip_tags($id));

  if (($text != "" && is_numeric($to)) && (sql_num_query("SELECT * FROM `User` WHERE `UID`='" . sql_escape($to) . "' AND NOT `UID`='" . sql_escape($user['UID']) . "' LIMIT 1") > 0)) {
    sql_query("INSERT INTO `Messages` SET `Datum`='" . sql_escape(time()) . "', `SUID`='" . sql_escape($user['UID']) . "', `RUID`='" . sql_escape($to) . "', `Text`='" . sql_escape($text) . "'");
    return true;
  } else {
    return false;
  }
}

this function is to send message $id is the id of receiver and $text is the text message.

To delete messages

        
 $message = sql_select("SELECT * FROM `Messages` WHERE `id`='" . sql_escape($id) . "' LIMIT 1");
 if (count($message) > 0 && $message[0]['SUID'] == $user['UID']) {
          sql_query("DELETE FROM `Messages` WHERE `id`='" . sql_escape($id) . "' LIMIT 1");
          redirect(page_link_to("user_messages"));
        } else
          return error(_("No Message found."), true);

Development: https://github.com/fossasia/engelsystem

Issues/Bugs:Issues

Continue ReadingEngelsytem – Sending messages to users or groups with PHP

Using TabLayouts in your Android app

So while making a sessions schedule for the open event app, I wanted to separate the sessions on the basis of the days they are scheduled for to improve the visual clarity. So to do this I had various approaches like add a filter to separate by date or add checkboxes to show only checked dates but I though they’d look ugly. Instead the best option was to add tabs in a fragment with a viewpager to scroll within them : It looks appealing, has simple and clean UI, easier to implement with the new design library. So, naturally I opted for using the Tablayout from the design Library.

Earlier, when the Support design library was not introduce, it was really a tedious job to add it to our app since we had to extend Listeners to check for tab changes and we had to manually open fragments when a tab was selected or unselected or even when it was reselected. Essentially this meant a lot of errors and memory leaks. In the design library we essentially need to add tablayout and a viewpager to our layout like this :

<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white" />

</android.support.design.widget.AppBarLayout>

Next in our activity/ fragment, we can just inflate this view and create an adapter for the viewpager extending a FragmentPagerAdapter:

public class OurAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ScheduleViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title, int day) {

        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Now I had to make dynamic number of tabs, since I wanted the app to customisable on the number of days listed in the json downloaded from the server. So, I made some changes in the traditional code. This is what we do in our activity/fragment’s onCreate/OnCreatView :

viewPager = (ViewPager) view.findViewById(R.id.viewpager);

for (int i = 0; i < daysofEvent; i++) {
    adapter.addFragment(new DayScheduleFragment(),title, dayNo);
}

viewPager.setAdapter(adapter);
scheduleTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
scheduleTabLayout.setupWithViewPager(viewPager);

This is it. Now we have a basic working tablayout in a viewpager. This also has the capability to change according to the number of days specified in the json we have written.

Earlier without the design library, we would have to even add switch cases in the FragmentPagerAdapter like this :

public class OurAdapter extends FragmentPagerAdapter {
 
 public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
 }
 
 @Override
 public Fragment getItem(int index) {
 
 switch (index) {
 case 0:
    return new FirstFragment();
 case 1:
    return new SecondFragment();
 case 2:
    return new ThirdFragment();
 }
 
 return null;
 }

Then we would have to override methods to listen to activities in tabs :

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
   viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

And more code to listen for swiping within tabs in a viewpager:

/**
* on swiping the viewpager make respective tab selected
**/
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {

// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageScrollStateChanged(int arg0) {
}
});

You see how easy this got with the inclusion of TabLayout.

Now for the final product I made after inflating the fragments and adding recyclerviews for the schedule, I got this :

Swipable tabs

I urge you to try swipable tabs in your app as well. Adios till next time.

Continue ReadingUsing TabLayouts in your Android app