Sunday 30 November 2014

Mailchimp Integration CodeIgniter


Codeigniter MailChimp API v2 Wrapper

I am sharing my Codeigniter Code regarding Mailchimp integration. May this small code can be helpful for someone.

Reference - https://github.com/benbowler/codeigniter-mailchimp-api-v2



<?php 

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or - 
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */

    public function __construct() {
        parent::__construct();
        $this->load->library('Mailchimp_library');
    }

    public function index()
    {       
        $list_id = '';
        $lists = $this->mailchimp_library->call('lists/list');
        if(isset($lists["data"][0])) {
            $list_id = $lists["data"][0]["id"];
        }
        if(!empty($list_id)) {
            $result = $this->mailchimp_library->call('lists/subscribe', array(
                'id'                => $list_id,
                'email'             => array('email'=>'sourabhgupta3838@gmail.com'),
                'merge_vars'        => array('FNAME'=>'Sourabh', 'LNAME'=>'Gupta'),
                'double_optin'      => false,
                'update_existing'   => true,
                'replace_interests' => false,
                'send_welcome'      => false,
            ));
            print_r($result);
        }
        $this->load->view('welcome_message');
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

MySQL Stored Procedure Tutorial

MySQL Stored Procedure Tutorial

I am sharing an example of MySQL stored procedure.

DELIMITER $$

USE `company`$$

DROP PROCEDURE IF EXISTS `update_t`$$

CREATE DEFINER=`root`@`%` PROCEDURE `update_t`(OUT last_id INT(11),OUT last_url 
VARCHAR(200))
BEGIN    
    SELECT company_id,company_url INTO last_id,last_url FROM company 
    ORDER BY id ASC LIMIT 0,1 LOCK IN SHARE MODE;
    UPDATE company SET cc=1 WHERE company_id = last_id;
    END$$

DELIMITER ;

Sphinx Search Engine installation WAMP

Sphinx Search Engine installation WAMP



 Here is my environment:

  • Windows
  • WAMP
  • Apache 2.2.11
  • MySQL 5.1.36
  • PHP 5.3.0
  • Sphinx 1.10
First of all download Sphinx for Windows which can be found (http://sphinxsearch.com/downloads/beta/).

Sphinx creates a separate index of the table you want to search. Your PHP scripts calls the Sphinx API to search connecting to a specific port where Sphinx is listening to. Sphinx then searches its own index and does the search returning the result. Yes, the index has to be updated every time your update your original table. 

Once you have created sphinx.conf in the bin folder copy the content from c:\sphinx\sphinx-min.conf.in (this is their provided sample file). It looks like:
#
# Minimal Sphinx configuration sample (clean, simple, functional)
#

source src1
{
 type   = mysql

 sql_host  = localhost
 sql_user  = test
 sql_pass  =
 sql_db   = test
 sql_port  = 3306 # optional, default is 3306

 sql_query  = \
  SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS
  date_added, title, content \
  FROM table

 sql_attr_uint  = group_id
 sql_attr_timestamp = date_added

 sql_query_info  = SELECT * FROM table WHERE id=$id
}

index test1
{
 source   = src1
 path   = @CONFDIR@/data/test1
 docinfo   = extern
 charset_type  = sbcs
}

index testrt
{
 type   = rt
 rt_mem_limit  = 32M

 path   = @CONFDIR@/data/testrt
 charset_type  = utf-8

 rt_field  = title
 rt_field  = content
 rt_attr_uint  = gid
}

indexer
{
 mem_limit  = 32M
}

searchd
{
 listen   = 9312
 listen   = 9306:mysql41
 log   = @CONFDIR@/log/searchd.log
 query_log  = @CONFDIR@/log/query.log
 read_timeout  = 5
 max_children  = 30
 pid_file  = @CONFDIR@/log/searchd.pid
 max_matches  = 1000
 seamless_rotate  = 1
 preopen_indexes  = 0
 unlink_old  = 1
 workers   = threads # for RT to work
}
These settings should cover most of what you're looking for in terms of setting up Sphinx.

Code in PHP script:
require_once('sphinxapi.php');
//Sphinx
$s = new SphinxClient;
$s->setServer("localhost"9312);
$s->setMatchMode(SPH_MATCH_EXTENDED2);


Sphinx commands:

C:\wamp\www\sphinx-2.2.3-beta-
win32\bin>indexer.exe --config c:\wamp\www\sphinx-
2.2.3-beta-win32\sphinx.conf.in test1

C:\wamp\www\sphinx-2.2.3-beta-win32\bin>searchd.exe --install --config c:\wamp\w
ww\sphinx-2.2.3-beta-win32\sphinx.conf.in --servicename SphinxSearch

Monday 10 November 2014

Webcam Broadcast using WebRTC and JavaScript

Webcam Broadcast using WebRTC and JavaScript


Introduction:

This document is created to describe technologies used and process flow of Video Broadcasting project.

Prerequisites:

Basic knowledge: HTML5, CSS, JQuery/JavaScript, experience in Online Chat application
Experience of Node.js would also be useful.
Installed on your development machine:
  • Google Chrome or Firefox.
  • Code editor.
  • Web cam.
  • Node.js with socket.io and express.

Technologies:

Node.JS

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. We used Node.js for making signalling server.

Download latest node.js - http://nodejs.org/download/. Install Node.Js using windows binary

WebRTC

Its a free, open project that enables web browsers with Real-Time Communications (RTC) capabilities via simple JavaScript APIs. The WebRTC components have been optimized to best serve this purpose. 

Socket.IO

Aims to make Realtime Apps possible in every browser and mobile device.
WEBRTC Video Conference chat app requires some modules i.e. socket.io, express

INSTALLATION

1. create folder videoconf
2. open command prompt. Go to path of videoconf folder.
3. command to install socket.io – [path to nodejs folder]/npm install socket.io
4. command to install express - [path to nodejs folder]/npm install express

Note: socket.io and express modules will install by node.js in folder videoconf/node_modules.

Node.js automatically assigns Apache’s Server Host to Socket.io.js and will use as follows:

Client side: 
script src = "http://locahost/socket.io/socket.io.js" > < /script>


Server.js

Server.js file is used for Communication/Chat Server. Server.js makes socket connections, receives messages to and from clients, can run any Javascript functionality on Server side like making AJAX requests from Server side only, converting video formats using FFMPEG command.

Server.js sample:

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
    socket.emit('news', {
        hello: 'world'
    });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});


