Create Event by Importing JSON files in Open Event Server

Apart from the usual way of creating an event in  FOSSASIA’s Orga Server project by using POST requests in Events API, another way of creating events is importing a zip file which is an archive of multiple JSON files. This way you can create a large event like FOSSASIA with lots of data related to sessions, speakers, microlocations, sponsors just by uploading JSON files to the system. Sample JSON file can be found in the open-event project of FOSSASIA. The basic workflow of importing an event and how it works is as follows: First step is similar to uploading files to the server. We need to send a POST request with a multipart form data with the zipped archive containing the JSON files. The POST request starts a celery task to start importing data from JSON files and storing them in the database. The celery task URL is returned as a response to the POST request. You can use this celery task for polling purposes to get the status. If the status is FAILURE, we get the error text along with it. If status is SUCCESS we get the resulting event data In the celery task, each JSON file is read separately and the data is stored in the db with the proper relations. Sending a GET request to the above mentioned celery task, after the task has been completed returns the event id along with the event URL. Let’s see how each of these points work in the background. Uploading ZIP containing JSON Files For uploading a zip archive instead of sending a JSON data in the POST request we send a multipart form data. The multipart/form-data format of sending data allows an entire file to be sent as a data in the POST request along with the relevant file informations. One can know about various form content types here . An example cURL request looks something like this: curl -H "Authorization: JWT <access token>" -X POST -F 'file=@event1.zip' http://localhost:5000/v1/events/import/json The above cURL request uploads a file event1.zip from your current directory with the key as ‘file’ to the endpoint /v1/events/import/json. The user uploading the feels needs to have a JWT authentication key or in other words be logged in to the system as it is necessary to create an event. @import_routes.route('/events/import/<string:source_type>', methods=['POST']) @jwt_required() def import_event(source_type): if source_type == 'json': file_path = get_file_from_request(['zip']) else: file_path = None abort(404) from helpers.tasks import import_event_task task = import_event_task.delay(email=current_identity.email, file=file_path, source_type=source_type, creator_id=current_identity.id) # create import job create_import_job(task.id) # if testing if current_app.config.get('CELERY_ALWAYS_EAGER'): TASK_RESULTS[task.id] = { 'result': task.get(), 'state': task.state } return jsonify( task_url=url_for('tasks.celery_task', task_id=task.id) ) After the request is received we check if a file exists in the key ‘file’ of the form-data. If it is there, we save the file and get the path to the saved file. Then we send this path over to the celery task and run the task with the .delay() function of celery. After the celery task is started, the corresponding data about the import job is…

Continue ReadingCreate Event by Importing JSON files in Open Event Server

Implementing Admin Statistics Mail and Session API on Open Event Frontend

