Youtube api v3で動画サイトを試作してみた。。

下記コードは、Jsonの取得のところまで。

<?php

require_once('vendor/autoload.php');

$client_id = '';
$service_account_name = '';
$key_file_location = '';

$client = new Google_Client();
$client->setApplicationName('Yutube Test');
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
	$service_account_name,
	array('https://www.googleapis.com/auth/youtube'),
	$key
);
$client->setAssertionCredentials($cred);

$youtube = new Google_Service_YouTube($client);

$array = array('viewCount','rating','date');

$query = 'X Japan';
$searchResponse = $youtube->search->listSearch('id,snippet',array(
	'q' => $query,
	'maxResults'=> 10,
	'order' => $array[0]
));

こちらがviewです。検索やソート順など、改良の余地が大いにありますね。

OAuthとは

OAuthは認可情報の委譲のための仕様
-あらかじめ信頼関係を構築したサービス間で、ユーザの同意のもとに、セキュアにユーザの権限を受け渡しする
※自分が利用したいサービスに最低限必要な権限のみを委譲することができる。そのため、basic認証と比べて柔軟かつセキュアな運用が可能

認可情報の委譲を行う仕様には、Google、Yahoo!、Flickr、Facebookなどが独自に提供しているものが

OAuth Service Provider(Google, Yahoo, Twitter)
OAuth Consumer
Users

[vagrant@localhost api]$ php composer.phar
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.6.2 2018-01-05 15:28:41

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                Shows the short information about Composer.
  archive              Creates an archive of this composer package.
  browse               Opens the package's repository URL or homepage in your browser.
  check-platform-reqs  Check that platform requirements are satisfied.
  clear-cache          Clears composer's internal package cache.
  clearcache           Clears composer's internal package cache.
  config               Sets config options.
  create-project       Creates new project from a package into given directory.
  depends              Shows which packages cause the given package to be installed.
  diagnose             Diagnoses the system to identify common errors.
  dump-autoload        Dumps the autoloader.
  dumpautoload         Dumps the autoloader.
  exec                 Executes a vendored binary/script.
  global               Allows running commands in the global composer dir ($COMPOSER_HOME).
  help                 Displays help for a command
  home                 Opens the package's repository URL or homepage in your browser.
  info                 Shows information about packages.
  init                 Creates a basic composer.json file in current directory.
  install              Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.
  licenses             Shows information about licenses of dependencies.
  list                 Lists commands
  outdated             Shows a list of installed packages that have updates available, including their latest version.
  prohibits            Shows which packages prevent the given package from being installed.
  remove               Removes a package from the require or require-dev.
  require              Adds required packages to your composer.json and installs them.
  run-script           Runs the scripts defined in composer.json.
  search               Searches for packages.
  self-update          Updates composer.phar to the latest version.
  selfupdate           Updates composer.phar to the latest version.
  show                 Shows information about packages.
  status               Shows a list of locally modified packages.
  suggests             Shows package suggestions.
  update               Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  upgrade              Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  validate             Validates a composer.json and composer.lock.
  why                  Shows which packages cause the given package to be installed.
  why-not              Shows which packages prevent the given package from being installed.

最新のgoogle-api-php-client

まず、コマンドラインでphpのバージョンを確認します。

[vagrant@localhost api]$ php -v
PHP 5.6.27 (cli) (built: Oct 14 2016 14:06:54)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

gitも確認。

[vagrant@localhost api]$ git version
git version 2.2.1

githubにあるリポジトリをローカルにcloneします。

[vagrant@localhost api]$ git clone https://github.com/google/google-api-php-client.git
Cloning into 'google-api-php-client'...
remote: Counting objects: 10177, done.
remote: Compressing objects: 100% (16/16), done.
remote: Total 10177 (delta 3), reused 8 (delta 2), pack-reused 10158
Receiving objects: 100% (10177/10177), 6.98 MiB | 1.51 MiB/s, done.
Resolving deltas: 100% (6953/6953), done.
Checking connectivity... done.

入りました。

では、試しに、examplesをサーバーで見てみましょう。

[vagrant@localhost google-api-php-client]$ php -S 192.168.33.10:8000
PHP 5.6.27 Development Server started at Mon Jan 29 16:12:27 2018
Listening on http://192.168.33.10:8000
Document root is /home/vagrant/api/google-api-php-client
Press Ctrl-C to quit.
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59098 [200]: /examples/
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59099 [200]: /examples/styles/style.css
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59101 [404]: /favicon.ico - No such file   or directory
[Mon Jan 29 16:12:47 2018] 192.168.33.1:59100 Invalid request (Unexpected EOF)

Google API Client Librariesとは?

API Client Libraries offers simple, flexible, powerful access to many Google APIs.

Setup
1. sign up Google account
2. create a project in the Google API Console
3. Install the library

