Subversion Repositories eFlore/Applications.cel

Compare Revisions

No changes between revisions

Ignore whitespace Rev 3772 → Rev 3773

/branches/v3.00-serfouette/scripts/modules/pull_plantnet/PullPlantnet.php
3,7 → 3,9
/*
PHP 7
 
Script used to synchronize PN occ with CEL
Script used to synchronize PN occ with Flora Data
 
Écrit en franglish pour une meilleure compréhension (lol)
*/
 
class PullPlantnet extends Script {
10,6 → 12,8
 
protected $bdd;
 
protected $debug = false;
 
protected $allowedPartners = ['tb', 'pn'];
 
// Nom du fichier contenant les correspondances d'ID TB/PN
25,7 → 29,6
protected $currentPage = '';
protected $currentProject = '';
protected $hasMore = false;
protected $count = 0;
 
// Traduction des organes de PN
protected $tagsImageTraduits = [
44,7 → 47,7
protected $lifecycles = [
'created',
'modified',
'deleted', // deleted peut être très lent
'deleted', // deleted peut être très lent (pas d'index coté PN pour le moment)
];
 
/**
66,6 → 69,7
'-pnObsId' => array(false, true, "ID de l'obs chez PlantNet"),
'-project' => array(false, true, "projectId de l'obs chez PlantNet"),
'-tbObsId' => array(false, true, "ID de l'obs chez Tela"),
'-debug' => array(false, false, "Mode débug (ajoute du log) Au choix parmi : debug/log (log est plus verbeux)"),
);
 
public function __construct($script_nom, $parametres_cli) {
73,6 → 77,8
$this->bdd = new Bdd();
 
$this->correspondingIdsFilename = Config::get('correspondingIdsFilename');
 
$this->debug = $this->getParametre('debug');
}
 
public function executer() {
80,13 → 86,13
 
switch ($cmd) {
case 'updateLatest':
$this->updateLatest($this->getParametre('startDate'));
$this->updateLatest($this->getParametre('startDate'), $this->getParametre('lifecycle'));
break;
case 'updateOnePN':
$this->updateOnePN((int)$this->getParametre('pnObsId'), $this->getParametre('project'));
break;
case 'updateOneTB':
$this->updateOneTB($this->getParametre('tbObsId'));
$this->updateOneTB((int)$this->getParametre('tbObsId'));
break;
case 'updateCorrespondingIdsTable':
$this->updateCorrespondingIdsTable();
95,8 → 101,8
$msg = "Erreur : la commande '$cmd' n'existe pas!\n"
. ', utilisez plutôt :' . "\n"
. 'php cli.php PullPlantnet -a updateLatest -startDate "YYYY:MM:DD HH:II:SS" [[-lifecycle [modified]/created/deleted]]' . "\n"
. 'php cli.php PullPlantnet -a updateOnePN -pnObsId "xxxxxx" -project "xxxxxx"' . "\n"
. 'php cli.php PullPlantnet -a updateOneTB -tbObsId "xxxxxx"' . "\n"
. 'php cli.php PullPlantnet -a updateOnePN -pnObsId "1234567890" -project "xxxxxx"' . "\n"
. 'php cli.php PullPlantnet -a updateOneTB -tbObsId "1234567890"' . "\n"
. 'php cli.php PullPlantnet -a updateCorrespondingIdsTable' . "\n"
;
throw new Exception($msg);
132,7 → 138,9
[$project['id'], Config::get('tokenPlantnet'), $startDate, $lifecycle],
Config::get('urlPlantnetBase').Config::get('urlPlantnetLatestChanges')
);
// die(var_dump($url_service));
 
$this->debug("URL service derniers changements : $url_service");
 
$this->currentPage = $url_service;
}
 
148,6 → 156,7
} elseif (200 != $code) {
// l'api répond avec une 404 quand y'a une date dans le futur ou simplement pas de nouvelle obs...
if (404 == $code && strpos($reponse, 'No more results')) {
$this->log("Pas d'autres résultats");
$this->hasMore = false;
$this->currentPage = '';
return [];
159,11 → 168,10
 
$this->hasMore = $responseJson['hasMore'];
if ($this->hasMore) {
$this->count += count($observations_PN);
$this->currentPage = Config::get('urlPlantnetBase').$responseJson['next'];
$this->debug("URL service derniers changements, page suivante : {$this->currentPage}");
} else {
$this->currentPage = '';
$this->count = 0;
}
 
return $observations_PN;
173,6 → 181,8
// get PN projects list
$url = str_replace('{token}', Config::get('tokenPlantnet'), Config::get('urlPlantnetBase').Config::get('urlPlantnetProjects'));
 
$this->debug("URL service liste projets : $url");
 
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$reponse = curl_exec($ch);
186,6 → 196,8
 
echo 'Liste de projets récupérée : ' . count($pnProjects) . " projets dans la liste\n";
 
$this->debug("Liste projets : " . json_encode($pnProjects));
 
return $pnProjects;
}
 
199,19 → 211,24
foreach ($observations_PN as $obs) {
// est-ce qu'on a déjà traité cette obs ? (oui une même obs peut être dans plusieurs projects)
if (in_array($obs['id'], $this->processedObsId)) {
$this->log("Obs {$obs['id']} déjà traitée pendant cette run");
continue;
} else {
$this->processedObsId[] = $obs['id'];
$this->log("Obs {$obs['id']} ajoutée à la liste de cette run");
}
 
// on ne teste pas la suppression de l'obs ici, faut le faire après avoir vérifié si on l'a déjà synchro
if (!isset($obs['currentName'])) {
$this->log("Obs {$obs['id']} sans nom de taxon, on zap");
continue; // pas de nom de taxon, obs inutile
}
if (!isset($obs['geo'])) {
$this->log("Obs {$obs['id']} sans geom, on zap");
continue; // pas de position, obs inutile
}
if (!isset($obs['dateObs'])) {
$this->log("Obs {$obs['id']} sans date, on zap");
continue; // pas de date, obs inutile
}
 
222,6 → 239,7
// on update l'identification proposée par PN
 
// @TODO
$this->log("Obs {$obs['id']} venant de Tela, mise à jour pas implémentée, on zap");
continue;
} elseif (!isset($obs['partner']['id'])) {
// ce n'est pas une obs d'un partenaire, c'est donc une obs PN
229,10 → 247,11
$email = $obs['author']['email'];
$infos_utilisateur = $this->findUserInfo($email);
if (!$infos_utilisateur) {
$this->log("Obs {$obs['id']} email $email ne provient pas d'un telabotaniste");
continue; // c'est pas un telabotaniste
}
//echo "Synchro d'une obs d'un telabotaniste : $email";
// echo json_encode($obs);
$this->log("Obs {$obs['id']} email $email provient d'un telabotaniste");
$this->log(json_encode($obs));
// die(var_dump($obs));
 
// vérification que l'obs n'a pas déjà été ajoutée à la BdD de Tela
254,6 → 273,7
}
 
if (isset($obs['deleted']) && (true === $obs['deleted'])) {
$this->log("Obs {$obs['id']} supprimée coté PlantNet");
continue; // obs supprimée chez PN sans être passée par nos serveurs
}
 
262,6 → 282,7
$images_size = 0;
foreach ($obs['images'] ?? [] as $i => $image) {
if ($image['deleted']) {
$this->log("Obs {$obs['id']} image {$image['id']} supprimée coté PlantNet");
continue;
}
 
271,6 → 292,7
do {
$img = file_get_contents($image['o']);
$retry--;
$this->log("Obs {$obs['id']} lecture image {$image['id']} tentatives restantes : $retry");
} while (!$img && $retry);
 
if (!$img) {
285,7 → 307,7
fclose($handle);
$images_size += filesize($tempfile);
 
// echo "Image de " . number_format(filesize($tempfile), 0, ',', ' ') . " octets créé : $tempfile\n";
$this->log("Obs {$obs['id']} image {$image['id']} créée " . number_format(filesize($tempfile), 0, ',', ' ') . " octets : $tempfile");
 
$params = [
'name' => 'image' . $i,
298,7 → 320,7
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$reponse = curl_exec($ch);
// var_dump($reponse);
$this->log("Obs {$obs['id']} image {$image['id']} envoyée à l'api de création. Réponse : $reponse");
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
 
328,6 → 350,8
// die();
 
$geo = $this->getGeoInfo($obs['geo']);
$this->log("Obs {$obs['id']} décodage du geom : " . json_encode($obs['geo']));
$this->log("Obs {$obs['id']} geom décodé : " . json_encode($geo));
 
// on insère l'obs via le service CelWidgetSaisie
$infos_obs = [
348,7 → 372,7
// 'obsId1[num_nom_ret]' => '',
// 'obsId1[num_nom_sel]' => '',
// 'obsId1[num_taxon]' => '',
'obsId1[referentiel]' => $this->findProbableTaxoRepos($this->currentProject['id']),
'obsId1[referentiel]' => $this->findProbableTaxoRepos($this->currentProject['id']), // @TODO faire une fois et mettre en cache
// 'obsId1[station]' => '',
'obsId1[obs_id]' => $obs['id'],
'projet' => 'PlantNet',
364,8 → 388,9
foreach ($images as $i => $image) {
$infos_obs["obsId1[image_nom][$i]"] = $image;
}
// var_dump($infos_obs);
 
$this->log("Obs {$obs['id']} prête à être insérée : " . json_encode($infos_obs));
 
// curl post $infos_obs
$ch = curl_init($url_cel_widget_saisie);
curl_setopt($ch, CURLOPT_POST, true);
372,6 → 397,7
curl_setopt($ch, CURLOPT_POSTFIELDS, $infos_obs);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$reponse = curl_exec($ch);
$this->log("Obs {$obs['id']} réponse de la requête d'insertion : " . json_encode($reponse));
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
 
379,7 → 405,6
throw new Exception("Ça a pété à l'envoi de l'obs :\n $reponse\n avec l'obs : " . json_encode($infos_obs) . "\n");
}
 
// var_dump($reponse);
$id_obs_tb = json_decode($reponse, true)['id'];
$id_obs_pn = $obs['id'];
// on insère les ids de correspondance obsPN obsTB dans la table cel_plantnet
392,7 → 417,7
$date = date('d/m/Y H:i:s', intdiv($obs['dateObs'], 1000));
$count_img = count($images);
$images_size = number_format($images_size, 0, ',', ' ');
echo "Obs insérée en base : ID PN $id_obs_pn ; ID TB $id_obs_tb ; utilisateur_tb $email ; date $date ; images $count_img ; taille_octets $images_size \n";
echo "Obs insérée en base : ID PN $id_obs_pn ; ID TB $id_obs_tb ; utilisateur_tb $email ; date_obs $date ; images $count_img ; taille_octets $images_size \n";
}
}
}
753,4 → 778,16
}
echo "Matching partners ids saved!";
}
 
private function debug($text) {
if ($this->debug) {
echo 'DEBUG - ' . $text . "\n";
}
}
 
private function log($text) {
if ('log' == $this->debug) {
echo 'LOG - ' . $text . "\n";
}
}
}
/branches/v3.00-serfouette/scripts
Property changes:
Modified: svn:mergeinfo
Merged /trunk/scripts:r3771-3772
/branches/v3.00-serfouette
Property changes:
Modified: svn:mergeinfo
Merged /trunk:r3771-3772