This blog article will illustrate how the admin-statistics-mail and admin-statistics-session API  are implemented on the admin dashboard page in Open Event Frontend.Our discussion primarily will involve the admin/index route to illustrate the process.The primary end points of Open Event API with which we are concerned with for fetching the admin statistics  for the dashboard are GET /v1/admin/statistics/mails GET /v1/admin/statistics/sessions First we need to create the corresponding models according to the type of the response returned by the server , which in this case will be admin-statistics-event and admin-statistics-sessions, so we proceed with the ember CLI commands: ember g model admin-statistics-mail ember g model admin-statistics-session Next we define the model according to the requirements. The model needs to extend the base model class, and all the fields will be number since the all the data obtained via these models from the API will be numerical statistics import attr from 'ember-data/attr'; import ModelBase from 'open-event-frontend/models/base'; export default ModelBase.extend({  oneDay     : attr('number'),  threeDays  : attr('number'),  sevenDays  : attr('number'),  thirtyDays : attr('number') }); And the model for sessions will be the following. It too will consist all the attributes of type number since it represents statistics import attr from 'ember-data/attr'; import ModelBase from 'open-event-frontend/models/base'; export default ModelBase.extend({  confirmed : attr('number'),  accepted  : attr('number'),  submitted : attr('number'),  draft     : attr('number'),  rejected  : attr('number'),  pending   : attr('number') }); Now we need to load the data from the api using the models, so will send a get request to the api to fetch the current permissions. This can be easily achieved via a store query in the model hook of the admin/index route.However this cannot be a normal get request. Because the the urls for the end point are /v1/admin/statistics/mails & /v1/admin/statistics/sessions but there are no relationships between statistics and various sub routes, which is what ember’s default behaviour would expect. Hence we need to override the generated default request url using custom adapters and use buildUrl method to customize the request urls. import ApplicationAdapter from './application'; export default ApplicationAdapter.extend({  buildURL(modelName, id, snapshot, requestType, query) {    let url = this._super(modelName, id, snapshot, requestType, query);    url = url.replace('admin-statistics-session', 'admin/statistics/session');    return url;  } }); The buildURL method replaces the the default  URL for admin-statistics-session  with admin/statistics/session otherwise the the default request would have been GET v1/admin-statistics-session Similarly it must be done for the mail statistics too. These will ensure that the correct request is sent to the server. Now all that remains is making the requests in the model hooks and adjusting the template slightly for the new model. model() {    return RSVP.hash({          mails: this.get('store').queryRecord('admin-statistics-mail', {        filter: {          name : 'id',          op   : 'eq',          val  : 1        }      }),      sessions: this.get('store').queryRecord('admin-statistics-session', {        filter: {          name : 'id',          op   : 'eq',          val  : 1        }      })    });  } queryRecord is used instead of query because only a single record is expected to be returned by the API. Resources Ember JS-models - Official ember documentation Ember JS adapters - Official ember documentation Open Event API Docs - authored by  Fossasia project…

Continue ReadingImplementing Admin Statistics Mail and Session API on Open Event Frontend

Enhancing LoklakWordCloud app present on Loklak apps site

LoklakWordCloud app is presently hosted on loklak apps site. Before moving into the content of this blog, let us get a brief overview of the app. What does the app do? The app generates a word cloud using twitter data returned by loklak based on the query word provided by the user. The user enters a word in the input field and presses the search button. After that a word cloud is created using the content (text body, hashtags and mentioned) of the various tweets which contains the user provided query word. In my previous post I wrote about creating the basic functional app. In this post I will be describing the next steps that have been implemented in the app. Making the word cloud clickable This is one of the most important and interesting features added to the app. The words in the cloud are now clickable.Whenever an user clicks on a word present in the cloud, the cloud is replaced by the word cloud of that selected word. How do we achieve this behaviour? Well, for this we use Jqcloud’s handler feature. While creating the list of objects for each word and its frequency, we also specify a handler corresponding to each of the word. The handler is supposed to handle a click event. Whenever a click event occurs, we set the value of $scope.tweet to the selected word and invoke the search function, which calls the loklak API and regenerates the word cloud. for (var word in $scope.wordFreq) { $scope.wordCloudData.push({ text: word, weight: $scope.wordFreq[word], handlers: { click: function(e) { $scope.tweet = e.target.textContent; $scope.search(); } } }); } As it can be seen in the above snippet, handlers is simply an JavaScript object, which takes a function for the click event. In the function we pass the word selected as value of the tweet variable and call search method. Adding filters to the app Previously the app generated word cloud using the entire tweet content, that is, hashtags, mentions and tweet body. Thus the app was not flexible. User was not able to decide on which field he wants his word cloud to be generated. User might want to generate his  word cloud using only the hashtags or the mentions or simply the tweet body. In order to make this possible, filters have been introduced. Now we have filters for hashtags, mentions, tweet body and date. <div class="col-md-6 tweet-filters"> <strong>Filters</strong> <hr> <div class="filters"> <label class="checkbox-inline"><input type="checkbox" value="" ng-model="hashtags">Hashtags</label> <label class="checkbox-inline"><input type="checkbox" value="" ng-model="mentions">Mentions</label> <label class="checkbox-inline"><input type="checkbox" value="" ng-model="tweetbody">Tweet body</label> </div> <div class="filter-all"> <span class="select-all" ng-click="selectAll()"> Select all </span> </div> </div> We have used checkboxes for the individual filters and have kept an option to select all the filters at once. Next we require to hook this HTML to AngularJS code to make the filters functional. if ($scope.hashtags) { tweet.hashtags.forEach(function (hashtag) { $scope.filteredWords.push("#" + hashtag); }); } if ($scope.mentions) { tweet.mentions.forEach(function (mention) { $scope.filteredWords.push("@" + mention); }); } In the above snippet, before adding the hashtags to the list…

