ラベル facebook の投稿を表示しています。 すべての投稿を表示
ラベル facebook の投稿を表示しています。 すべての投稿を表示

2013年3月20日水曜日

phonegap-facebook-plugin



















phoneGap 2.5 
+ phonegap-facebook-plugin + facebook SDK3.2 Xcode 4.6.1 iOS(phoneGap)で facebook の
javascript SDKを動かす 




まず、phoneGapをインストールして
コマンドラインより、Xcode の
プロジェクトを作成 作成したプロジェクトを実行してみる






ダウロードした phoneGap の zip ファイルを解凍し、
解凍したディレクトリに移動して create を実行
$ cd phonegap-2.5.0/
$ ./lib/ios/bin/create ./HelloFBjs HelloFBjs HelloFBjs



作成された project を Xcode で開き、
実行してエラーがないことを確認
一部、警告が表示されるが 表示部分をコメントアウトして
config.xml に同等の内容を追記













































appId を設定し fql も動作OK

           document.addEventListener('deviceready', function() {
                                      try {
                                      alert('Device is ready! Make sure you set your app_id below this alert.');
                                      FB.init({ appId: "XXXXX", nativeInterface: CDV.FB, useCachedDialogs: false });
                                      document.getElementById('data').innerHTML = "";
                                      } catch (e) {
                                      alert(e);
                                      }
                                      }, false);



   *     FB.login(function(response) {
   *       if (response.authResponse) {
   *         // if you need to know which permissions were granted then
   *         // you can can make an fql-call
   *         FB.api({
   *                  method: 'fql.query',
   *                  query: 'select read_stream, publish_stream, ' +
   *                    'offline_access from permissions where uid=me()'
   *                },
   *                function (data) {
   *                  if (data[0].read_stream) {
   *                    // we have read_stream
   *                  }
   *                });
   *       } else {
   *         // user is not logged in
   *       }
   *     }, {scope:'read_stream, publish_stream, offline_access'});

2011年12月3日土曜日

Post facebook photo by Command line

access_token に対応したfacebook application名のアルバムに保存される
公開するためには手動で承認作業が必要。
 

fb_image_upload.sh

#!/bin/bash

if [ "$#" -eq 0 ];then
 echo "Do not get image. "
 else
 echo " Get image. "$1
 /opt/local/bin/python2.5 get_image.py $1
fi

msg="test"
caption="message="$msg""
token=`cat .fb_access_token`
echo $caption
echo $token

echo `curl -F "access_token="$token"" -F "source=@"dummy.jpg"" -F "$caption" https://graph.facebook.com/me/photos`

alubm ID によりアルバムを指定して post することもできるが、この場合も公開には承認作業が必要。
echo `curl -F "access_token="$token"" -F "source=@"dummy.jpg"" -F "$caption" https://graph.facebook.com/10150411507966880/photos`
 

アプリケーションで自動作成されるアルバムには1000枚まで写真が保存できるみたいです。

https://graph.facebook.com/ALBUM_ID/photos - The photo will be published to a specific, existing photo album, represented by the ALBUM_ID. Regular albums have a size limit of 200 photos. Default application albums have a size limit of 1000 photos.

https://developers.facebook.com/docs/reference/api/photo/

 

関連
画像の取得 get_image.py

#!-*- coding:utf-8 -*-
#!/opt/local/bin/python2.5

import sys
import urllib
import httplib
import cStringIO
import ImageFile
from PIL import Image, ImageDraw, ImageFont
import string
import re

url = "http://xxx/xxx.jpg"
file = urllib.urlopen(url)
try:
  size = file.headers.get("content-length")
  print "size:" + size
  im = cStringIO.StringIO(file.read())
  img = Image.open(im)

except:
  print "Error: Url = " + url

img_type = "jpg"
img_file = url
if img_file[-3:] == "PNG" or img_file[-3:] == "png":
  img_type = "png"
  img.save("dummy."+ img_type,"PNG")
elif img_file[-3:] == "GIF" or img_file[-3:] == "gif":
  img_type = "gif"
  img.save("dummy."+ img_type,"GIF")
else:
  img.save("dummy."+ img_type,"JPEG")

Get facebook albums by commad line

