Coder Social home page Coder Social logo

appdotnetphp's Introduction

AppDotNetPHP

PHP library for the App.net Stream API

More info on the App.net Stream API here

Find more App.net code libraries and examples here

Sign up for App.net here

NOTE:
The Stream API is currently under development. This library will be rapidly changing in accordance with changes made in the API.

Contributors:

WARNING:

This version breaks a lot of backward compatibility with the previous version, in order to be more flexible with the rapidly evolving API. YOU WILL HAVE TO MAKE CHANGES TO YOUR CODE WHEN YOU UPGRADE.

Usage:

###EZAppDotNet If you are planning to design an app for viewing within a browser that requires a login screen etc, this is a great place to start. This aims to hide all the nasty authentication stuff from the average developer. It is also recommended that you start here if you have never worked with OAuth and/or APIs before.

<?php

require_once 'EZAppDotNet.php';

$app = new EZAppDotNet();

// check that the user is signed in
if ($app->getSession()) {

    // post on behalf of the user
    $app->createPost('Hello world');

    // get the current user as JSON
    $data = $app->getUser();

    // accessing the user's username
    echo 'Welcome '.$data['username'];

// if not, redirect to sign in
} else {

    $url = $app->getAuthUrl();
    header('Location: '.$url);

}

?>

To view a full example in action, you should copy the project files into your webroot directory. Edit the values in EZsettings.php to reflect the ones for your app (to make things easy, change the Callback URL within your app.net developers console to http://localhost/ez-example/callback.php). Add or remove values from the $app_scope array to change the permissions your app will have with the authenticated user. Travel to http://localhost/ez-example/ and click 'Sign in with App.net'.

###AppDotNet Use this class if you need more control of your application (such as running a command line process) or are integrating your code with an existing application that handles sessions/cookies in a different way.

First construct your authentication url.

<?php

require_once 'AppDotNet.php';

// change these to your app's values
$clientId     = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$clientSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

// construct the AppDotNet object
$app = new AppDotNet($clientId,$clientSecret);

$redirectUri  = 'http://localhost/callback.php';
$scope        =  array('stream','email','write_post','follow','messages','update_profile','files','export');

// create an authentication Url
$url = $app->getAuthUrl($redirectUri,$scope);

?>

Once the user has authenticated the app, grab the token in the callback script, and get information about the user.

<?php
require_once 'AppDotNet.php';
$app = new AppDotNet($clientId,$clientSecret);

// get the token returned by App.net
// (this also sets the token)
$token = $app->getAccessToken($redirectUri);

// get info about the user
$user = $app->getUser();

// get the unique user id
$userId = $user['id'];

?>

Save the token and user id in a database or elsewhere, then make API calls in future scripts after setting the token.

<?php

$app->setAccessToken($token);

// post on behalf of the user w/ that token
$app->createPost('Hello world');

?>

To consume the stream, try something like:

<?php

require_once 'AppDotNet.php';
$app = new AppDotNet($clientId,$clientSecret);

// You need an app token to consume the stream, get the token returned by App.net
// (this also sets the token)
$token = $app->getAppAccessToken();

// create a stream
// if you already have a stream you can skip this step
// this stream is going to consume posts and stars (but not follows)
$stream = $app->createStream(array('post','star','user_follow','stream_marker','message','channel','channel_subscription','mute','token','file'));
// you might want to save $stream['endpoint'] or $stream['id'] for later so
// you don't have to re-create the stream

// we need to create a callback function that will do something with posts/stars
// when they're received from the stream. This function should accept one single
// parameter that will be the php object containing the meta / data for the event.
function handleEvent($event) {
	switch ($event['meta']['type']) {
		case 'post':
			print "Handle a post type\n";
			break;
		case 'star':
			print "Handle a star type\n";
			break;
	}
}

// register that function as the stream handler
$app->registerStreamFunction('handleEvent');

// open the stream for reading
$app->openStream($stream['endpoint']);

// now we want to process the stream. We have two options. If all we're doing
// in this script is processing the stream, we can just call:
// $app->processStreamForever();
// otherwise you can create a loop, and call $app->processStream($milliseconds)
// intermittently, like:
while (true) {
	print "hello, I'm going to do some other non-streaming things here...\n";
	// now we're going to process the stream for awhile (3 seconds)
	$app->processStream(3000000);
	// then do something else...
}
?>

Copyright (c) 2013, Josh Dolitsky All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Josh Dolitsky nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TRAVIS RICHARDSON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

appdotnetphp's People

Contributors

33mhz avatar berg avatar cdn avatar charlw avatar jdolitsky avatar martinstuecklschwaiger avatar neuroscr avatar ravisorg avatar wpstudio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

appdotnetphp's Issues

Undefined variables

Was getting errors
Notice: Undefined variable: redirectUri in /EZAppDotNet.php on line 48

Notice: Undefined variable: scope in /EZAppDotNet.php on line 48

Here's the diff, not sure of the best way to submit it

$ diff AppDotNet.php ~/git/AppDotNetPHP/AppDotNet.php 
79d78
< global $app_redirectUri;
89c88
<               'redirect_uri'=>$app_redirectUri,

---
>               'redirect_uri'=>$this->_redirectUri,

$ diff EZAppDotNet.php ~/git/AppDotNetPHP/EZAppDotNet.php 
34c34
<       global $app_redirectUri,$app_scope;

---
> 
48c48
<       parent::__construct($clientId,$clientSecret,$app_redirectUri,$app_scope);

---
>       parent::__construct($clientId,$clientSecret,$redirectUri,$scope);
60c60
<       return parent::getAuthUrl($redirectUri);

---
>       return parent::getAuthUrl();

Error handling in getAccessToken()

Currently, getAccessToken() assumes that the call to access_token always returns a valid token. However, if the code has expired, has been used before, is incorrect or in a range of other cases, an error is returned instead.

Auth not working

I'm following the instructions in the readme for AppDotNet.php auth. The first part works fine. But when I approve the app and it returns to my callback URL, $_GET['code'] is set but both $token and $user are NULL.

Mute / Unmute / Muted

I thought that you had added these... anyway I hacked these together but I am getting inconsistent results with Unmute... maybe it needs curl magic.

Cheers

// Mute user
function muteUser($user_id=null) {
    return $this->httpPost($this->_baseUrl.'users/'.$user_id.'/mute');
}   

//Unmute user
function unmuteUser($user_id=null) {
    return $this->httpDelete($this->_baseUrl.'users/'.$user_id.'/unmute');
}       

//List Muted
// Returns an array of User objects for users following the specified user.
function getMuted($user_id='me',$count=20,$before_id=null,$since_id=null) {
    return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/muted?count='.$count.'&before_id='.$before_id.'&since_id='.$since_id);
}

Cookies, Sessions ...

Hey guys,

I know there have been some exchanges on this but what can we do to implement solid cookie session setting support into the library directly? Before I go off and try to hack something together maybe better expertise can do it and help make it standard for apps using this lib.

Cheers,

Harold

new api functionality

//todo describe
public function getUserUnifiedStream($params = array()) {
    return $this->httpReq('get',$this->_baseUrl.'posts/stream/unified?'.$this->buildQueryString($params));
}


//todo describe
public function interactions($params = array()) {
    return $this->httpReq('get',$this->_baseUrl.'users/me/interactions?'.$this->buildQueryString($params));
}   

RateLimits and Scope

The getRateLimitRemaining() and associated functions don't seem to work.
Also need to add getScope.

createChannel - $pm not declared and is not necessary

The $pm variable is not declared in this scope, and given that the function may not be used to create a PM channel, the ternary clause is unnecessary.

return $this->httpReq('post',$this->_baseUrl.'channels'.($pm?'/pm/messsages':''), $json, 'application/json');

With this version, however:

return $this->httpReq('post',$this->_baseUrl.'channels', $json, 'application/json');

with this data object:

{"type":"ca.roaringsky.group","writers":{"immutable":"0","public":"0","user_ids":"10403","73417"]}}