Continue ReadingEnhancing LoklakWordCloud app present on Loklak apps site

Adding Voice Recognition in Description Dialog Box in Phimpme project

In this blog, I will explain how I added Voice Recognition in a dialog box to describe an image in Phimpme Android application. In Phimpme Android application we have an option to add a description for the image. Sometimes the description can be long. Adding Voice Recognition text to speech will ease the user's experience to add a description for the image. Adding appropriate Dialog Box In order to take input from the user to prompt the Voice Recognition function, I have added an image button in the description dialog box. Since the description dialog box will only contain an EditText and a button will have used material design to make it look better and add caption on top of it.   <LinearLayout   android:id="@+id/rl_description_dialog"   android:layout_width="match_parent"   android:layout_height="wrap_content"   android:orientation="horizontal"   android:padding="15dp">   <EditText       android:id="@+id/description_edittxt"       android:layout_weight="1"       android:layout_width="fill_parent"       android:layout_height="wrap_content"       android:padding="15dp"       android:hint="@string/description_hint"       android:textColorHint="@color/grey"       android:layout_margin="20dp"       android:gravity="top|left"       android:inputType="text" />   <ImageButton       android:layout_width="@dimen/mic_image"       android:layout_height="@dimen/mic_image"       android:layout_alignRight="@+id/description_edittxt"       app2:srcCompat="@drawable/ic_mic_black"       android:layout_gravity="center"       android:background="@color/transparent"       android:paddingEnd="10dp"       android:paddingTop="12dp"       android:id="@+id/voice_input"/> </LinearLayout> Function to prompt dialog box We have added a function to prompt the dialog box from anywhere in the application. getDescriptionDialog() function is used to prompt the description dialog box. getDescriptionDialog() returns EditText which can be further be used to manipulate the text in the EditText. Please follow the following steps to inflate description dialog box in the activity. First, In the getDescriptionDialog() function we will inflate the layout by using getLayoutInflater function. We will pass the layout id as an argument in the function. public EditText getDescriptionDialog(final ThemedActivity activity, AlertDialog.Builder descriptionDialog){ final View DescriptiondDialogLayout = activity.getLayoutInflater().inflate(R.layout.dialog_description, null); Second, Get the TextView in the description dialog box. final TextView DescriptionDialogTitle = (TextView) DescriptiondDialogLayout.findViewById(R.id.description_dialog_title); Third, Present the dialog using cardview to make use of the material design. Then take an instance of the EditText. This EditText can be further used to input text from the user either by text or Voice Recognition. final CardView DescriptionDialogCard = (CardView) DescriptiondDialogLayout.findViewById(R.id.description_dialog_card); EditText editxtDescription = (EditText) DescriptiondDialogLayout.findViewById(R.id.description_edittxt); Fourth, Set onClickListener when the user clicks the mic image icon. This onClicklistener will prompt the voice Recognition in the activity. We need to specify the language for the speech to text input. In the case of Phimpme its English so “en-US”. We have set the maximum results to 15.   ImageButton VoiceRecognition = (ImageButton) DescriptiondDialogLayout.findViewById(R.id.voice_input); VoiceRecognition.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View v) {       // This are the intents needed to start the Voice recognizer       Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);       i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");       i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 15); // number of maximum results..       i.putExtra(RecognizerIntent.EXTRA_PROMPT, R.string.caption_speak);       startActivityForResult(i, REQ_CODE_SPEECH_INPUT);   } }); Putting Text in the EditText After Voice Recognition prompt ends the onActivityResult function checks to see if the data is received or not. if (requestCode == REQ_CODE_SPEECH_INPUT && data!=null) { We get the spoken text from intent data.getString() and store it in ArrayList. To store the received data in a string we need to get the first string from the ArrayList. ArrayList<String> result = data       .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); voiceInput = result.get(0); Setting the received data in the the EditText editTextDescription.setText(voiceInput); Conclusion Using Voice recognition is a quick and simple way to add a…