Note: any unique port can assign Multiple servers can create on one platform using multiple server.js files but need to give different ports.

5. RUN SERVER - [path to nodejs folder]/node [path to webchat folder]/server.js.
6. Server will run in command prompt
7. on Linux to run server in background, I used: nohup command

Command to run any Linux command oin background:

nohup node server.js

client.js sample:

<script src="http://localhost/socket.io/socket.io.js"></script>

<!-- socket.io.js will run on your localhost and this path is automatically set by node.js. Its node.js magic. -->

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', {
        my: 'data'
    });
});

navigator.getUserMedia

navigator.getUserMedia function of Mozilla and Chrome bowser us used to open webcam in the browser.


RTCPeerConnection.js

Javascript class RTCPeerConnection is the WebRTC API for video and audio calling.



HTML5

HTML5 is used at client side to get stream and give stream to Video element.

Process flow for Webcam Broadcasting:

1.    We run server.js file on server using node command[described above]. The code is in javascript. We can use jquery also we need to install jquery module in node. We assign one unique port in server.js which is used to make connection on client side.
2.    On client side A user using HTML5, JQuery and Socket.io creates socket connection on server using unique port
3.    Also A user make global object of Conference class [conference.js].
4.    On connect method, A user asked to open the webcam.
5.    Once browser gets A user’s webcam stream, stream get attach with conference attach using config.attachstream method.
6.    Conference object sends offer to other peer.
7.    When other peer B user connects to server with above procedure, he gets offer sent by A user peer connection and also receives A user’s stream
8.    B user in return sends answer to A user that he joins him. But we are not asking B user to open the webcam because he will be viewer only.
9.    Once both users get joined and B User receives A user’s webcam stream using socket.getremotestream function, and puts stream in video element.
10.  B user starts viewing A’s webcam.
11.  A’s stream stops when user call leave function of conference.
12.  If A user close his browser, his stream will stop sending.
13.  We can notify B user and other peer connections that host has closed his webcam
14.  Any number of peer connections can be made. We need to test load.

File Structure in Fleshcast for Webcam Broadcasting:

1.            Server.js - placed on root
2.            RTCPeerConnection.js and conference.js JS files placed in assets/js folder
3.            HTML5 and Javascript code to make connection and open webcam is done in golive method in sitemodels controller.

References:

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...