CHAT APPLICATION USING RUBY ON RAILS Utkarsh Patel B.E. Veer Narmad South Gujarat University, 2005 PROJECT Submitted in partial satisfaction of the requirements for the degree of MASTER OF SCIENCE in COMPUTER SCIENCE at CALIFORNIA STATE UNIVERSITY, SACRAMENTO SPRING 2011 CHAT APPLICATION USING RUBY ON RAILS A Project by Utkarsh Patel Approved by: __________________________________, Committee Chair Jinsang Ouyang, Ph.D. __________________________________, Second Reader Ahmed Salem, Ph.D. ________________________________________ Date ii Student: Utkarsh Patel I certify that this student has met the requirements for format contained in the University format manual, and that this project is suitable for shelving in the Library and credit is to be awarded for the Project. ________________________, Graduate Coordinator Nikrouz Faroughi, Ph.D. Department of Computer Science iii ___________________ Date Abstract of CHAT APPLICATION USING RUBY ON RAILS by Utkarsh Patel. There has been a tremendous improvement and growth in popularity of chat applications as a means of internet communication since inception because of its real-time and non real-time nature. Conventional chat applications need to be installed and configured before it can be used and beside they are platform dependent. These requirements comprise problems for users especially those using the application in public computers such as school libraries, computer labs, etc where most of the time the application is not installed or the users are not allowed to install such applications. Web-based Chat application is the solution to these problems since it does not require any downloading, installation or configuration and besides it is platform independent. This project implements a real time web-based chat application using open ource web application framework Ruby on Rails. _______________________, Committee Chair Jinsang Ouyang, Ph.D. _______________________ Date iv ACKNOWLEDGMENTS I would like to take this opportunity to remember and acknowledge the guidance, cooperation, goodwill and both moral and technical support, extended by all staff and faculty members of California State University, Sacramento. I would like to thank my project advisor, Dr. Jinsang Ouyang for supporting the idea of the project and providing me such a great opportunity to work on this project. I am thankful to him because of his continuous guidance on the work performance, motivation and timely suggestions helped me a lot throughout the project. I am also grateful to my second reader, Dr. Ahmed Salem for being a second reader and providing me great help when needed during the project. He has done great help in giving important advices and proof reading the document. I am also grateful to Dr. Nikrouz Faroughi for helping me during the completion of my project. He has shown the path during preparation for the project and provided great ease during completion of the project. I sincerely record my debt of gratitude to Dr. Cui Zhang for helping in various prospects and providing enormous guidance during my Masters at California State University, Sacramento. Finally, I am thankful to my family and friends for encouragement during tough times and guidance during all the time for completion of my Masters project. v TABLE OF CONTENTS Page Acknowledgments............................................................................................................... v List of Figures ..................................................................................................................... x Chapter 1. INTRODUCTION .......................................................................................................... 1 2. APPLICATION OVERVIEW ........................................................................................ 4 2.1 Web-Based Chat Client..................................................................................... 5 2.2 Web Server........................................................................................................ 6 2.3 Chat Server........................................................................................................ 6 3. TOOLS AND TECHNOLOGY ...................................................................................... 8 3.1 Ruby on Rails .................................................................................................... 8 3.1.1 MVC Framework ............................................................................... 8 3.1.2 Rails Structure .................................................................................... 9 3.1.3 Configuring Database ...................................................................... 10 3.1.4 Models.............................................................................................. 11 3.1.5 Controllers........................................................................................ 12 3.1.6 Views ............................................................................................... 13 3.1.7 Layouts ............................................................................................. 14 3.1.8 Scaffoldings and Migration.............................................................. 15 3.1.9 Routes in Rails ................................................................................. 17 3.1.10 Error Handling ............................................................................... 18 3.1.11 Instant Rails ................................................................................... 18 3.2 Apache ............................................................................................................ 19 vi 3.3 Openfire .......................................................................................................... 19 3.4 MySQL ........................................................................................................... 20 3.5 Strophe ............................................................................................................ 20 3.6 AJAX ............................................................................................................. 21 3.7 CSS ................................................................................................................. 21 4. DESIGN ........................................................................................................................ 22 4.1 Basix XMPP Architecutre............................................................................... 22 4.2 Decentralized Architecture ............................................................................. 23 4.3 JabberID (JID) ................................................................................................ 24 4.4 Stanza .............................................................................................................. 24 4.4.1 Message Stanza ................................................................................ 24 4.4.2 Presence Stanza ................................................................................ 25 4.4.3 Info/Query Stanza..………………………………………………...26 4.5 Error Handling ................................................................................................ 27 4.6 Multiuser Chat……………………………………………………………….28 4.7 File Transfer………………………………………………………………….29 4.8 Client-Server Connection................................................................................ 30 4.9 Server-to-Server Connection .......................................................................... 30 4.10 BOSH ............................................................................................................ 31 5. IMPLEMENTATION ................................................................................................ 32 5.1 Connection and Registration ........................................................................... 32 5.2 Login ............................................................................................................... 35 5.3 Adding Friend ................................................................................................. 36 vii 5.4 Edit Friend Information .................................................................................. 37 5.5 Remove Friend From List ............................................................................... 37 5.6 View Presence of the Friends ........................................................................ 38 5.6.1 Change own Presence Status ........................................................... 38 5.7 Instant Messaging ........................................................................................... 40 5.8 Group Chat ...................................................................................................... 42 5.9 File Transfer .................................................................................................... 47 5.10 Recent Chat Conversation............................................................................. 49 6. EXECUTION AND SCREEN LAYOUT ................................................................. 52 6.1 Home Page ...................................................................................................... 52 6.2 Registration Screen ......................................................................................... 53 6.3 Login Screen ................................................................................................... 54 6.4 Chat Application Screen after Successful Login ............................................ 56 6.5 User Presence or Status Change Screen.......................................................... 57 6.6 Add Friends ..................................................................................................... 58 6.7 Chat Mesage.................................................................................................... 60 6.8 Edit or Delete Contacts ................................................................................... 61 6.9 Recent Chat Coversations ............................................................................... 63 6.10 Group Chat .................................................................................................... 65 6.11 Chat with other Apps .................................................................................... 73 6.12 File Transfer .................................................................................................. 74 7. CONCLUSION AND FUTURE WORK ..................................................................... 80 Appendix Installation Procedure...................................................................................... 81 viii Prerequisites .......................................................................................................... 81 Sysrem Requirements ............................................................................... 81 Software Requirements ............................................................................. 81 Installing MySQL ................................................................................................. 81 Installing Openfire ................................................................................................ 82 Installing Instant rails ............................................................................................ 82 References ......................................................................................................................... 84 ix LIST OF FIGURES Page 1. Figure 1 Basic Architecture of Web Application……………………………...2 2. Figure 2 Basic Architecture of Web Based Chat................................................5 3. Figure 3 Basic Chat Application Overview……………………………………6 4. Figure 4 XMPP architecture consisting of a server and two clients...………...22 5. Figure 5 Decentralized Client-Server Architecture……..…………………….23 6. Figure 6 Home Page……….……………………………………………….....52 7. Figure 7 Registration Page …………………………………………………...53 8. Figure 8 Registration Successful Message…………………………………....54 9. Figure 9 Registration Error Messages.……………….…………………….....54 10. Figure 10 Login Screen…………….…………………………………………55 11. Figure 11 Login Error Message 1....………………...………………………..55 12. Figure 12 Login Error Message 2.…….……………………………………...55 13. Figure 13 Chat Application Screen after Login………………………………56 14. Figure 14 Presence Status Change .…………………………………………..57 15. Figure 15 Add User………….……….……………………………………….58 16. Figure 16 Incorrect User Id…………….……………………………………..59 17. Figure 17 Adding user not registered to the application……………………...59 18. Figure 18 Add request notification message………………………………….60 19. Figure 19 Chat Window with chat messages.………………………………...61 20. Figure 20 Available options for added contact..……………………………...62 x 21. Figure 21 Edit Contact Information….……………………………………….62 22. Figure 22 Delete Contact……………………..…………………………........63 23. Figure 23 Recent Chat Conversation Window .………………………….......64 24. Figure 24 Recent Chat Conversation Screen Output…………………….......64 25. Figure 25 Provision for Multi user Chat room .………………………….......65 26. Figure 26 Newly Created Chat room………………………………………...66 27. Figure 27 Window of Newly Created Chat room………………………........67 28. Figure 28 Request Message to join Chat room…………………………........68 29. Figure 29 Request accepted to join Chat room.………………………….......68 30. Figure 30 Request denied to Join Chat room…………………………….......69 31. Figure 31 Available Multi user Chat rooms……………………………........70 32. Figure 32 Window output of Available Multi user chat rooms……………..70 33. Figure 33 Request Message to allow joining chat room..……………….......71 34. Figure 34 User using multiple chat rooms……………...…………………...72 35. Figure 35 User clicks on about us Link…………………………………......73 36. Figure 36 User directed to about us page...………………………………....74 37. Figure 37 User selecting a file for transfer...………………...……………...75 38. Figure 38 User uploading a file for transfer…………....……………….......76 39. Figure 39 Notification to download the file…..………...…………………..76 40. Figure 40 User downloading the file….………………………………….....77 41. Figure 41 User uploading the file for groups of users.………...…………...78 42. Figure 42 User from chat room downloading the file……..…...……………78 xi 43. Figure 43 Another user from chat room downloading the file....…………..79 xii 1 Chapter 1 INTRODUCTION With the evolution of the web, demand for web applications to be more interactive and provide live, real time informations to the users has been increasing day by day. Web application is an application that is widely used on Internet. Web application is a computer program that is used with web browser such as Internet Explorer, FireFox, Safari, Google Chrome, etc. Recent web advances in web provide new ways for people to communicate on a global scale and assess vast amount of information. Web application is different from many conventional websites in that their emphasis is on allowing user to accomplish tasks such as send email, make travel reservation, pay bills, instant messaging, etc. Websites on the other hand, are content oriented and are designed to facilitate browsing. Common web application includes e-commerce application like retail sales, trading, online auction and web mails, etc. Today web applications are so widely used in social networking, blogging, instant messaging, etc. Web application works on hypertext transfer protocol which is a client-server architecture, this means the client initiate the connection and the server only respond to its request. Earlier client-server application had its own client program which served as its user interface and had to be separately installed and configured on each user's computer, instead web application uses standard format document which are supported by browsers. This feature gives more portability as user can access their application from anywhere in the world. Web applications are also popular with business and software developers as they can be developed, maintained and updated remotely. 2 Figure 1 shows the basic structure of the web applications. [1] Figure 1: Basic Architecture of Web Application In general, web applications use the client/server architecture (i.e. two-tier) where the browser acts as a client. With the evolution of three-tier architecture, it is becoming more popular and even necessary when implementing enterprise systems that require better scalability. Three-tier architecture consist of application server, database Server and client software installed locally (e.g. web browser). Advantage of this system is central database server can be accessed by multiple application server and application server could independently manage thousands of users. Database servers are designed to 3 do database operation such as data storage and low level data manipulation. Application server manages client connections and data processing. Web-based chat application is a form of web application. It allows users to communicate in very easy way using user-friendly web interface. Using such a web application user can avoid installation of specialized softwares. These applications are also accessible from anywhere, using any browsers and with any operating system. There is no requirement of software installation or any software updates. Web-based chat application requires no application download, updates, installation or configuration. No need for any configuration to avoid firewall since the application is embedded/ integrated in a web browser. The purpose of this project is to develop a distributed web-based chat application using open source web application framework Ruby on rails and latest technologies like Ajax, Strophe/Jquery and XMPP. There are many web-based chat applications available in the market, but this project explores some exciting features and compatibility of Ajax, XMPP and Strophe/Jquery with latest technology Ruby on rails. This application allows you to chat with your friend or group of friends and navigate some other pages (e.g. Gmail Chat) while instant messaging. This application will let you add your friends, send an instant message, create and join chat rooms, search for chat rooms and saves your recent chat conversations. This application also allows you to send files to your friend or group of friends. 4 Chapter 2 APPLICATION OVERVIEW This chapter provides functional overview of the web based application. The goal of this project is to build a chat-application using brand new technologies and allow users to use exciting features of chat and also providing them with features to navigate through other web-pages. This application also provides feature of multi user conference and file transfer. Interesting Feature of the Application: The users will have following features: 1. Create login password 2. Add New Friends 3. Edit Friends Information 4. Remove friend from the list 5. View the Presence of the friends 6. Change his own Presence Status 7. Send Instance Message to any friend 8. Join any available multi user chat room 9. Create a new multi user chat room 10. Join multiple chat rooms 11. Search for available chat room 12. View the chat Log History 13. Navigate to other pages during instant messaging 14. Transfer files to your friend 5 15. Transfer files to group of friends during multi user conference 14. Exit from the Application The application overview also provides detailed information for the user and system requirements, system models and system evolution of web-based Chat Application. This chat application has three components web-based client, Chat Server and a Web Server. The three components operate together to form web based chat application. Figure 2 shows very basic architecture of Web-based chat. Chat Server Web Server User Profiles and Membership Server INTERNET Chat Client/ Web Browser Chat Client/ Web Browser Figure 2: Basic Architecture of Web-Based Chat 2.1 Web-Based Chat Client Web based client is an application that transmits messages from user to user. Chat client is an application that communicates with chat server enables users to send 6 messages, to set and change user’s presences. Applications can build their own chat client. 2.2 Web Server Web Servers are the software that allows application to share the information over the internet. Web Servers are based on client-server architecture. Web Servers are the vital part of World Wide Web. e.g. apache. Apache is the most powerful web server used in today’s industry. 2.3 Chat Server Chat server is software that translates all messages for the clients. It also stores all users’ contacts and other information collected from outside source. A chat server receives the commands and messages from the chat clients and processes them. It stores user’s conversation history as well. Figure 3 shows basic overview of the chat client and chat server. [11] Figure 3: Basic Chat Application Overview 7 The web-based client works as the interface between the user and the server. Through the chat client user authenticates to the server using a combination of username and password. Once the user is logged on, the user has the option of sending an instant message, creating or joining a chat room, check previous chat history. User can also create chat rooms to chat with the multiple user or group of members. Once inside the chat room, the user starts communicating with other users by sending and receiving messages. User can also look for available chat rooms and join them if permitted by the chat room owner. During users are provided with the feature of sending a file to their friends. Another advantage of this application is it allows users to transfer a file even if the recipient user is offline. Recipient user can download those files whenever they login to the application. 8 Chapter 3 TOOLS AND TECHNOLOGY This chapter describes various technology and tools that are used to implement this application. The main objective of the project is to implement the XMPP architecture over Ruby on Rails infrastructure and also explore capability of AJAX API and JavaScript open source libraries with Ruby on Rails. In this application Openfire is used as XMPP Server, apache is used as web server and MySQL is used as database server. Enthralling technology CSS is used to create interactive looks in the web application. 3.1 Ruby on Rails Ruby on Rails is an open source web-application framework for the Agile web application development. In Ruby on rails everything is written in the ruby programming language. Ruby follows strict concepts of Object Oriented programming languages (OOPS). RoR provides supportive, integrated environment to develop complete web applications from start to end. Rails also provides libraries for easier database programming, server-side programming and web service programming, on the client side rails also includes a JavaScript prototype and a library for Ajax. Ruby on Rails is designed with various component libraries and works in a similar way to any web application framework. 3.1.1 MVC Framework Framework is a set of program. Rails is an MVC web framework where models, views, and controllers are fully integrated in an unseamed fashion. That means users can have all the benefits of an MVC design without explicitly configuring each component. 9 In rails application when browser sends a request to web server, web server passed on to a rails controller and controller renders the views which is converted to HTML format. In dynamic web application controller interacts with model. Model: Model represents data and it is implemented in ActiveRecord library to maintain tables in relational database. Views: Views represents the data in particular format in other terms user interface. They are script based like java script, ajax, etc. They are implemented in Actionview library. Controller: Controller controls the flow of the application .They are implemented in Actioncontroller which sits between ActiveRecord and Actionview. When web browser sends a request, it is received by web server and passed on to a rails controller which decides what to do next. For dynamic sites controller directly connects to the model and then renders the view but in some case controller directly renders the view. When you install RoR on windows machine all this libraries are listed in ruby\lib\ruby\gems\1.8\gems directory. [15] In this directory you will find all the libraries inside subdirectories. Actionview and Actioncontroller are included in Actionpack directory. 3.1.2 Rails Structure When you creates any rails application, rails creates the entire directory structure as a framework for the application and find the things needed through this structure. For example this project use rails command to create chat application project, rails –d mysql chatapplication 10 Chatapplication project has several directories like app, config, db, public, log, test, doc, lib, script, vendor and temp. [15] Each directory has its own functionality. app : Organizes your application. It has subdirectories that bind model, views and controller. config : Directory maintains code for database configuration, rails environment and routing for web requests. db : Rails manages relational database from the code written in db directory. public : It contains subdirectories for java script files, image files and style sheets. log : All the error logs will be stored in log directory. Failure logs for the server and each rails environment will be stored separately. test : Test files will be placed in test directory. It also contains subdirectories for unit tests, functional tests, etc. doc : Application documentation will be stored in doc directory. Lib : Application specific libraries are stored in lib directory. script : It contains the script to manage various tools that are used with rails. vendor : It contains all the libraries provided by third party. temp : It is used to hold the temporary files. 3.1.3 Configuring Database In rails application database is stored in config/database.yml. Rails by default provides three environment development, testing and production which makes software development much easier. Example of the database for development section is shown below, 11 development: adapter: mysql encoding: utf8 database: openfire username: root password: root host: localhost port: 3307 The database name is automatically generated based on the name of the application or you can manually change the name. You can use your own username and password. The default host name is local host. You can use the similar setting for another database adapter instead of Mysql. Once the database has been configured you can create tables and insert records using defined adapter. Rails active records bind the tables in relational database and ruby program. Ruby method names are normally created from the field names of the database tables. This project uses Openfire to create and maintain real time database. [4] 3.1.4 Models Ruby models are stored inside app/models. You can create models using command, ruby script/generate model hello You can create more than one model in your application. These Models have create, update, delete and read methods for database access. Models allow simple designs 12 and easy mappings between objects and tables. If the application have more than one models then they needs to be connected using associations. These can be done by adding declarations such as has_one, has_many, belongs_to and has_and_belongs_to_many in models. [15] Example of content inside newly created model hello, class hello < ActiveRecord::Base belongs_to :users validates_presence_of :users end 3.1.5 Controllers Controllers are stored inside app/controllers. They are the main logical part of the application. Controller interacts with model, views and users. In this project chat application is using hello controller as central controller. You can create controller using following command, ruby script/generate controller hello With the use of this command file name hello_controller.rb will be created inside controllers directory. In the file controller class will be inherited from application controller which is another controller file in same directory. Once the controller is created you can define any number of functions based on your requirements. [4] For each defined function embedded ruby (html.erb) files needs to be created inside views. Example of controller file is shown below. Both this method aboutus and contact will display the contents created inside respective embedded ruby files. 13 def aboutus if params[:template] render :layout => false end @title = "About Us" end def contact if params[:template] render :layout => false end @title = "Contact Us" end 3.1.6 Views Rails view is an embedded ruby program which can be accessed through controller. They can be found inside app/views. With each of the created controller, new subdirectories with controller’s name will be created inside views. In this project the hello subdirectory is created inside views. For each defined functions in controller respective .html.erb file needs to be created with the same name as functions to display the data. This embedded ruby files allows application to use ruby code inside an HTML file. For example view file for contact functions, 14 <center><div> Utkarsh H Patel </div> <div style="padding-top:15px;"> patelut@ecs.csus.edu </div> <div style="padding-top:15px;"> California State University, Sacaramento </div></center> 3.1.7 Layouts Inside views directory another subdirectory layout is created which provides support to create common look or common template for the final output. In this project this is implemented through application.html.erb file stored inside layouts subdirectory. This layout files are specific to one or more controller depends upon the application. Layout files are programmed using HTML. You can use stylesheet_link_tag and javascript_include_tage helper method to display stylesheet and JavaScript output. When appropriate JavaScript or CSS files are included inside application.html.erb files application will find those files from public/javascripts or public/stylesheets subdirecotries. [15] This is the advantage of using RoR, it makes web application programming much easier, allowing web programmer to write less code and achieve more. [4] Snippet of the code used inside layout file which is necessary to use style sheet and JavaScript in your application, 15 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Website - <%= @title %></title> <%=stylesheet_link_tag("default")%> <%=stylesheet_link_tag("login")%> <%=stylesheet_link_tag("notification")%> <%=stylesheet_link_tag("contextMenu")%> <%= <%= <%= <%= <%= <%= <%= <%= <%= <%= javascript_tag "window._token = '#{form_authenticity_token}'" %> javascript_include_tag 'swfobject'%> javascript_include_tag 'config'%> javascript_include_tag 'jquery'%> javascript_include_tag 'strophejs'%> javascript_include_tag 'callback_handler'%> javascript_include_tag 'common'%> javascript_include_tag 'event_handler'%> javascript_include_tag 'jquery_validate'%> javascript_include_tag 'jquery_notification'%> 3.1.8 Scaffolding and Migration Scaffolding is a technique used by model-view-controller framework that describes how the database will be used. Scaffolding may be considered as a new form of database code generator such as oracle’s CASE generator. When the scaffold is added inside code, rails generate all the required code at run time. The concept behind using scaffolding is to get basic CRUD application that manipulated and prints the data from the table without writing single line of code. [15] Programmer can also use scaffold creation script as shown below, ruby script/generate scaffold hello id:string content:text category:integer When you executes this script rails will generate hello.rb, hello_controller.rb, views folder containing index, show, new and edit files and unit test files When the 16 controller is created using scaffolding any create, read, edit or delete operation can be performed. It allows you to test your application without writing lot of code. . It also creates migration file inside db/migrate subdirectory. Using rails migration you can use ruby code to define changes to your database. It also helps to use version control for your application to keep the thing synchronized. Rails migration can create, drop and rename tables. It can also add, rename, change and remove details inside tables. Migration supports all the basic data types like string, integer, float, text, date and time, timestamp, binary and boolean. [15] Application can manually creates the migration file using ruby scripts as shown below, ruby script/generate migration users This script will create 12_users.rb file. Following code is the example maintaining user’s details through RoR using migration technique. Method self.up is useful for creating new version and self.down is useful to roll back any changes. class users < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name, :limit => 10, :null => false t.string :pass t.text :email t.timestamp :created_at end end 17 def self.down drop_table :users end end 3.1.9 Routes in rails This file can be found inside config directory as config.rb. This routes file contains rules which will parse the URL request and decide where to direct the request. When any application is created following route can be generated, map.connect ':controller/:action/:id' This route specifies that it expects requests that has controller followed by an action and that insert some id. So when the incoming request is received as “http://localhost:3000/hello/login/ut” then it will map as, Controller -> hello Action -> login Id -> ut Routing also has the priorities, defined in the order of appearance in routes.rb file. The routes defined first has the highest priority and the last routes has lowest priority. In this project empty route method is used to specify the routes as shown below. In this method domain name is used in browser to connect to the application. When you use this method index.html file inside public directory needs to be deleted. map.root :controller => "hello" 18 3.1.10 Error Handling Exceptions are used to handle various errors occur during execution of the rails application. It takes proper steps if error occurs rather than stopping the application. Rails exception handling is same as ruby where exception is defined inside begin/end and rescue clause is used to give the type of exception. RoR gives three options every time an exception occurs logs an internal log file, prints appropriate error message or redisplay the same page. All this messages can be displayed from layout file. Exceptions can be written as, [15] begin rescue Execption of One Type rescue Exception of another Type else ensure # Another type always executed end 3.1.11 Instant Rails In this project for the development and deployment purpose instant rails is used which contains Ruby, Rails, MySQL, mongrel and Apache. Instant Rails is the most preferable and easiest way to use Rails on windows machine. Instant rails uses mongrel as secure Ruby/C HTTP server. Mongrel uses fast HTTP library which makes rails application faster. Mongrel (cluster of Mongrel servers) is used with apache to provide extra speed and ability of configuration. [5] 19 3.2 Apache Apache is an open source web server developed by Apache software foundation. It is a very complex web server because of the vast number of features provided. In this project with the use of instant rails a mongrel cluster is used, running on top of Apache with load balancing enabled. So a cluster of Mongrel servers is executed locally, and route requests through Apache’s mod_proxy_balancer. [9] Apache divides the incoming requests among the available Mongrel processes and with careful configuration it can even serve static content. In this project Apache is configured to forward XMPP request over BOSH by enabling proxy module.[9] 3.3 Openfire Openfire is an open source XMPP server, written in JAVA language and is both user friendly and easy to install. Openfire administration runs on the ports 9090 (HTTP) and 9091 (HTTPS) by default. Administrators can connect from anywhere and edit the server's settings, add and delete users. [6] Openfire supports the following features: ï‚· Web-based administration panel. ï‚· Plug-in interface. ï‚· Customizable. ï‚· User-friendly web interface and guided installation. ï‚· Database connectivity for storing messages and user details. ï‚· Lightweight Directory Access Protocol connectivity. ï‚· Platform independent, pure Java 20 In real time web application all the data are real time data, MySQL database server is configured and database is created with Openfire as JDBC driver for MySQL is bundled with Openfire. By using MySQL with Openfire the application can add, edit, delete and query XMPP server users. Openfire stores all data in a back-end database. 3.4 MySQL MySQL is an Open source database system. It is a relational database management system that runs as a server providing multi-user access to a number of databases. It is commonly used for web applications and for embedded applications. MySQL database server provides scalability and flexibility in supporting platforms. It provides high performance in application and robustness. It also has strong data protection. Instant rails have built in preconfigured MySQL support. [10] 3.5 Strophe To create user interface for the web based chat application Strophe libraries are used. Strophe is a collection of libraries for XMPP protocol. It is mostly used in implementing real-time games, notification systems, search engines and in traditional instant messaging. Two main libraries that are used are Strophe.js and libstrophe. Strophe.js a JavaScript library for sending and receiving XMPP data over BOSH and libstrophe is a C library for XMPP clients and components. [7] They can work with any browser. Strophe handles two-way communication with the application. JQuery libraries are also used with Strophe for event handling, animation and AJAX interaction. [8] In this project all javascripts files are placed inside javascript subdirectory of public 21 directory. When the application starts its execution they are all used through application.html.erb file. 3.6 AJAX AJAX stands for Asynchronous JavaScript and XML. Ajax allows programmer to write applications that doesn’t require reloading of a page to display new information. AJAX methodology allows information to be passed back and forth seamlessly which makes websites more dynamic. In Ajax extra data is requested from the server are loaded in the background without interfering with the display and behavior of the existing page. Ajax uses a combination of HTML and CSS to mark up and style information. In this project AJAX is also used to surf other web pages while doing instant messaging at the same time. 3.7 CSS CSS stands for Cascading Style sheets. It defines how to display HTML elements. Styles are normally saved in external .css files. External style sheets changes the appearance and layout of all the pages in a Web site. CSS can also allow the same markup page to be presented in different styles for different rendering method. In this project all css files are stored inside stylesheets subdirectory of public directory. When the application starts its execution they are all used through application.html.erb file. 22 Chapter 4 DESIGN Real time web based chat application is designed and implemented using Extensible Messaging and Presence Protocol (XMPP). XMPP is an open source Extensible Markup Language (XML) based protocol for server-to-server communication, instant messaging and presences. For Real time web based chat application XML-based technologies provide significant advantage to web-scale application. XMPP uses Extensible Markup Language as the base format for exchanging information. XMPP specification defines open protocols that are used for communication among networks and real-time interaction over the internet. [3] 4.1 Basic XMPP Architecture In XMPP architecture a client with a unique name communicates with another client with a unique name through an associated server. Each client implements the client form of the protocol, where the server provides routing capability. Servers are also used for routing between domains. [3] Figure 3 shows simple XMPP architecture made up of one server and two clients. Figure 4: XMPP architecture consisting of a server and two clients 23 4.2 Decentralized Architecture XMPP uses decentralized client-server architecture similar to the architecture used for World Wide Web and email network. This architecture allows one chat client to send messages to any other chat client connected on server. Decentralized architecture based application are easy to manage as client developers can focus on user experience and server developers can focus on reliability and scalability. In XMPP architecture when chat client sends a message to any contact, it first connects to its local server which then connects directly to a contact’s server and contact server finally deliver a message to a contact. [3] Figure 5 shows basic decentralized client-server architecture, Figure 5: Decentralized Client-Server Architecture 24 4.3 Jabber ID (JID) XMPP uses Domain Name System (DNS) to provide the underlying structure for addressing instead of using raw internet protocol addresses. In terms of XMPP it is called JID (JabberID). Every time user creates their user id in XMPP based application, this JID works as their virtual identity on the network. This JID looks much like an email address, it contains all the information required to contact users. Both client and server have JIDs. These JIDs are not limited to old ASCII character range. 4.4 Stanza Real time communication system using XMPP composed of three broad categories of communication. In XMPP this communication is known as stanza. There are three basic kinds of stanzas message, presence and info/query. XMPP stanzas have the following attributes in common: ï‚· From: The JID of the source XMPP entity. ï‚· To: The JID of the intended XMPP recipient. ï‚· Id: An optional identifier for the conversation. ï‚· Type: Optional subtype of the stanza. ï‚· XML:Lang: Language in which the textual description is written. 4.4.1 Message Stanza This is the basic method for getting information from one place to another after the communication is established. There are five types of message stanzas normal, chat, group chat, headline and error. Each of these stanzas is differ in their types. [3] In this 25 project all of above except normal stanza are used. Message stanzas are also used to provide real time web interface. ï‚· Chat: These stanzas are exchanged in a real time while instant messaging. ï‚· Group chat: These stanzas are exchanged in multi-user chat room. ï‚· Headline: These stanzas are used to send alerts and notifications. Senders can not expect a response at all. ï‚· Error: If any error occurs during the communication, the entity that detects the problem will return a message of type error. Message stanza contains only 3 elements body, subject and thread. Example of a simple message stanza, <message from="utpatel@127.0.0.1" to="rohan@127.0.0.1"type="chat"> <body>How are you?</body> <subject>Query</subject> </message> 4.4.2 Presence Stanza Presence is the important feature in real time communication. Presence advertises the network availability of other entities and thus enables users to know whether other entries are online and available for communication. In order to see your presence, other person needs to send you a subscription request which you need to approve. Once you have approved the subscription, that user will automatically receive regular notification about your network availability. In this project XMPP presence state has been extended 26 to some common state like online, busy, away, pending, invisible and offline. In this project presence is typically displayed in the roster. Roster is a presence enabled contact list which usually contains list of JIDs. Presence stanza made up of 3 elements show, status and priority. Priority element of the presence stanza is an optional element which is used to sets the priority of the added JIDs. The priorities can be set from -127 to 128. JID sets with negative priority will never receive this message. [3] Example of simple presence stanza, <presence from="rohan@127.0.0.1"> <show>chat</show> <status>busy</status> </presence> 4.4.3 Info/Query Stanza The Info/Query stanza provides a structure for request response mechanism. It is similar to the GET, POST and PUT method from HTTP. [3] IQ stanzas provide a more reliable transport that is optimized for a structured exchange of data. IQ stanza contains only one payload, which defines the request to be proceed or action to be taken by the recipient. Request and responses are tracked using the id attribute which is generated by the requesting entity and then included by the responding entity. Using IQ Stanza users can add new contact to their rosters. An IQ-set creates, delete or update any kind of information. [3] The type attribute has special values in IQ stanzas, ï‚· Get: The requesting entity asks for account information. ï‚· Set: The requesting entity provides some information or make request. 27 ï‚· Result: The responding entity provides the result of a get operation. ï‚· Error: The requesting entity such as XMPP Server notifies the requesting entity that it was unable to process the get or set request. Example of IQ Stanza, <iq from=utpatel@127.0.0.1 id="rr82a1z7" to="utpatel@127.0.0.1" type="get"> <query xmlns="openfire:iq:roster"/> </iq> XML Stanza can also contain any number of other child elements including XHTML-formatted message bodies, pointers to URLs, RSS, forms to be filled out and a wide range of other payloads. XMPP is a pure XML technology hence it makes extensive use of XML namespace. 4.5 Error Handling XMPP does not acknowledge every message that is sent over network. Instead in XMPP IQ stanzas are more structured, it always generates either an IQ-result or IQ-error in response to an IQ-get or IQ-set. Errors are reported by setting the stanza’s type attribute to a value error, along with an <error/> child element. [3] The type attribute of the <error/> element is one of cancel, continue, modify, or wait. In addition to the stanza error conditions, some conditions are also defined for stream errors and authentications errors. The main difference between these two errors are steam errors are unrecoverable and force to close the XML steam while stanza errors are recoverable and use to report the problem with particular stanzas. [3] 28 Simple example of how the stanza error looks like, <message from="rohan@127.0.0.1” to="ut@127.0.0.1I” type="error"> <error type="cancel"> <service-unavailable xmlns="urn:params:xml:ns:xmpp-stanzas"/> </error> </message> 4.6 Multiuser Chat XMPP also supports group chat aka multi user chat including the processes for joining, participating in, and leaving a chat room. In multi user chat process client needs to reserve a nickname using the in-band registration protocol, imposing appropriate security and privacy measures. Owner or the creator of the chat room owns the authority to delete or ban users from the chat room. In XMPP, group chat is a particular room and it has its own JID. When user creates a chat room, name of the chat room is going to be the JID of that particular room. e.g. news_usa@conference.127.0.0.1. Owner of the chat room can add any of his friends from the contact list by adding his JID in to the chat room. When any other user wants to join this room, user sends his directed presence to the room including preferred nick name as the resource identity which is know as user’s room JID. When any user join the chat room several things happen, [3] ï‚· The room sends a join notification from room JID to the other participants. ï‚· The room sends presence to the user from the JIDs of all other participants. ï‚· The room will also send some the recent messages exchanged. 29 There are several rules associated with the joining of chat room. Owner of the chat room can send request message to users from his list whom he wants to join the room. User who has received the request can either accept or deny. Users are also allowed to join the chat room by sending a request notification to the room owner. They can only join the chat room once the owner accepts the request. XMPP uses several status code to remove and ban the user from the chat room. When the room owner wants to remove any of the user from chat room it simply fires IQ stanza with status code 307. But if the removed user again tries to join the chat room and creates more problem room owner can ban the user by firing IQ stanza with status code 301. [3] 4.7 File Transfer In file transfer, the sender and receiver needs to establish a connection which allows them to transfer binary data stream. From its innovation XMPP is not optimized for data transfer. There are two methods defined in XMPP for managing binary data stream in-band and out-of-bound. In-band method is similar to the instant messaging where data is sent in piece of XML. In out-of-band method clients themselves needs to make separate connections bys sharing IP-address with each other. Out-of-band file transfer is much faster than in-band but it is less secure than in-band. This application uses different approach where user uploads a file to the server and server sends notification using XMPP message stanza to the desired recipient, and using this notification recipient user can download the appropriate file. This approach gives an advantage of transferring a file when the users are not available on the network. Using same method user can also send a file to the group of users during multi-user conference. 30 4.8 Client-Server Connection In XMPP a client session starts by connecting to a server and negotiating the session details, after which client can send message, presence and IQ stanzas to other entities on the network. The session ends when the client decides to close the steam. In XMPP setting up a client-to-server session consist of following phases, ï‚· Initiate a TCP connection to the server. ï‚· Opening an XML steam. ï‚· Negotiating Various Stram Features. ï‚· Authenticating with the server. ï‚· Selecting resources. ï‚· For IM application, requesting and sending initial presence. So after the session has been started, the actual XMPP communication can start happening. 4.9 Server-to-Server Connection When client needs to send a message to a contact on another server, server needs to connect to the other server before it can send the message through. Server-to-server connection basically follows the same pattern as client-to-server connection. After opening a connection to the host serving XMPP for the target JID, the sending server needs to authenticate itself before it is allowed to send a message. [3] 31 4.10 BOSH The client to server and server to server connections are normally happen over long-lived TCP connection. Sometime it can be difficult to maintain long-lived TCP connection. The solution is to use a method that does not require the client to maintain a long-lived TCP connection. To overcome this issue Bidirectional-streams over Synchronous HTTP (BOSH) are used in which HTTP request/response pairs are synchronously used multiple times. [3] BOSH based systems are normally deployed with a special connection manager that acts a proxy between the client and the XMPP server. In this project apache is used as proxy which works as connection manager between the client and Openfire XMPP server. [3] In addition to the all above mentioned features XMPP provides service discovery features which is helpful to determine what clients and servers are available on the network and what are the XMPP features those entities implement. These can be done using disco#items and disco#info. [3] 32 Chapter 5 IMPLEMENTATION This chapter describes how the chat application is implemented using Ruby on Rails and Strophe JavaScript libraries to implement XMPP design. Using RoR appropriate controller and for each controller respective embedded ruby files has been created. All java script and style sheets have been included in application.html.erb ruby layout file which will be used by browser during run time. All the implemented features of this application will be explained one by one. 5.1 Connection and Registration For any web based application first of all connection needs to be made between the client and server. Chat application makes the connection using the username and password created by the user. For the first time user or non-registered user, application provides registration option to create username and password. For registration one predefined user account and password needs to be created in order to establish connection with the chat server. Predefined account will be created by chat server administrator. Following Strophe XMPP API is used to make connection with the chat server which is Openfire in this project, [7] connection.connect(predifinedAcc, predifinedAccP,onShadowConnect) Here predifinedAcc is user’s JID and predifinedAccP is user’s password created by Openfire administrator.(e.g. test@127.0.0.1 ), onShadowConnect is connect callback function for the notification when the connection is established. As the connection 33 process proceeds, callback function retrieve the registration fields to know how many fields are required for registration. Only some of them are mandatory like username, password, email and name. You can also customize registration page as per the requirements. In “onShadowConnect” function, handler function is added using strophe API definition like below, connection.addHandler (onRegisterCred, 'jabber:iq:register', 'iq', null, null, null) This function adds a stanza handler to the connection. This handler will be called for any stanza that matches the parameters. If multiple parameters are supplied, they must all match for the handler to be invoked. [7] This application has several handler created depending on the functionalities, examples are - presence stanza handler connection.addHandler(notifyPresence, null, 'presence', null, null, null); - chat stanza handler connection.addHandler(onchatmessage, null, "message", "chat"); - friend list stanza handler connection.addHandler(rosterChanged, Strophe.NS.ROSTER, "iq", "set"); - group chat stanza handler connection.addHandler(onGCmessage,null, "message", "groupchat"); - chat history stanza handler connection.addHandler(showChatHistroy,"urn:xmpp:archive","iq""result"); 34 Now once the handler is created, appropriate IQ stanza will be sent to chat server to retrieve registration fields. In this project it is created as shown below, var iq = $iq( { id: connection.getUniqueId("register"), type: "get"}) .c("query", {xmlns: "jabber:iq:register” }); connection.send(iq.tree()); Once all required registration fields will be received from chat server the handler will be called. In this case “onRegisterCred” function will send the details entered by user to the chat server for registration. Below given sample code for IQ stanza is used for registration, var iq = $iq( {id: reg_id, type: "set" }) .c("query", { xmlns: "jabber:iq:register"}) .c('username').t(username).up() .c('name').t(name).up().c('email').t(email).up() .c('passwor').t(password) Once IQ stanza is sent, chat server will send the acknowledgment message in handler function weather the user is created or not. 35 5.2 Login After user successfully registered themselves to the application, system allows them to enters in to main application using their username and password. For users to enter in to main application login needs to be created. When user enters correct username and password and click on “Login” button first of all information in login form will be validated against fields. Login validation function is created which requires correct username and password. After successful authentication user will be connected to the chat server using user’s JID as shown below, [7] connection.connect (Buildjid(LoginJID,VHOST),LoginPass,onConnect) Then callback function will be called after user is connected with chat server, in this case it is “onConnect”. Once the user is connected to the chat server user’s login credential should be stored for continuous session in session variable. The session is created as method inside rails controller as shown below. In this project this is created inside hello_controller, def login session[:loginjid] = params[:loginjid] session[:loginpass] = params[:loginpass] render :layout => false end 36 5.3 Adding Friend To provide add new contact feature, new IQ stanza needs to be created and send it to the server. This can be done using JID of the any contact user wants to add. But application also needs to make sure that the added contact is registered to the application and user use correct information to add contact. Method is created in to rails controller to retrieve the registered users as shown below, def checkfriend if params[:name] @rs=sql.select_all("select count(username) as rs from ofuser where username='#{params[:name]}'") render :text => @rs end end After retrieving the list, function validates the contact added by user. If the entered information is correct, IQ stanza will be sent as shown below to the chat server with all required details. var iq = $iq({type: "set"}) .c("query", {xmlns: Strophe.NS.ROSTER}) .c("item", {name: name || "", jid: jid}) 37 Now, if the contact is added in to the friend list, notification message will be sent the added contact using presence stanza. Until added contact accepts the request, status of the request will be pending. Presence stanza needs to be sent as below. var subscribe = $pres({to: jid, "type": "subscribe"}); If added contact accepts user’s presence subscription then system will reply with subscribed presence stanza to user as shown below. connection.send($pres({to: tojid,"type": "subscribed"})); If contact rejects presence subscription then system will reply unsubscribed presence stanza to user as below. connection.send($pres({to: tojid,"type": "unsubscribed"})); 5.4 Edit Friend Information Application allows user to edit the information of added contact. Edit functionality is same as add friends but in edit section contact values are set on input field using contact’ JID, nickname and contact’s group. In this project following function is used to edit the information, callbackEdit(RosterJID,Rosternickname,Rostergroup) 5.5 Remove Friend From List Users are allowed to remove their contact from the list. To remove contact from list simple IQ stanza with user‘s JID is sent to chat server. Chat server will remove the 38 contact from the list and acknowledge with handler method. Example of IQ stanza for remove friend is shown below, var iq = $iq({type: "set"}) .c("query", {xmlns: Strophe.NS.ROSTER}) .c("item", {jid: jid, subscription: "remove"}); 5.6 View Presence of the Friends Presence is the important aspects in real time communication which enables users to know whether other users are available or not. When the user is connected to the chat server he has to send his own presence status to others to inform other users about his availability. That can be sent as, connection.send($pres().tree()); Then retrieve user roster (friend) list by creating function to get user’s roster on each connection. Following IQ stanza will be fired to get friends list, var roster_iq = $iq({type: "get"}) .c('query', {xmlns: Strophe.NS.ROSTER}); Now every contact in user’s list knows that user is online but user needs to retrieve all his contact’s presence status as well. To achieve this below stanza is used and chat server will reply according to the availability of the contact’s presence. connection.send($pres({to: RosterJID, type: "probe"})); 5.6.1 Change own Presence Status In this chat application user can also change his own presence status e.g. invisible, away, online, busy etc. To achieve this, function is created and when the user changes his 39 presence, current presence status is sent to all his friends using the same method when user first get connected to the application var presenceStatus = obj.value; changeStatus(JIDtoID(connection.jid), findPresenceClass(presenceStatus)); connection.send($pres().c("show").t(presenceStatus)); connection.flush(); When user selects “Logout” option from presence status selection, first of all “Offline” presence status is sent to all friends and then Strophe disconnect() API method is called to close connection. if(presenceStatus=="unavailable") connection.send($pres({type:presenceStatus}).tree()); connection.disconnect(); When the user logged out from the application, a method is created inside rails controller to close the session of the particular user. def logout if session[:loginjid] reset_session end render :layout => false end. 40 5.7 Instant Messaging To send an instant message to any friend “Chat” window is created where user can type and send messages. Function is created with runtime html to be build at runtime and appended to body tag and also all required events are bind to html elements. e.g. key press event on text area and also configure file uploader to send file to any friend. Another function is created to handle key press events in text area in popup window. This function continuously sends composing status message when any key is pressed except Enter key. In instant messaging all the messages and notification will be send using XMPP message stanza. var notify = $msg({to: reciepentjid, "type": "chat"}) .c('composing', {xmlns: "http://jabber.org/protocol/chatstates"}) If after typing a message, enter key is pressed then the message will be sent in the form of message stanza to the respective friend and message will be displayed in sender’s chat message area as well. var message = $msg({to: reciepentjid,type:"chat"}) .c('body').t(body).up() .c('active', {xmlns: "http://jabber.org/protocol/chatstates"}); connection.send(message); Handler function is created to display the same message on receiver’s chat message window. Here onchatmessage function is used to handle incoming messages and composing status messages. 41 connection.addHandler(onchatmessage, null, "message", "chat"); Snippet of the function which handles all the chat message activity, function onchatmessage(message){ var full_jid = $(message).attr('from'); var jid = Strophe.getBareJidFromJid(full_jid); var jid_id = JIDtoID(jid); var composing = $(message).find('composing'); var domainPart=Strophe.getDomainFromJid(jid) if($(message).find("invite").length>0){ var chatroom=$(message).find("invite").attr("fromroom"); showGCInvitation(jid_id,chatroom,jid,''); return true; } if(domainPart==ChatRoomServer){ var bodyMsg=$(message).find('body').text(); if(bodyMsg=='accept'){ $("#"+jid_id).show(); } else{ $("#"+jid_id).remove(); alert("Sorry..Your request for " + jid + " room has been rejected by moderator."); } return true; } if (composing.length > 0) { $("[chatid='"+jid_id+"'] .chat-event").html(' ( Composing... )'); if($("[chatid='"+jid_id+"']").is(":visible")==true){ scrollChat(jid_id); } } var body = $(message).find("html > body"); if (body.length === 0) { body = $(message).find('body'); if (body.length > 0) { body = body.text() } else { body = null; } } else { 42 body = body.contents(); var span = $("<span></span>"); body.each(function () { if (document.importNode) { $(document.importNode(this, true)).appendTo(span); } else { // IE workaround span.append(this.xml); } }); body = span; } if (body) { $("[chatid='"+jid_id+"'] .chat-event").html(""); if($("[chatid='"+jid_id+"']").is(":visible")==false){ ConfigChatPopup(jid_id,jid); } // add the new message $("[chatid='"+jid_id+"'] .chat-messages").append( "<div class='chat-message'><span class='chat-name' style='color:#49AED7;'>" + Strophe.getNodeFromJid(jid) + " : </span><span class='chat-text'>" + body + "</span></div>" ); scrollChat(jid_id); } return true; } 5. 8 Group Chat In XMPP, group chat is a particular room and it has its own chat room id which is JID. When user creates any chat room that name is going to be the JID of the chat room. To create chat room just bind a nickname with chat room id then fire simple presence stanza as shown below. If chat room is not already created then chat server will create a room for you with the provided data. In below code nickname is the name 43 provided by users, and chat room is the name of the chat room provided by user. e.g. smart_tv@conference.127.0.0.1 connection.send($pres({to:chatroom+"/"+nickname}).c('x',{xmlns:Groupie.NS_MUC})) If chat room is already available then user can become the member of that chat room by joining the chat room. To send and catch chat server’s notification presence stanza handler is defined at the time of logged in as shown below. Presence stanza is defined because when the user becomes the member of any chat room, room consider members as “available” and when the get out of the room, room consider them as “unavailable” connection.addHandler(notifyPresence, null, 'presence', null, null, null) For all incoming presence stanza a function is created which will handle all the request. Chat server will return Status code 201 if room is successfully created. Once status code is return by chat server system will send IQ stanza to unlock the room for use and opens the group chat window. Snippet of the source code for chat server response is shown below, var code = preStatusObj.getAttribute('code'); switch (code) { case '201': // room created var iq = $iq({ to: from, type: "set" }).c("query", { xmlns: Groupie.NS_MUCOWNER 44 }) .c("x",{xmlns: "jabber:x:data", type:"submit"}); connection.send(iq); ConfigGroupChatPopup(fromJID_ID,fromjid,from,'block'); Groupie.participants[fromjid]["moderator"]=tojid; break; If someone tries to join the already created chat room, room owner should be able to decide whether to accept that user or not. If room owner wants to allow the user to join chat room he will accept it otherwise reject the request. When any user tries to join chat room, system sends notification with request message to room owner (moderator) and reply with appropriate response from room owner. This request message is created using message stanza. This can be done using code shown below, if(Groupie.participants[fromjid]["moderator"]==tojid) {ConfigGroupChatPopup(fromJID_ID,fromjid,from,'block'); if(confirm(nick + " wants to join "+fromjid+" groupchat discussion.\n\rDo you want them to continue ?")) {var groupchatnotify=$msg({to:from,id:"groupchatnotify",type:"chat"}).c('body').t('accept'); connection.send(groupchatnotify); } else{var groupchatnotify=$msg({to:from,id:"groupchatnotify",type:"chat"}).c('body').t('reject'); 45 connection.send(groupchatnotify); kickGCOccupantAtJoin(escape(nick),fromjid) } If any group chat member willing to get out of chat room then he will send “unavailable” presence stanza to group chat room and then chat server will notify to other room members about absence of the user. If user logged out during continuous chat room session without leaving chat room, system consider user as “unavailable” and follow the same procedure. Procedure is shown below, If (Groupie.participants[fromjid][nick] && ptype == 'unavailable') {Groupie.participants[fromjid][nick] =’’; $("#" + fromJID_ID + ' .participant-list #'+convertStrToID(nick)).remove(); GCUserLeft(nick,fromJID_ID); } Now to delete a member from chat room forcefully, iq stanza is created using nick name and chat room id as shown below. var iq = $iq({to: chatroom,type:"set"}) .c('query', {xmlns: Groupie.NS_MUCADMIN}) .c('item', {nick: nick,role:'none'}) .c('reason').t(''); connection.send(iq); For sending and displaying group chat message handler function is created which will handle all the instant messaging activity inside chat rooms. It uses the same 46 procedure as explained in section 5.7, but instead of sending message stanza to the user’s JID, it is sent to chat room JID as shown below, var body = $(this).val(); connection.send($msg({to: gcroom, type: "groupchat"}).c('body').t(body)); To invite another user in chat room message like below is sent and invitee will get the message notification. var invitee=$("#"+notifyID).find(".gconline").val(); var msg=$msg({to:invitee,type:"chat"}) .c('body').t("invitation"). c('invite',{fromroom : room}); Invited user will have option to accept or decline the request. According to the Invitee’s selection appropriate message using following code will be sent. These message are created using XMPP message stanza. If ($(message).find("invite").length>0) { var chatroom=$(message).find("invite").attr("fromroom"); showGCInvitation(jid_id,chatroom,jid,''); } To retrieve number of available chat room IQ stanza is created as below. Chat server will reply with all the available chat rooms. Every time new chat room is created it will be added in to the list and with the provided refresh button it will be available. var service_iq = $iq({to: ChatRoomServer,id:"info2",type:"get"}) 47 .c('query',{xmlns: trophe.NS.DISCO_ITEMS}); connection.sendIQ(service_iq,function(iq){ GetGroupChatList(iq);}); Users are also allowed to join multiple chat rooms. To join multiple chat rooms join button with room selection option is provided. As explained earlier to join any chat room simple presence stanza will be fired with the room JID and user JID. 5.9 File Transfer To transfer file during instant messaging, file needs to be uploaded on to the server by sender and downloadable link is sent to the receiver to download the file. Function is created to configure file uploader in instant chat window using JID of the users and chatID. In rails controller a method is created which is used to upload the file as shown below. def uploadfile if params[:Filedata] filename=params[:Filedata].original_filename sendto = params[:sendto] directory = @@pathtodonwload+"#{sendto}" FileUtils.mkdir_p(directory) path = File.join(directory, filename) File.open(path, "wb") { |f| f.write(params[:Filedata].read)} @my_json="{success:true,path:'#{sendto}/# {filename}',sendto:'#{sendto}', 48 file:'#{filename}'}" render :layout => false end end This method gets the file name and receiver’s name as follows, filename=params[:Filedata].original_filename sendto = params[:sendto] Server will create the appropriate directory path for the receiver to download the file, write the uploaded file in created folder and then successful string message is return by web server. directory = @@pathtodonwload+"#{sendto}" FileUtils.mkdir_p(directory) @my_json="{success:true,path:'#{sendto}/#{filename}',sendto:'#{sendto}',file:'# {filename}'}" Now, when the file is successfully uploaded, recipient JID is fetched from string in this case string is my_json, the downloadable link will be sent using message stanza to recipient as follows, var message = $msg({to: reciepentjid,type:"chat"}) .c('body').t(downloadlink).up() .c('active', {xmlns: "http://jabber.org/protocol/chatstates"}); 49 When user clicked on download link rails controller’s “download” method is executed. In download method, file path is used which is a query string and default rails method to download file is used. def download if params[:file] file = params[:file] send_file @@pathtodonwload+"#{file}" end end In group chat file transfer feature follows the same above procedure but here the downloadable link will be sent to all the available user inside chat room using chat room JID. 5.10 Recent Chat History This application also has a feature of viewing the message history. To get chat history, function is created to retrieve the list of message collections using IQ stanza. Shown below is the IQ stanza for requesting a collections list with JID, var getCollections=$iq({id:"page1",type:"get"}) .c("list",{xmlns:"urn:xmpp:archive",'with':chatwith}) .c("set",{xmlns:"http://jabber.org/protocol/rsm"}) .c("max").t("30"); connection.sendIQ(getCollections, function (iq){ 50 var totalCollections=$(iq).find("chat").length;} Here the client sends a <list/> element. The 'start' and 'end' attributes can be used specifies to date range, 'with' attribute specify the JIDs in IQ stanza. If the 'with' attribute is omitted then collections with any JID are returned. If only 'start' is specified then all collections on or after that date should be returned. If only 'end' is specified then all collections prior to that date should be returned. To request a page of messages from a collection the client sends a <retrieve/> element. The 'with' and 'start' attributes specify the participating JID and the start time respectively. Both attributes must be included to uniquely identify a collection. IQ stanza used for retrieving messages is shown below, var startTime=$(this).attr('start'); var getCollection = $iq({id:"1",type:"get"}) .c("retrieve",{xmlns:"urn:xmpp:archive", 'with':chatwith,start:startTime}) .c("set",{xmlns:"http://jabber.org/protocol/rsm"}) .c("max").t("100"); connection.sendIQ(getCollection); To display conversations messages in browser handler function is used which will display list of all the available conversations. To delete chat history a function is created which makes an Ajax call to web server to delete archive messages. Inside rails 51 controller a using index delete query is created which will delete conversation messages from respective tables. 52 Chapter 6 EXECUTION AND SCREEN LAYOUT This chapter runs through the complete work flow of the application. Screen layouts have also been placed for details. Now when the application is deployed using instant rails through mongrel server and user types www.chatpplication.com in webbrowser, application starts its execution 6.1 Home Page When the application starts its execution the first page will be home page with log in option.For non-register or first time user registration option is also available in home page. Figure 6 shows the home page of the application, Figure 6: Home page 53 6.2 Registration Screen Non-register users or first time users can register themselves to use this application. When the non-registered user clicks on register now option, apploication displays the registration box with appropriate options in the browser. Figure 7 shows registration form for the new user. Figure 7: Registration Page 54 After the user enters all the required information and click the registration button following message as shown in figure 8 appears on the screen. Application validates the required details. Figure 8: Registration Successful Message If user misses any information then application gives following error messages. Figure 9: Registration Error Messages 6.3 Login Screen User enters in to the main chat application by providing appropriate username and password. Application validates the username and password and allows user to access the application if the provided information is correct. If user enters wrong information then application displays error messages. Figure 10 shows login screen. 55 Figure 10: Login Screen Figure 11 shows login error message if user leaves username and password fields blank. Figure 12 shows error message if user enters incorrect username or password, application displays following error message. Figure 11: Login Error Message 1 Figure 12: Login Error Message 2 56 6.4 Chat Application Screen after Successful Login Once user enters correct username and password, he is authorized to enter in to the main chat application. Initially when user enters in to the application for the first time the screen will be displayed as shown in figure 13. Application retrieves all his contacts if he has any. Application allows users to add his friends, change his presence status, instant messaging and use all other features available through this application. Figure 13: Chat Application Screen after Login 57 6.5 User Presence or Status Change Screen After successfully logged in to the chat application user can change their presence status. They have options like online, busy, away and invisible. User can select logout option to exit from the application. Figure 14 shows all the available presence status options, Figure 14: Presence Status Change 58 6.6 Add Friends Users can add their friends in to their contact list by adding another user’s ID. If User1 enters correct contact information about User2 and User2 is registered to this application, system sends add request notification to the User2 and adds the User2 with pending status in to User1’s contact list. When User2 accept the request, he will be added to the User1’s contact list with appropriate status message. If User2 decline the request User2 will be removed from the list. If User1 enters incorrect id or that person is not registered to the application system gives appropriate error messages. Figure 15 shows screen output when user press add button. Figure 15: Add User 59 Figure 16 and 17 shows various error messages generated while user tries to add contact with incorrect ID. Figure 16: Incorrect User Id Figure 17: Adding user not registered to the application 60 Figure 18 shows the add request notification sends to the User2 from User1. Figure 18: Add request notification message 6.7 Chat Message Once the friend is added in to the contact list, users can send instant messages to their friends. When user double clicks on any added contact application will open chat pop up window for instant messaging. 61 Figure 19 shows chat window with chat messages, Figure 19: Chat window with chat messages 6.8 Edit or Delete Contacts User can edit their contacts, user can also delete their contacts by using specific option available through right clicking on any contact. When user right clicks on any contact application gives users edit, delete, chat and recent history options. Figure 20 shows screen output for all the available option when user right clicks on any added contacts. 62 Figure 20: Available options for added contact Figure 21 shows window output when user click on edit option tries to edit any of his added friend’s information. Figure 21: Edit Contact Information 63 Figure 22 shows screen messages when user clicks on delete option to delete any of his contact. Figure 22: Delete Contact 6.9 Recent Chat Conversations When user right clicks on any contact, application also gives an option to check his previous conversation with that contact. User can view all his previous conversations, he can also delete any conversation if he does not need them anymore. Figure 23 shows how the recent chat conversation window looks like and Figure 24 show its screen output in application. 64 Figure 23: Recent Chat Conversation Window Figure 24: Recent Chat Conversation Screen Output 65 6.10 Group Chat Web Based chat application also has provision for the multi user chat where user can create their own chat room, send a request to the friends to join the chat room.. User can also search for the available chat room and join any of the available chat rooms by sending request to the owner of the chat room. If owner of the room accepts the request user can join the chat room. Application also provides ownership right to the room creator to decline any request or remove any user from the chat room at any time. Application provides users group chat icon to join or create the chat room. Figure 25 shows screen output with available option. Figure 25: Provision for Multi user Chat room 66 When user clicks on create chat room option, application asks user to provide certain necessary information to create chat room. When user provides appropriate information, application creates the chat room with option of adding contacts in to chat room and sending file. Figure 26 shows screen output of newly created chat room, Figure 26: Newly Created Chat room 67 Figure 27 shows window output of newly created chat room, Figure 27: Window of Newly Created Chat room After creating a chat room user can invite any of his friends from the contact list to join particular chat room irrespective of user is online or offline. Application will send the notification to all the invited users. Online users can join the chat room immediately and offline users can join the chat room once they become the online by accepting the notification. Figure 28 shows request message when a room owner sends request to his friend to join chat room. 68 Figure 28: Request Message to join Chat room When user accepts or deny the invitation to join the chat room appropriate response message will be send to the creator of chat room. Figure 29 shows a message when a request was accepted to join chat room. Figure 29: Request accepted to join Chat room 69 Figure 30 shows a message when a request was denied to join chat room. Figure 30: Request denied to join Chat room Every time new chat room is created, application will add it in to the list of the chat rooms. Every time user clicks on refresh button, application provides all available chat rooms. Figure 31 shows screen output when user search for the available chat rooms. 70 Figure 31: Available Multi user Chat rooms Figure 32 shows window output for available created chat room, Figure 32: Window output of Available Multi user chat rooms 71 User can join any of the above available chat rooms only if their request was accepted by the room owner. When user tries to join a chat room, a request message to allow joining a chat room will be send to the owner of the chatroom. Chat room owner has right to accept or deny the request. Application also provides authority to the room owner to delete any user at any time from the chat room. Figure 33 shows request message sent to chat room owner when user tries to join chat room. Figure 33: Request Message to allow joining chat room 72 User can also join multiple chat rooms at any time. Figure 34 shows screen output where user has joined multiple chat rooms. Figure 34: User using multiple chat rooms Users are also allowed to share a file with multiple users during group chat. This portion will be covered in file transfer part. 73 6.11 Chat with other Apps While doing instant messaging, application allows users to navigate to any other web-links available with in the application that does not stop, halts or pause their instant massaging process. This is the ample advantage of this web based application. This feature allows web-based application to include other useful applications with chat application. In this project while instant messaging user can navigate to about us or contact us pages which are embedded ruby pages and does not stop instant messaging. Figure 35 and 36 illustrate how user can jump from one webpage to another during chatting. Figure 35: User clicks on about us Link 74 Figure 36: User directed to about us page 6.12 File Transfer This application allows user to transfer files to their friends. Users can send file during one-to-one instant messaging or also during group chat. This application also enables user to send a file while the recipient user is offline. This is the biggest advantage of this feature in this application. 75 Figure 37 and figure 38 shows screen layout when user1 tries to send file to user2, Figure 37: User selecting a file for transfer 76 Figure 38: User uploading a file for transfer Figure 39 and figure 40 shows screen layout when user2 tries to download the file. Figure 39: Notification to download the file 77 Figure 40: User downloading the file This application enables users to transfer a file to the group of users during group chat. Figure 41 shows screen layout when user is trying to send a file for available users in chat room. 78 Figure 41: User uploading the file for group of users Figure 42 shows screen layout when one user from chat room tries to download the file. Figure 42: User from chat room downloading the file 79 Figure 43 shows screen layout when another user from same chat room tries to download the file. Figure 43: Another user from chat room downloading the file 80 Chapter 7 CONCLUSION AND FUTURE WORK Instant messaging has been always integral part of our lives and is extensively used. Embedding instant messaging with real time web based application it becomes more valuable. Biggest advantage of web based applications is they are available to broadest audience. Web based application allows user to use the application from any where at anytime irrespective of device or operating system. In conclusion, this project demonstrates how ruby on rails can be used to develop user friendly web based applications. Ruby on Rails provide solid infrastructure to build a web application. This project also delivered its primary goal to implement XMPP architecture over ruby on rails. This project also explores compability of Ruby on Rails with other technology like AJAX, Java Script and MySQL. Through this project I have learned that good architecture and design produce high quality software application and has very fewer bugs. For future work and enhancements, we can extend the application to support on large scale use and also implement wide verities of features. There is scope for significant future work on the project especially related to video conferencing. This application already supports file sharing within a group during mutli-user chat, using same scenario multi-user video conferencing will be developed, where users can share their video with multiple users. 81 APPENDIX Installation Procedure This section describes the procedure to install require software and procedure to execute web based chat application. Prerequisites: The following hardware and software is required to install and execute the web based chat application. System Requirements: Computer with a 1GB RAM, 20 GB of available hard-disk space, Microsoft Windows XP with Service Pack 2 or higher versions, 1024x768 or higher-resolution display with 256 colors. Software Requirements: Java 2 SDK 1.4.2_13, MySQL 5.1, OpenFire 3.6.4, Instant Rails 2.0, Internet Explorer 7 or 8, Firefox 3 and higher, Safari 4, Chrome 4. To develop and deploy ruby on rails download and configure all folllowing technologies. Installing MySQL Download MySQL community server 5.1. [13] Once the download process is finish launch MySQL workbench. Once you open it create new connection to create databse for openfire. While making connection give appropriate name for the connection which you are going to use throught your project, enter 127.0.0.1 or any domain name as host name. Prefer 127.0.0.1 as a hostname during development process because Openfire 82 normally works on http://127.0.0.1:9090 and create username and password that you remember.e.g. root. I have used SQLyog Enterprise as MySQL GUI. Installing Openfire Download latest version of Openfire. [6] Once the download process is completed, click on launch admin to open web based wizard for configuration. When you are on web-based wizard it will give you the option for embeded database connection or standard database connection, select standard database selection. Select MySQL as Database Driver Presets, insert the name of the server and database inside database URL field, e.g. jdbc:mysql://localhost:3307/openfire. Use the same username and password that has been created inside MySQL server, with this procedure configuration for server administration and location for XMPP server has been established. Once the server set up is done, login to the admin screen, click on edit properties. User server name 127.0.0.1 or any domain name of your JID you want to use for the application. For this application one predined user is created by going to the user/groups option inside openfire which is used during registration process.By using MySQL with Openfire, application can add, edit, delete, and query all XMPP server users, as well as scale your XMPP infrastructure in line with your web infrastructure. This will work as your Chat Server which will maintain all the real time data. Installing Instant rails Download latest version of instant rails. [14] Instant rails contain bundle of Ruby, Rails, MySQL, mongrel and Apache. Lanuch instant rails to configure apache, and windows host file. This application will use apache as web server. Once you have 83 installed Instantrails, apache needs to be configured to forward XMPP request over BOSH. Openfire maintains an HTTP binding URL for access over BOSH at http://localhost:3007/http-bind. [6] To use this on port 80 configure apache HTTP server to forward a XMPP URL to this location. For this proxy module in http.conf, apache configuration file needs to be enabled to enable proxy support. Also copy following code in httpd.conf file of apache. <VirtualHost *> ServerName www.chatapplication.com ProxyRequests Off ProxyPass /xmpp-httpbind http://127.0.0.1:7070/http-bind/ ProxyPassReverse /xmpp-httpbind http://127.0.0.1:7070/http-bind/ ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000 </VirtualHost> After successfully installing web server and chat server, before deploying the chatapplication using ruby on rails Mongrel server, copy following line in instant rail’s windows host file to deploy the application using mongrel.. 127.0.0.1 www.chatapplication.com Now when you execute www.chatapplication.com in your browser you will be able to see web-based chat application login page. 84 REFERENCES [1] J.D. Meier; Alex Homer; David Hill; Jason Taylor “Web application Architecure Pocket Guide”, Microsoft Corporation, 2008 [2] David Flanagan; Yukihiro Matsumoto “Beginning Ruby:From Novice to Professional,” 2nd ed., 2009 [3] Peter Saint-Andre; Kevin Smith, and Remko Tronçon, “XMPP: The Definitive Guide”, 1st ed., O'Reilly Media, 2009 [4] Dave Thomas; David Heinemeier Hansson; Sam Ruby, “Agile Web Development with Rails,” 3rd ed., Pragmatic Bookshelf, 2006 [5] http://instantrails.rubyforge.org [6] http://www.igniterealtime.org [7] http://strophe.im/strophejs/ [8] http://api.jquery.com/jQuery/ [9] http://tomcat.apache.org/ [10] http://www.mysql.com [11] http://cnx.org/content/m30811/latest/ [12] http://jabber.org [13] http://www.mysql.com/downloads/mysql/ [14] http://www.rubyforge.org [15] http://www.tutorialspoint.com/ruby-on-rails-2.1/