Continue ReadingAdding Voice Recognition in Description Dialog Box in Phimpme project

Google Authentication and sharing Image on Google Plus from Phimpme Android

In this blog, I will be explaining how I implemented Google Authentication and sharing an Image on GooglePlus from Phimpme Android application. Adding Google Plus authentication in accounts activity in Phimpme Android In accounts Activity, we added Google Plus option. This is done by adding “Googleplus” in accountName.   public static String[] accountName = { "Facebook", "Twitter", "Drupal", "NextCloud", "Wordpress", "Pinterest", "Flickr", "Imgur", "Dropbox", "OwnCloud", "Googleplus"}; Add this to your Gradle Build. Please note that the version of Google:play-services in the grade should be same. In the case of Phimpme the version is 10.0.1, so all the services from Google should be 10.0.1. compile 'com.google.android.gms:play-services-auth:10.0.1 In onCreate we need to make the object of the GoogleSignInOptions. This is required to call methods: requestEmail() and build. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)       .requestEmail()       .build(); Building GoogleApiClient with access to the Google Sign and the option specified by the gso. mGoogleApiClient = new GoogleApiClient.Builder(this)       .enableAutoManage(this , AccountActivity.this)       .addApi(Auth.GOOGLE_SIGN_IN_API, gso)       .build(); Signing in Google Authentication can take place through intent which calls logged in users on the phone. The user will choose an option to select the account he or she wants to authenticate the application. private void signInGooglePlus() {   Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);   startActivityForResult(signInIntent, RC_SIGN_IN); } Adding Google Plus account in the Realm Database HandleSignInResult() function is used to handle Sign in result. This result includes: Storing the received data in the Realm Database. Showing the appropriate username in the Accounts activity and handling login failed. Checking if login is successful or not If the login is successful a Toast message will pop up to show the appropriate message.   private void handleSignInResult(GoogleSignInResult result) {   if (result.isSuccess())       GoogleSignInAccount acct = result.getSignInAccount();//acct.getDisplayName()       Toast.makeText(AccountActivity.this, R.string.success, Toast.LENGTH_SHORT).show(); Creating Object to store the details in Realm Database. First, we need to begin realm transaction.Then add logged in username in the database. To display the username we will create the function setUserName(acct.getDisplayName()). And then finally commit everything to Realm database.         realm.beginTransaction();       account = realm.createObject(AccountDatabase.class,       accountName[GOOGLEPLUS]);       account.setUsername(acct.getDisplayName());       realm.commitTransaction();   } Adding Google Plus option in Sharing Activity. To add Google Plus option in the sharing Activity we first added Google Plus icon in the resource folder. The Google Plus icon is SVG(scalable vector) format so that we can manipulate it to apply any colour and size. <vector xmlns:android="http://schemas.android.com/apk/res/android"   android:width="24dp"   android:height="24dp"   android:viewportHeight="32.0"   android:viewportWidth="32.0">   <path       android:fillColor="#00000000"       android:pathData="M16,16m-16,0a16,16 0,1 1,32 0a16,16 0,1 1,-32 0" />   <path       android:fillColor="#000000"       android:pathData="M16.7,17.2c-0.4,-0.3 -1.3,-1.1 -1.3,-1.5c0,-0.5 0.2,-0.8 1,-1.4c0.8,-0.6 1.4,-1.5 1.4,-2.6c0,-1.2 -0.6,-2.5 -1.6,-2.9h1.6L18.8,8h-5c-2.2,0 -4.3,1.7 -4.3,3.6c0,2 1.5,3.6 3.8,3.6c0.2,0 0.3,0 0.5,0c-0.1,0.3 -0.3,0.6 -0.3,0.9c0,0.6 0.3,1 0.7,1.4c-0.3,0 -0.6,0 -0.9,0c-2.8,0 -4.9,1.8 -4.9,3.6c0,1.8 2.3,2.9 5.1,2.9c3.1,0 4.9,-1.8 4.9,-3.6C18.4,19 18,18.1 16.7,17.2zM14.1,14.7c-1.3,0 -2.5,-1.4 -2.7,-3.1c-0.2,-1.7 0.6,-3 1.9,-2.9c1.3,0 2.5,1.4 2.7,3.1C16.2,13.4 15.3,14.8 14.1,14.7zM13.6,23.2c-1.9,0 -3.3,-1.2 -3.3,-2.7c0,-1.4 1.7,-2.6 3.6,-2.6c0.4,0 0.9,0.1 1.2,0.2c1,0.7 1.8,1.1 2,1.9c0,0.2 0.1,0.3 0.1,0.5C17.2,22.1 16.2,23.2 13.6,23.2zM21.5,15v-2h-1v2h-2v1h2v2h1v-2h2v-1H21.5z" /> </vector> Sharing Image on Google Plus from Sharing Activity After creating the appropriate button, we need to send the image to Google Plus. We need to import the PlusShare files in the SharingActivity. import com.google.android.gms.plus.PlusShare; Share Image function To share the image on Google Plus we have used PlusShare function which comes in Google Plus…