ポイント
  1. GAEで利用する python2.5 でなくpython2.6以上を利用
    json や urlparse.parse_qs でエラーとなる
    AttributeError: 'module' object has no attribute 'parse_qs'
  2. 'scope':'read_stream,user_photos'
  3. 1度で20件づつしか取得できないので paging が必要となる
    また、先頭の1行のデータは重複する(?)。
  4. http://127.0.0.1:8080/ を登録
     

  5. token が expire している場合は以下のエラーとなるため
    urllib2.HTTPError: HTTP Error 400: Bad Request
    $ rm .fb_access_token

参考
https://sites.google.com/site/benersuayen/lab/facebook     

 

fb_albums.py

#!-*- coding:utf-8 -*-
#!/opt/local/bin/python2.7
import os.path
import json
import urllib2
import urllib
import urlparse
import BaseHTTPServer
import webbrowser

APP_ID = 'XXX'
APP_SECRET = 'XXX'
ENDPOINT = 'graph.facebook.com'
REDIRECT_URI = 'http://127.0.0.1:8080/'
ACCESS_TOKEN = None
LOCAL_FILE = '.fb_access_token'

def get_url(path, args=None):
    args = args or {}
    if ACCESS_TOKEN:
        args['access_token'] = ACCESS_TOKEN
    if 'access_token' in args or 'client_secret' in args:
        endpoint = "https://"+ENDPOINT
    else:
        endpoint = "http://"+ENDPOINT
    return endpoint+path+'?'+urllib.urlencode(args)

def get(path, args=None):
    return urllib2.urlopen(get_url(path, args=args)).read()

def do_next(next,last_id):
    count = 0
    for item in json.loads(get(next))['data']:
        if last_id <> item['id'].encode('utf-8'):
            print "%s, %s" % ( item['id'].encode('utf-8') ,item['name'].encode('utf-8') )
            count = count + 1
    print '---'
    last_id = item['id'].encode('utf-8')
    next = json.loads(get(next))['paging']['next']
    next = next.replace("https://graph.facebook.com/me/albums","/me/albums")
    if next and count > 0:
        do_next(next,last_id)

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        global ACCESS_TOKEN
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        code = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('code')
        code = code[0] if code else None
        if code is None:
            self.wfile.write("Sorry, authentication failed.")
            sys.exit(1)
        response = get('/oauth/access_token', {'client_id':APP_ID,
                                               'redirect_uri':REDIRECT_URI,
                                               'client_secret':APP_SECRET,
                                               'code':code})
        ACCESS_TOKEN = urlparse.parse_qs(response)['access_token'][0]
        open(LOCAL_FILE,'w').write(ACCESS_TOKEN)
        self.wfile.write("You have successfully logged in to facebook. "
                         "You can close this window now.")

if __name__ == '__main__':
    if not os.path.exists(LOCAL_FILE):
        print "Logging you in to facebook..."
        webbrowser.open(get_url('/oauth/authorize',
                                {'client_id':APP_ID,
                                 'redirect_uri':REDIRECT_URI,
                                 'scope':'read_stream,user_photos'}))

        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
    else:
        ACCESS_TOKEN = open(LOCAL_FILE).read()
#    for item in json.loads(get('/me/feed'))['data']:
#        if item['type'] == 'status':
#            print item['from']['name'].encode('utf-8')
#            print item['message'].encode('utf-8')
#            if 'comments' in item:
#                for comment in item['comments']['data']:
#                  print comment['from']['name'].encode('utf-8')
#                 print comment['message'].encode('utf-8')
#            print '---'

#   for item in json.loads(get('/me/friends'))['data']:
    for item in json.loads(get('/me/albums'))['data']:
        print "%s, %s" % ( item['id'].encode('utf-8') ,item['name'].encode('utf-8') )
    last_id = item['id'].encode('utf-8')
    print '---'
    next = json.loads(get('/me/albums'))['paging']['next']
    prev = json.loads(get('/me/albums'))['paging']['previous']
#   print  prev
    print  next
    next = next.replace("https://graph.facebook.com/me/albums","/me/albums")
    if next:
        do_next(next,last_id)

Unityでドアの開閉はAnimatorそれともiTween?

Mac Mini M2 の Unity で Sketchup のデータを復元したつづき。 以前、苦労して作成したドアの開閉が動作しないので修復する。 どうやって動かしていたのか、また忘れそうなので記録しておく。             Animator 左右のドア PlaneL,...