google-api-php-client
https://github.com/google/google-api-php-client

Authentication and authorization
All API calls must use either simple or authorized access.
API Key: to authenticate your application, use API Key for your Google API Console.

Authorized API access(OAuth 2.0)
your application must be authenticated, the user must grant access for your application, and the user must be authenticated in order to grant that access.
scope: each api defines one or more scopes that declare a set of operations permitted.
Refresh and access tokens: when a user grants your application access, the OAuth 2.0 authorization server provides your application with refresh and access tokens.
Client ID and client secret: these strings uniquely identify your application and are used to acquire tokens.

Build the client object

$client = new Google_Client();
$client->setApplicationName("My Application")
$client->setDeveloperKey("My_SIMPLE_API_KEY")

Build the service object
services are called through queries to service specific objects. These are created by constructing the service object, and passing an instance of Google_Client to it.

$service = new Google_Service_Books($client);

Calling an API
each API provides resources and methods, usually in chain. These can be accessed from the service object in the form $service->resource->method(args). Most method require some arguments, then accept a final parameter of an array containing optional parameters.

$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoeau', $optParams);

Handling the result
There are two main types of response – items and collections of items. Each can be accessed either as an object or as an array.

foreach($results as $item){
	echo $item['volumeInfo']['title'], "<br />\n";
}

Google Cast

Streaming media

Google Cast
-multi device
-android, ios, web

Android TV
-extended android app
-runs on TV

Platform
android -> android TV

Android TV platform
1.declare the TV activity in the manifest
2.Update UI with the leanback library
-BrowseFragment
-DetailsFragment
-SearchFragment
3.Content discovery
-Apps/Games row
-Recomendations
-Search

https://developers.google.com/cast/docs/developers

Getting started
https://cast.google.com/publish/

Google app engine

Set Up Development Environment
Editor – Sublime Text

Python 2.7 – check your version by running python -V and if it’s not 2.7.

Git – download git from it’s official site.

SDK – download and install Google App Engine SDK for Python
https://cloud.google.com/appengine/downloads

def sumUp(n):
	total = 0
	for x in range(n):
		total += x
	return total
sumUp = timer.timedFunction(sumUp)
import endpoints
from protorpc import message
from protorpc import message_types
from protorpc import remote

REQUEST_CONTAINER = endpoints.ResourceContainer(
	message_types.VoidMessage,
	name=messages.StringField(1),
)

package = 'Hello'

class Hello(messages.Message):
	"""String that stores a message."""
	greeting = messages.StringField(1)

@endpoints.api(name='helloworldendpoints', version='v1')
class HelloWorldApi(remote.Service):
	"""Helloworld API v1."""

	@endpoints.method(message_types.VoidMessage, Hello,
		path = "sayHello", http_method='GET', name = "sayHello")
	def say_hello(self, request):
		return Hello(greeting="Hello World")

	@endpoints.method(REQUEST_CONTAINER, Hello,
		path = "sayHelloByName", http_method='GET', name = "sayHelloByName")
	def say_hello_by_name(self, request):
		greet = "Hello {}".format(request.name)
		return Hello(greeting=greet)

APPLICATION = endpoints.api_server([HelloWorldApi])

Field Classes
https://cloud.google.com/appengine/docs/python/tools/protorpc/messages/fieldclasses

API Explore
https://developers.google.com/apis-explorer/#p/

translate api

{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt"
      },
      {
        "translatedText": "Mein Name ist Jeff"
      }
    ]
  }
}
from google.appengine.ext import ndb

class Recipe(ndb.Model):
	name = StringProperty()
	ingredients = StringProperty(repeated=True)
	instructions = TextProperty()
	vegetarian = BooleanProperty()
	servings = IntegerProperty()

google map api

https://developers.google.com/maps/documentation/geocoding/get-api-key

import httplib2
import json

def getGeocodeLocation(inputString):
	google_api_key = "your_key"
	locationString = inputString.replace(" ", "+")
	url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (
		locationString, google_api_key))
	h = httplib2.Http()
	response, content = h.request(url, 'GET')
	result = json.loads(content)

	latitude = result['result'][0]['geometry']['location']['lat']
	longitude = result['result'][0]['geometry']['location']['lng']
	return(latitude,longitude)

flask

from flask import Flask
app = Flask(__name__)

def puppyFunction():
	return "Yes, puppies!"

def puppiesFunction(id)
	return "This method will act on the puppy with id %s" % id

if __name__ == '__main__':
	app.debug = True
	app.run(host='0.0.0.0', port=5000)
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from passlib.apps import custom_app_context as pwd_context

Base = declarative_base()

class User(Base):
	__tablename__ = 'user'
	id = Column(Integer, primary_key=True)
	username = Column(String(32), index=True)
	password_hash = Column(String(64))

engine = create_engine('sqlite:///users.db')