Continue ReadingGoogle Authentication and sharing Image on Google Plus from Phimpme Android

Developing LoklakWordCloud app for Loklak apps site

LoklakWordCloud app is an app to visualise data returned by loklak in form of a word cloud. The app is presently hosted on Loklak apps site. Word clouds provide a very simple, easy, yet interesting and effective way to analyse and visualise data. This app will allow users to create word cloud out of twitter data via Loklak API. Presently the app is at its very early stage of development and more work is left to be done. The app consists of a input field where user can enter a query word and on pressing search button a word cloud will be generated using the words related to the query word entered. Loklak API is used to fetch all the tweets which contain the query word entered by the user. These tweets are processed to generate the word cloud. Related issue: https://github.com/fossasia/apps.loklak.org/pull/279 Live app: http://apps.loklak.org/LoklakWordCloud/ Developing the app The main challenge in developing this app is implementing its prime feature, that is, generating the word cloud. How do we get a dynamic word cloud which can be easily generated by the user based on the word he has entered? Well, here comes in Jqcloud. An awesome lightweight Jquery plugin for generating word clouds. All we need to do is provide list of words along with their weights. Let us see step by step how this app (first version) works. First we require all the tweets which contain the entered word. For this we use Loklak search service. Once we get all the tweets, then we can parse the tweet body to create a list of words along with their frequency. var url = "http://35.184.151.104/api/search.json?callback=JSON_CALLBACK&count=100&q=" + query; $http.jsonp(url) .then(function (response) { $scope.createWordCloudData(response.data.statuses); $scope.tweet = null; }); Once we have all the tweets, we need to extract the tweet texts and create a list of valid words. What are valid words? Well words like ‘the’, ‘is’, ‘a’, ‘for’, ‘of’, ‘then’, does not provide us with any important information and will not help us in doing any kind of analysis. So there is no use of including them in our word cloud. Such words are called stop words and we need to get rid of them. For this we are using a list of commonly used stop words. Such lists can be very easily found over the internet. Here is the list which we are using. Once we are able to extract the text from the tweets, we need to filter stop words and insert the valid words into a list. tweet = data[i]; tweetWords = tweet.text.replace(", ", " ").split(" "); for (var j = 0; j < tweetWords.length; j++) { word = tweetWords[j]; word = word.trim(); if (word.startsWith("'") || word.startsWith('"') || word.startsWith("(") || word.startsWith("[")) { word = word.substring(1); } if (word.endsWith("'") || word.endsWith('"') || word.endsWith(")") || word.endsWith("]") || word.endsWith("?") || word.endsWith(".")) { word = word.substring(0, word.length - 1); } if (stopwords.indexOf(word.toLowerCase()) !== -1) { continue; } if (word.startsWith("#") || word.startsWith("@")) { continue; } if (word.startsWith("http") || word.startsWith("https")) { continue; } $scope.filteredWords.push(word); }…

