I'm trying to figure out how to add a task using the Google tasks API. The docs leave a lot to investigate and I seen to be stuck. This is my code:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Tasks($client);
...
... get token etc...
...
// Create a task
$task = new Google_Service_Tasks_Task();
$task->setTitle("Call mum");
$task->setNotes("Inserted by app");
$task->setStatus("needsAction");
$task->setDue(new DateTime('2020-01-01T00:00:01.000Z'));
// constructor needs 4 params: service, serviceName, resourceName, resource
$res = new Google_Service_Tasks_Resource_Tasks('', '', '', '');
$res->insert($lastListID, $task);
When creating the new Google_Service_Tasks_Resource_Tasks (second-last line) I need to provide 4 parameters to the constructor: service, serviceName, resourceName, resource.
I cant find any docs explaining the last three params. I use this class because it has an insert method and I think that's the one I need. The examples all stop at listing the tasks (works).
I tried making sense of these docs:
https://developers.google.com/tasks/v1/reference/tasks/insert
https://developers.google.com/resources/api-libraries/documentation/tasks/v1/php/latest/index.html
I couldn't make sense of the actual classes in my vendor dir.
Does anyone know how to tame this API?
I understand that you want to create a task using the PHP Tasks API. Your approach is correct, you only need to use the constructor with three parameters instead of four. As we can see on the Google_Service_Tasks_Resource_Tasks documentation, the insert operation is defined as:
/**
* Creates a new task on the specified task list. (tasks.insert)
*
* #param string $tasklist Task list identifier.
* #param Google_Service_Tasks_Task $postBody
* #param array $optParams Optional parameters.
*
* #opt_param string parent Parent task identifier. If the task is created at
* the top level, this parameter is omitted. Optional.
* #opt_param string previous Previous sibling task identifier. If the task is
* created at the first position among its siblings, this parameter is omitted.
* Optional.
* #return Google_Service_Tasks_Task
*/
public function insert($tasklist, Google_Service_Tasks_Task $postBody, $optParams = array())
{
$params = array('tasklist' => $tasklist, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Tasks_Task");
}
That comment define the three parameters as:
Task list identifier. This is the id of the task list as defined on its resource.
Content of the task object to be created, like the one on your code.
Optional object containing two elements:
Parent task identifier. This element is called id on the resource documentation. If the task has no parent task, this parameter can be omitted.
Previous sibling task. This element is the same as the previous point, but makes reference to the previous element of the list. If the new element will be the first one between its sibling (or it will be the only one) this parameter can be omitted.
A working example, based on the variables of your code, will be:
$optParams = array("{PARENT TASK ID}", "{PREVIOUS TASK ID}");
$res = new Google_Service_Tasks_Resource_Tasks();
$res->insert($taskListID, $task, $optParams);
With this method you can create a task using your approach. Please, do not hesitate to ask for further clarification if you have any questions.
Related
For context:
I am setting up a PubSub Emitter for snowplow. (For other readers PubSub is a simple queue on Google Cloud Platforms that takes in messages which are an array as input).
['data' => 'Name', 'attributes' => 'key pair values of whatever data you are sending']
The above is irrelevant except that I must create a custom Emitter class in order to achieve this goal since Google Cloud PubSub has some different connectors than the stereotypical http request/sockets/others that snowplow provides.
Actual problem:
I want to set a specific schema for each event I am sending. How do you associate the schema to each payload?
The PHP Tracker SyncEmitter (the most standard snowplow provided Emitter) doesn't allow any custom setting for the schema (as shown below)
private function getPostRequest($buffer) {
$data = array("schema" => self::POST_REQ_SCEHMA, "data" => $buffer);
return $data;
}
It is hardcoded in to every event tracked.
So I investigated. And read up on snowplow trackers a bit more. I am still baffled, and I know I can extend the Payload class and force my own schemas as a variable, but why is it not this way already? I am asking because I am assuming the opensource programmer did it right, and I am not understanding it correctly.
I figured it out.
The Tracker class contains trackUnstructuredEvent:
/**
* Tracks an unstructured event with the aforementioned metrics
*
* #param array $event_json - The properties of the event. Has two fields:
* - A "data" field containing the event properties and
* - A "schema" field identifying the schema against which the data is validated
* #param array|null $context - Event Context
* #param int|null $tstamp - Event Timestamp
*/
public function trackUnstructEvent($event_json, $context = NULL, $tstamp = NULL) {
$envelope = array("schema" => self::UNSTRUCT_EVENT_SCHEMA, "data" => $event_json);
$ep = new Payload($tstamp);
$ep->add("e", "ue");
$ep->addJson($envelope, $this->encode_base64, "ue_px", "ue_pr");
$this->track($ep, $context);
}
Which accepts the schema as input. Snowplow wants you to use the Tracker's default function and provided the above as a solution to my issue.
But it still has a schema wrapped around the data(that contains the input schema).... More questions from my own answer...
I basically want to do this: Add custom field to Laravel queued job records?
However the top-voted answer there doesn't really address how to do this, rather it advocates for a work-around.
I know in order to actually accomplish this I need to tap into the dispatch function. The issue is it isn't being called directly in my (in this case) event listener.
According to this and this dispatch is a global helper function. Where in the source code is this registered and how should I overwrite it in my event listener in order to run handle() (that which dispatch itself calls) in my Job class after a specified delay and yet be able to add additional entries/fields to the database?
My prime reason for this is because:
1). The job is sending a notificaiton via email.
2). Emails should only go out after a delay IF the user hasn't logged in/been active during that delay.
3). AND emails should only go out if that user doesn't have another email queued up since the first was dispatched, in which case the first should be consolidated and deleted into the second email.
Therefore I need additional database fields in order to find, delete and modify entries in the jobs table.
These ideas come from an article on Medium which teaches that you don't want to spam users with emails/notifications and you need to consolidate/group/prioritize them and I'm trying to do this in Laravel.
I believe it is possible in Laravel but I am unsure how to overwrite the functionality when dispatch is a global and I don't know from where it is invoked. The Laravel docs on the Command Bus don't go beyond Laravel 5.0.
Edit: I have to use Redis now, according to this (because I am getting that beginTransaction() error in my queue):
Redis Driver > Database Driver
I think a model watcher would be best but I'm not sure if Job is an Eloquent model. I need something that will work consistently across database drivers.
When you create a job instance everything assigned to a public property is serialized and thereafter available to you during the job processing. You can pass in parameters to the job constructor and then assign them to properties like
public $foo;
public function __constructor($bar) {
$this->foo = $bar;
}
Then in the handle function you can get the value $bar from $this->foo
Edit: If found this method within the DatabaseQueue class. Perhaps you could override to suit your needs:
/**
* Create an array to insert for the given job.
*
* #param string|null $queue
* #param string $payload
* #param int $availableAt
* #param int $attempts
* #return array
*/
protected function buildDatabaseRecord($queue, $payload, $availableAt, $attempts = 0)
{
return [
'queue' => $queue,
'attempts' => $attempts,
'reserved_at' => null,
'available_at' => $availableAt,
'created_at' => $this->currentTime(),
'payload' => $payload,
];
}
I'm feeling like this is an idiotic mistake on my part, but I can't figure out how to use the google-api-php-client to do a simple search. My goal is to run simple keyword queries against a google search engine for my site.
I've created my api key, a google search engine and downloaded a release of the api client, but the google site for the php client doesn't seem to have any documentation on how to use the client and the only related example I've found so far specifically searches google's book service. The problem is that example implies that different search services have different search result types and I can't find any documentation on how to retrieve results from a Google_Service.
I think I can set up a simple search like this, but I don't know how to actually retrieve the results.
include_once __DIR__ . '/vendor/autoload.php';
...
public function __construct($searchTerm) {
$client = new Google_Client();
$client->setApplicationName("My_First_Search");
$client->setDeveloperKey(self::GCSE_API_KEY);
$service = new Google_Service($client);
$optParams = array('filter' => $searchTerm);
$results = $service->???
The documentation must be out there, but it's not in any of the obvious places....
Update (1/14/17):
(Update 1/21/17: actually, these docs didn't help me much, but I'll leave them up just FYI)
I used phpdoc to generate api documentation for the google apiclient. I made a repo and put the phpdocs and the libary on github. The phpdocs are browsable here.
So hopefully that will be helpful to someone. Unfortunately even with the docs I'm having trouble unraveling proper usage. I haven't generated docs for the google apiclient-services package yet because they are huge, but I can do that if necessary (depending on disk limits on github pages).
Thanks to #gennadiy for putting me on the right track. Without his suggestion to use ->cse->listCse() to retrieve the results, I probably would have given up and gone in search of a different library. Luckily this is pretty much all I need to use this library for so I think I'm all set.
Simple Example
Executing a search is pretty simple; it basically looks like this:
include_once __DIR__ . '/vendor/autoload.php';
$GCSE_API_KEY = "nqwkoigrhe893utnih_gibberish_q2ihrgu9qjnr";
$GCSE_SEARCH_ENGINE_ID = "937592689593725455:msi299dkne4de";
$client = new Google_Client();
$client->setApplicationName("My_App");
$client->setDeveloperKey($GCSE_API_KEY);
$service = new Google_Service_Customsearch($client);
$optParams = array("cx"=>self::GCSE_SEARCH_ENGINE_ID);
$results = $service->cse->listCse("lol cats", $optParams);
The results object implements Iterator so we can loop over them as follows:
foreach($results->getItems() as $k=>$item){
var_dump($item);
}
Google Prerequisites
In order to use this library though, you will have to set up a few google things first. These things are eventually mentioned on the Google API Client Libraries PHP (Beta) website, but you'll have to click around & dig for them and even then, you'll miss the last one below:
You will need a Custom Search Engine. Don't be confused by the fact that most of the references on the internet to Custom Search Engines are for people who are not trying to do programatic searches. You need one, and they're easy to set up here: https://cse.google.com/cse/all
You will need a Google Project. Again, set up is easy when you know where to go: https://console.developers.google.com/apis/dashboard
You will need an API Key (aka a Developer Key). Go here and create a new key if you don't already have one: https://console.developers.google.com/apis/credentials
You will need to enable Google Custom Search for your project. At this point you can make queries to google, but you may get an error response back if you have not yet enabled Google Custom Search for your project. Go to the dashboard, click the blue "Enable API" link, search for Google Custom Search and enable it. https://console.developers.google.com/apis/dashboard
A Thoroughly Commented Example
This is a more realistic example than the example above. It is still very simple, but it's always nice to have something new explained in two different ways with lots of explanatory comments.
<?php
include_once __DIR__ . '/vendor/autoload.php';
/**
* Retrieves a simple set of google results for a given plant id.
*/
class GoogleResults implements IteratorAggregate {
// Create one or more API keys at https://console.developers.google.com/apis/credentials
const GCSE_API_KEY = "nqwkoigrhe893utnih_gibberish_q2ihrgu9qjnr";
/* The search engine id is specific to each "custom search engine"
* you have configured at https://cse.google.com/cse/all
* Remember that you must have enabled Custom Search API for the project that
* contains your API Key. You can do this at the following url:
* https://console.developers.google.com/apis/api/customsearch.googleapis.com/overview?project=vegfetch-v01&duration=PT1H
* If you fail to enable the Custom Search API before you try to execute a search
* the exception that is thrown will indicate this. */
const GCSE_SEARCH_ENGINE_ID = "937592689593725455:msi299dkne4de";
// Holds the GoogleService for reuse
private $service;
// Holds the optParam for our search engine id
private $optParamSEID;
/**
* Creates a service object for our Google Custom Search. The API key is
* permiently set, but the search engine id may be changed when performing
* searches in case you want to search across multiple pre-prepared engines.
*
* #param string $appName Optional name for this google search
*/
public function __construct($appName = "My_Search") {
$client = new Google_Client();
// application name is an arbitrary name
$client->setApplicationName($appName);
// the developer key is the API Key for a specific google project
$client->setDeveloperKey(self::GCSE_API_KEY);
// create new service
$this->service = new Google_Service_Customsearch($client);
// You must specify a custom search engine. You can do this either by setting
// the element "cx" to the search engine id, or by setting the element "cref"
// to the public url for that search engine.
//
// For a full list of possible params see https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Customsearch/Resource/Cse.php
$this->optParamSEID = array("cx"=>self::GCSE_SEARCH_ENGINE_ID);
}
/**
* A simplistic function to take a search term & search options and return an
* array of results. You may want to
*
* #param string $searchTerm The term you want to search for
* #param array $optParams See: For a full list of possible params see https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Customsearch/Resource/Cse.php
* #return array An array of search result items
*/
public function getSearchResults($searchTerm, $optParams = array()){
// return array containing search result items
$items = array();
// Merge our search engine id into the $optParams
// If $optParams already specified a 'cx' element, it will replace our default
$optParams = array_merge($this->optParamSEID, $optParams);
// set search term & params and execute the query
$results = $this->service->cse->listCse($searchTerm, $optParams);
// Since cse inherits from Google_Collections (which implements Iterator)
// we can loop through the results by using `getItems()`
foreach($results->getItems() as $k=>$item){
var_dump($item);
$item[] = $item;
}
return $items;
}
}
You have to use not Google_Service, but Google_Service_Customsearch
$service = new Google_Service_Customsearch($client);
and then:
$results = $service->cse->listCse($searchTerm, $optParams);
The listCse() function (now) only takes one parameter - the complete array of keys mentioned in the API documentation (https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list).
So - a minimum the cx and q keys have to be included in the array.
I am using API Platform 2.0 with Symfony 3.1.
I followed the WIP documentation to add groups to serialisation context conditionally. For that I decorated the ContextBuilder.
This works well to set some groups based on currently logged in user.
But now I additionally want to add some groups depending on the requested resource item - so I need that to be available as Object, already fetched from persistence layer.
Something like this:
public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null) : array {
/* #var $currentUser User */
$currentUser = $this->tokenStorage->getToken()->getUser();
/* #var $requestedProduct Product */
$requestedProduct = $this->getRequestedItem();
if ($product->getAuthoringOrganization() === $currentUser->getOrganization() {
$context['groups'][] = 'api_products_get_item_current_user_is_owner';
}
return $context;
}
I am afraid i cant get the requested item / collection in ContextBuilder. If so, i would be really happy to get some advice where to build my serialisation groups.
In EventListener i can do that to get what i called "$requestedProduct" here:
$subject = $event->getControllerResult())
Thanks a lot for your help.
Cheers Ben
It is available from the request attributes:
$request->attributes->get('data');
See https://github.com/api-platform/core/blob/2d252cfe1a188cc0d05c70a78d111b7e54c6d650/src/EventListener/ReadListener.php#L61
Passing uid as an argument works fine with this code:
$bouts = views_get_view_result('Results', 'page_1', array($user->uid));
The key line in views_get_view_result that sets arguments is:
$view->set_arguments($args);
But what about passing date ranges?
Also, if something is specified as a filter on a view, is there a way to prorammatically alter it?
views_get_view_result:
/**
* Investigate the result of a view.
* from Drupal.org.
*
* #param string $viewname
* The name of the view to retrieve the data from.
* #param string $display_id
* The display id. On the edit page for the view in question, you'll find
* a list of displays at the left side of the control area. "Defaults"
* will be at the top of that list. Hover your cursor over the name of the
* display you want to use. A URL will appear in the status bar of your
* browser. This is usually at the bottom of the window, in the chrome.
* Everything after #views-tab- is the display ID, e.g. page_1.
* #param array $args
* Array of arguments. (no keys, just args)
* #return
* array
* An array containing an object for each view item.
* string
* If the view is not found a message is returned.
*/
function views_get_view_result($viewname, $display_id = NULL, $args = NULL) {
$view = views_get_view($viewname);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
/* print "<pre> $viewname: $display_id";
print_r(get_class_methods($view)); */
return $view->result;
}
else {
return t('View %viewname not found.', array('%viewname' => $viewname));
}
}
As for passing data ranges and given the posted function definition, you could pass date ranges to that only if the view would accept them as arguments. I'm not 100% sure, but afaik date ranges can only be defined as filters, not as arguments, which leads to your second Question:
Programmatically altering the views filter settings is possible, but a bit messy, given the rather complicated view object/array mashup structure. In your posted function above, the first line is
$view = views_get_view($viewname);
After that, $view contains the whole view object. The filter settings are defined per display, so assuming you have a view with only a default display, you will find the filter settings under
$view->display['default']->display_options['filters']
(Note the object/array notation mix - the display is a contained object of type views_display)
The 'filters' array contains one entry per filter, with varying elements depending on the filter type. For your purpose, I would suggest to create a dummy view with just the filter you are interested in, with preconfigured/hardcoded values. Using a debugger (or var_dump/print_r) you can then take a look at the filter array after view creation. From what you find there, you should be able to deduce how to inject your custom date range.
Disclaimer: Poking around in the view like this is a bit annoying and not to effective, but it works. As of yet, I have not found a concise documentation of Views2 that would explain the innards in a straight forward way, as I find the official API documentation a bit lacking concerning the usage from code. (Of course this could well be just me being to stupid ;)
If you're using views 2, you can use the GUI to add a date argument. Then in the url, you can put :
www.yousite.com/yourview/startDate--finishDate
For the startDate/finishDate, the format is YYYY-MM-DD-HH.
GL!