the call fails to complete. Suggestions?

404 on unfollowUser ?

Follow seems to be working but unfollowUser is throwing 404 errors most of the time.. but sometimes I think it gets though. The url and user id(s) look ok.

setSession() ?

I'm using some of the basic code on the readme as well as the core appdotnet.php files.

It keeps going through a redirect loop. It looks as though the function setSession is never actually called, however. So the cookies don't get set and thus the loop is created. I'll see if I can fix this and put in a PR.

Handled URLs on Post

May or may not be an issue with urls getting cut off, maybe not...

getSession()) { $app -> createPost('This is a test message with a url http://appeio,com?v=post&p=555',null); } ?>

Lib changes

Hi,

I am right now going to learn how to properly do a pull request so I can do this properly but in case I fail..

I've been trying to get back in line with AppDotNetPHP proper before the Streaming stuff but I've made a couple of small changes since last syncing up.

Mostly I added two functions:

getId, which is an API supported way to get an ID (user object) when you only know the username.

getTokenStream, this is a way to pass in a token other than the authed users to get a different stream.

This was in order to make @teawithcarls "View Accounts" work with Appeio. In order to get this to work I also had to changed httpReq slightly. I realize this is a bit specific but not too bad..

I think that's the only diffs.

Trying out SmartGit and some other softwares.