Continue ReadingDeveloping LoklakWordCloud app for Loklak apps site

Export an Event using APIs of Open Event Server

We in FOSSASIA’s Open Event Server project, allow the organizer, co-organizer and the admins to export all the data related to an event in the form of an archive of JSON files. This way the data can be reused in some other place for various different purposes. The basic workflow is something like this: Send a POST request in the /events/{event_id}/export/json with a payload containing whether you require the various media files. The POST request starts a celery task in the background to start extracting data related to event and jsonifying them The celery task url is returned as a response. Sending a GET request to this url gives the status of the task. If the status is either FAILED or SUCCESS then there is the corresponding error message or the result. Separate JSON files for events, speakers, sessions, micro-locations, tracks, session types and custom forms are created. All this files are then archived and the zip is then served on the endpoint /events/{event_id}/exports/{path} Sending a GET request to the above mentioned endpoint downloads a zip containing all the data related to the endpoint. Let’s dive into each of these points one-by-one POST request ( /events/{event_id}/export/json) For making a POST request you firstly need a JWT authentication like most of the other API endpoints. You need to send a payload containing the settings for whether you want the media files related with the event to be downloaded along with the JSON files. An example payload looks like this: {  "image": true,  "video": true,  "document": true,  "audio": true } def export_event(event_id): from helpers.tasks import export_event_task settings = EXPORT_SETTING settings['image'] = request.json.get('image', False) settings['video'] = request.json.get('video', False) settings['document'] = request.json.get('document', False) settings['audio'] = request.json.get('audio', False) # queue task task = export_event_task.delay( current_identity.email, event_id, settings) # create Job create_export_job(task.id, event_id) # in case of testing if current_app.config.get('CELERY_ALWAYS_EAGER'): # send_export_mail(event_id, task.get()) TASK_RESULTS[task.id] = { 'result': task.get(), 'state': task.state } return jsonify( task_url=url_for('tasks.celery_task', task_id=task.id) ) Taking the settings about the media files and the event id, we pass them as parameter to the export event celery task and queue up the task. We then create an entry in the database with the task url and the event id and the user who triggered the export to keep a record of the activity. After that we return as response the url for the celery task to the user. If the celery task is still underway it show a response with ‘state’:’WAITING’. Once, the task is completed, the value of ‘state’ is either ‘FAILED’ or ‘SUCCESS’. If it is SUCCESS it returns the result of the task, in this case the download url for the zip. Celery Task to Export Event Exporting an event is a very time consuming process and we don’t want that this process to come in the way of user interaction with other services. So we needed to use a queueing system that would queue the tasks and execute them in the background with disturbing the main worker from executing the other user…

Continue ReadingExport an Event using APIs of Open Event Server

Uploading Files via APIs in the Open Event Server

There are two file upload endpoints. One is endpoint for image upload and the other is for all other files being uploaded. The latter endpoint is to be used for uploading files such as slides, videos and other presentation materials for a session. So, in FOSSASIA’s Orga Server project, when we need to upload a file, we make an API request to this endpoint which is turn uploads the file to the server and returns back the url for the uploaded file. We then store this url for the uploaded file to the database with the corresponding row entry. Sending Data The endpoint /upload/file  accepts a POST request, containing a multipart/form-data payload. If there is a single file that is uploaded, then it is uploaded under the key “file” else an array of file is sent under the key “files”. A typical single file upload cURL request would look like this: curl -H “Authorization: JWT <key>” -F file=@file.pdf -x POST http://localhost:5000/v1/upload/file A typical multi-file upload cURL request would look something like this: curl -H “Authorization: JWT <key>” -F files=@file1.pdf -F files=@file2.pdf -x POST http://localhost:5000/v1/upload/file Thus, unlike other endpoints in open event orga server project, we don’t send a json encoded request. Instead it is a form data request. Saving Files We use different services such as S3, google cloud storage and so on for storing the files depending on the admin settings as decided by the admin of the project. One can even ask to save the files locally by passing a GET parameter force_local=true. So, in the backend we have 2 cases to tackle- Single File Upload and Multiple Files Upload. Single File Upload if 'file' in request.files: files = request.files['file'] file_uploaded = uploaded_file(files=files) if force_local == 'true': files_url = upload_local( file_uploaded, UPLOAD_PATHS['temp']['event'].format(uuid=uuid.uuid4()) ) else: files_url = upload( file_uploaded, UPLOAD_PATHS['temp']['event'].format(uuid=uuid.uuid4()) ) We get the file, that is to be uploaded using request.files[‘file’] with the key as ‘file’ which was used in the payload. Then we use the uploaded_file() helper function to convert the file data received as payload into a proper file and store it in a temporary storage. After this, if force_local is set as true, we use the upload_local helper function to upload it to the local storage, i.e. the server where the application is hosted, else we use whatever service is set by the admin in the admin settings. In uploaded_file() function of helpers module, we extract the filename and the extension of the file from the form-data payload. Then we check if the suitable directory already exists. If it doesn’t exist, we create a new directory and then save the file in the directory extension = files.filename.split('.')[1] filename = get_file_name() + '.' + extension filedir = current_app.config.get('BASE_DIR') + '/static/uploads/' if not os.path.isdir(filedir): os.makedirs(filedir) file_path = filedir + filename files.save(file_path) After that the upload function gets the settings key for either s3 or google storage and then uses the corresponding functions to upload this temporary file to the storage. Multiple File Upload elif 'files[]' in request.files:…

Continue ReadingUploading Files via APIs in the Open Event Server

Implementation of Text-To-Speech Feature In Susper