Stream stops providing data after ADN server responds with keep-alive

I'm opening a stream using the ConsumeStream functions, however as soon as it goes 'quiet', i.e. no data is coming through, ADN servers respond every 60 seconds with:

HTTP/1.1 200 OKServer: nginx/1.2.6Date: Mon, 11 Mar 2013 21:29:27 GMTContent-Type: text/html; charset=UTF-8Transfer-Encoding: chunkedConnection: keep-alive

As soon as the class receives this, no new data will come through. I can see ADN objects coming through previous to this message, and can post them myself, but they instantly stop as soon as the keep-alive arrives.

How can we fix this issue?

Following / Followers pagination

So I was trying to get Following / Follower pagination working but I think I am confused on how the migration works.

  1. How do I enable the migration(s) .. an example?

  2. The lib needs this update (I think..) (parms)

    /**

    • Returns an array of User objects the specified user is following.
    • @param mixed $user_id Either the ID of the user being followed, or
    • the string "me", which will retrieve posts for the user you're authenticated
    • as.
    • @return array An array of associative arrays, each representing a single
    • user following $user_id
      */
      public function getFollowing($user_id='me',$params = array()) {
      return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/following?'.$this->buildQueryString($params));
      }

    /**

    • Returns an array of User objects for users following the specified user.
    • @param mixed $user_id Either the ID of the user being followed, or
    • the string "me", which will retrieve posts for the user you're authenticated
    • as.
    • @return array An array of associative arrays, each representing a single
    • user following $user_id
      */
      public function getFollowers($user_id='me',$params = array()) {
      return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/followers?'.$this->buildQueryString($params));
      }

It's full of stars

/**
 * Star a post
 * @param integer $post_id The post ID to star
 */
public function starPost($post_id=null) {
    return $this->httpPost($this->_baseUrl.'posts/'.urlencode($post_id).'/star');
}   

/**
 * Unstar a post
 * @param integer $post_id The user ID to unstar
 */
public function unstarPost($post_id=null) {
    return $this->httpDelete($this->_baseUrl.'posts/'.urlencode($post_id).'/star');
}       

/**
 * List the posts started by the current user
 * @return array An array of associative arrays, each representing one starred post.
 */
public function getStarred($user_id=null) {
    return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/stars');
}   

getPost working?

Hi,

Can you or anyone confirm that getPost works? I get an internal error?

I'll send you in my changes to AppDotNetPHP asap. It's a bit of a mess right now.

Smarter function calls

Thinking about this. Maybe AppDotNet class should be straight dumb calls and EZ should a smarter wrapper that makes the API easier to deal with. This would give the advantage if you already knew/want to the learn the ADN API you can use straight AppDotNet and anything specific to our upgrade would be in EZ.

This would revert the change to getFile and getFiles to make them 2 different web calls but then EZ would have a function that takes one or more IDs and be smarted enough to make the appropriate backend call.

Set user's username [suggestion]

It would be great if the user's username was set (either in GLOBAL, _SESSION, or in the cookie).

That makes it easier to spot if a post is a reply, can be deleted, etc.

Move scope to settings

At the moment, the default scope is to get everything

$scope=array('stream','email','write_post','follow','messages','export')) {

I don't disagree with that, but I think it should be moved into EZsettings, so that developers don't overlook it. I've already been burned by someone complaining that I wanted their email.

Whitespace 2 space vs tab?

any one have any problems with me converting the files over to using 2 space for indentation instead of tabs?

Return data from createFile() appears to be getting lost.

$ok = $app->createFile($file, array('metadata' => 'file.type'); leaves me with nothing in $ok

$ok2 = $app->getLastResponse(); called afterwards clearly shows expected return data with file id and token.

Has anyone else seen this?

Posting to app.net

Hi,

Can you show a working example for posting a new message / reply to app.net? I have tried.. but have only gotten 401 unauthorized back. I think I am missing something as I can read streams and login. http://appeio.com

Cheers,
Harold

Extended Post options

Any plans to update the lib to support passing the new @mentions flag and the other post options not implemented? I can do it but if someone else can that's good too. Thinking there will be a few API updates this week.

What is the license of this code?

Is this code published under a free license? Which license is it?

Would love to re-use the code but would need at least a BSD compatible license to do so.

Err in getFollowers

Line 412: missing a ? mark.

return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/followers'.http_build_query($params));

should be

return $this->httpGet($this->_baseUrl.'users/'.$user_id.'/followers?'.http_build_query($params));

UserID from Username?

Is there currently an API method I am not seeing or undocumented that makes it available to get a User ID from the Username? I don't really want to expose the id for internal app links.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.