Susper has been given a voice search feature through which it provides the user a better experience of search. We introduced to enhance the speech recognition by adding Speech Synthesis or Text-To-Speech feature. The speech synthesis feature should only work when a voice search is attempted. The idea was to create speech synthesis similar to market leader. Here is the link to YouTube video showing the demo of the feature: Video link In the video, it will show demo : If a manual search is used then the feature should not work. If voice search is used then the feature should work. For implementing this feature, we used Speech Synthesis API which is provided with Google Chrome browser 33 and above versions. window.speechSynthesis.speak(‘Hello world!’); can be used to check whether the browser supports this feature or not. First, we created an interface: interface IWindow extends Window {   SpeechSynthesisUtterance: any;   speechSynthesis: any; };   Then under @Injectable we created a class for the SpeechSynthesisService. export class SpeechSynthesisService {   utterence: any;  constructor(private zone: NgZone) { }  speak(text: string): void {   const { SpeechSynthesisUtterance }: IWindow = <IWindow>window;   const { speechSynthesis }: IWindow = <IWindow>window;  this.utterence = new SpeechSynthesisUtterance();   this.utterence.text = text; // utters text   this.utterence.lang = 'en-US'; // default language   this.utterence.volume = 1; // it can be set between 0 and 1   this.utterence.rate = 1; // it can be set between 0 and 1   this.utterence.pitch = 1; // it can be set between 0 and 1  (window as any).speechSynthesis.speak(this.utterence); }// to pause the queue of utterence pause(): void {   const { speechSynthesis }: IWindow = <IWindow>window; const { SpeechSynthesisUtterance }: IWindow = <IWindow>window;  this.utterence = new SpeechSynthesisUtterance();   (window as any).speechSynthesis.pause();  } }   The above code will implement the feature Text-To-Speech. The source code for the implementation can be found here: https://github.com/fossasia/susper.com/blob/master/src/app/speech-synthesis.service.ts We call speech synthesis only when voice search mode is activated. Here we used redux to check whether the mode is ‘speech’ or not. When the mode is ‘speech’ then it should utter the description inside the infobox. We did the following changes in infobox.component.ts: import { SpeechSynthesisService } from ‘../speech-synthesis.service’; speechMode: any; constructor(private synthesis: SpeechSynthesisService) { } this.query$ = store.select(fromRoot.getwholequery); this.query$.subscribe(query => {   this.keyword = query.query;   this.speechMode = query.mode; });   And we added a conditional statement to check whether mode is ‘speech’ or not. // conditional statement // to check if mode is ‘speech’ or not if (this.speechMode === ‘speech’) {   this.startSpeaking(this.results[0].description); } startSpeaking(description) {   this.synthesis.speak(description);   this.synthesis.pause(); } The source code for the implementation can be found here: https://github.com/fossasia/susper.com/commit/3624d504c4687c227016b4fea229c680ad80a613 Resources Getting started with the Speech Synthesis API. Web Apps that talk - Introduction to Speech Synthesis API.      

Continue ReadingImplementation of Text-To-Speech Feature In Susper

Implementing Speakers Call API in Open Event Frontend

This article will illustrate how to display the speakers call details on the call for speakers page in the Open Event Frontend project using the Open Event Orga API. The API endpoints which will be mainly focussing on for fetching the speaker call details are: GET /v1/speakers-calls/{speakers_call_id} In the case of Open Event, the speakers are asked to submit their proposal beforehand if they are interested in giving some talk. For the same purpose, we have a section on the event’s website called as Call for Speakers on the event’s public page where the details about the speakers call are present along with the button Submit Proposal which redirects to the link where they can upload the proposal if the speakers call is open. Since the speakers call page is present on the event’s public page so the route which will be concerned with will be public/index route and its subroute public/index/cfs in the application. As the call for speakers details are nested within the events model so we need to first fetch the event and then from there we need to fetch the speaker-calls detail from the model. The code to fetch the event model looks like this: model(params) { return this.store.findRecord('event', params.event_id, { include: 'social-links' }); } The above model takes care of fetching all the data related to the event but, we can see that speakers call is not included as the parameter. The main reason behind this is the fact that the speakers is not required on each of the public route, rather it is required only for the subroute public/index/cfs route. Let’s see how the code for the speaker-call modal work to fetch the speaker calls detail from the above event model.   model() { const eventDetails = this.modelFor('public'); return RSVP.hash({ event : eventDetails, speakersCall : eventDetails.get('speakersCall') }); } In the above code, we made the use of this.modelFor(‘public’) to make the use of the event data fetched in the model of the public route, eliminating the separate API call for the getting the event details in the speaker call route. Next, using the ember’s get method we are fetching the speakers call data from the eventDetails and placing it inside the speakersCall JSON object for using it lately to display speakers call details in public/index subroute. Until now, we have fetched event details and speakers call details in speakers call subroute but we need to display this on the index page of the sub route. So we will pass the model from file cfs.hbs to call-for-speakers.hbs the code for which looks like this: {{public/call-for-speakers speakersCall=model.speakersCall}} The trickiest part in implementing the speakers call is to check whether the speakers call is open or closed. The code which checks whether the call for speaker has to be open or closed is: isOpen: computed('startsAt', 'endsAt', function() { return moment().isAfter(this.get('startsAt')) && moment().isBefore(this.get('endsAt')); }) In the above-computed property isOpen of speakers-call model, we are passing the starting time and the ending time of the speakers call. We are…

Continue ReadingImplementing Speakers Call API in Open Event Frontend