Instagram

Verze:

14. 09. 2022

Zodpovědná osoba:

Dominik Šlechta

—Insert into DB

INSERT INTO `settings_config` (`id`, `name`, `value`, `hidden`, `type`, `note`, `visible`) VALUES ('ADMIN_INSTAGRAM', 'Přidat tlačítko instagramu do adminu pro přihlášení', '1', 0, 'input', 'Přidá tlačítko přihlásit se přes instagram do nastavení webu, po přihlášení se zobrazí instagram příspěvky na webu.', 0);

—app/lang/admin.cs_CZ.neon

setting:
	..............

	instagram_login_failed: 'Chyba komunikace s instagramem'
	instagram_login_invalid: 'Neplatné přihlášení, zkuste se přihlásit znovu.'
	instagram_remove: 'Odhlásit a odstranit data instagramu'
	instagram_remove_confirm: 'Opravdu smazat načtená data a odhlásit se z instagramu? Z webu zmizí část s Vašimi instagram příspěvky a pro opětovné zobrazení bude nutné se znovu přihlásit.'
instagram_cleanup:
	default_header: 'Odstranění dat instagramu ze systému'
	success: 'Instagram úspěšně odhlášen ze systému a všechna načtená data instagramu vymazána.'
	failed: 'Nepodařilo se vyčistit ze systému všechny data instagramu, zkuste akci opakovat.'

—app/presenters/Admin/NastaveniPresenter.php

public function renderWeb()
{
	$domain = str_replace('www.', '', parse_url($this->link('//Nastaveni:web'))['host']);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, 'https://www.czechgroup.cz/api/instagram/get?' . http_build_query(['fields' => 'username', 'domain' => $domain, 'token' => hash_hmac('sha256', json_encode(['fields' => 'username']), $domain)]));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	$result = json_decode($result, true);

	if (!empty($result)) {
		if (!isset($result['error'])) {
			$this->template->instagramUser = $result['username'];
		} else {
			switch ($result['error_code']) {
				case('UNAUTHORIZED'):
					$this->template->instagramError = true;
					break;
				case('LOGIN_INVALID'):
					$this->template->instagramInvalidLogin = true;
					break;
			}
		}
	} else {
		$this->template->instagramError = true;
	}

	$this->template->domain = $domain;
	$this->template->redirect_uri = $this->link('//Nastaveni:web');
	$this->template->czechgroupLoginToken = hash_hmac('sha256', json_encode(['redirect_uri' => $this->link('//Nastaveni:web')]), $domain); //Token je keyed sha256 hash json encoded parameterů (vyjma tokenu a domény)
	$this->template->instagramCached = (file_exists('../temp/instagramCache.json') || isset($this->template->instagramUser));
}

public function renderInstagramCleanup()
{
	$domain = str_replace('www.', '', parse_url($this->link('//Nastaveni:web'))['host']);
	$success = true;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, 'https://www.czechgroup.cz/api/instagram/removeDataWebCall?' . http_build_query(['action' => 'data-only', 'domain' => $domain, 'token' => hash_hmac('sha256', json_encode(['action' => 'data-only']), $domain)]));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	$result = json_decode($result, true);

	if (file_exists('../temp/instagramCache.json')) {
		$success = unlink('../temp/instagramCache.json');
	}
	if ($success && isset($result['state'])) {
		$this->template->success = true;
	} else {
		$this->template->success = false;
	}
}

public function renderRedirects()

—app/presenters/Admin/templates/Nastaveni/instagramCleanup.latte
FULL FROM DEMO

—app/presenters/Admin/templates/Nastaveni/web.latte

<h2 class="h2">{_admin.setting.default_header}</h2>

<div n:if="$web['ADMIN_INSTAGRAM']" class="row">
	<div class="col-4 col-md-4 col-lg-4">
		<a href="https://www.czechgroup.cz/api/instagram/login?redirect_uri={$redirect_uri}&domain={$domain}&token={$czechgroupLoginToken}"
				class="btn btn-info"><i class="fa fa-instagram"></i> Přihlásit přes instagram
		</a>
	</div>
</div>
{if isset($_GET['instagramError']) || isset($instagramError)}
	<div class="row">
		<div class="col-6 col-md-6 col-lg-6">
			{_'admin.setting.instagram_login_failed'}
		</div>
	</div>
{/if}
{if isset($_GET['instagramInvalidLogin']) || isset($instagramInvalidLogin)}
	<div class="row">
		<div class="col-6 col-md-6 col-lg-6">
			{_'admin.setting.instagram_login_invalid'}
		</div>
	</div>
{/if}
{if isset($instagramUser)}
	<div class="row">
		<div class="col-6 col-md-6 col-lg-6">
			{_'admin.layout.login_as'}
			<a href="https://www.instagram.com/{$instagramUser}" target="_BLANK">@{$instagramUser}</a>
		</div>
	</div>
{/if}
{if $instagramCached}
	<div class="row">
		<div class="col-6 col-md-6 col-lg-6">
			<a n:href="Nastaveni:instagramCleanup"
					onclick="return confirm({_'admin.setting.instagram_remove_confirm'})">{_'admin.setting.instagram_remove'}</a>
		</div>
	</div>
{/if}


{form nastaveniWebu class => "form-horizontal"}

—app/presenters/Front/BasePresenter.php
END OF FUNCTION beforeRender()

$domain = str_replace('www.', '', parse_url($this->link('//Homepage:page'))['host']);

if (!file_exists('../temp/instagramCache.json') || empty(json_decode(file_get_contents('../temp/instagramCache.json'), true)['expire']) || json_decode(file_get_contents('../temp/instagramCache.json'), true)['expire'] < time() || empty(json_decode(file_get_contents('../temp/instagramCache.json'), true)['urls'])) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, 'https://www.czechgroup.cz/api/instagram/get?' . http_build_query(['fields' => 'username,media', 'domain' => $domain, 'token' => hash_hmac('sha256', json_encode(['fields' => 'username,media']), $domain)]));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	$result = json_decode($result, true);
	$instagramPhotosUrls = [];
	if (!isset($result['error'])) {
		$this->template->instagramUsername = $result['username'];
		foreach ($result['media'] as $data) {
			if ($data['media_type'] == 'VIDEO') {
				$instagramPhotosUrls[] = $data['thumbnail_url'];
			} else {
				$instagramPhotosUrls[] = $data['media_url'];
			}
		}
	}

	if (!empty($instagramPhotosUrls)) {
		file_put_contents('../temp/instagramCache.json', json_encode(['urls' => $instagramPhotosUrls, 'username' => $this->template->instagramUsername, 'expire' => strtotime('+2 hours')]));
		$this->template->instagramData = $instagramPhotosUrls;
	}
} else {
	$instagramCache = json_decode(file_get_contents('../temp/instagramCache.json'), true);
	$this->template->instagramData = $instagramCache['urls'];
	$this->template->instagramUsername = $instagramCache['username'];
}

—app/presenters/Front/InstagramPresenter.php
FULL FROM DEMO

—app/router/RouterFactory.php

$frontRoutes[] = new Route('/api/eshop/pohoda/stock', 'Pohoda:stock');
$frontRoutes[] = new Route('/api/eshop/pohoda/orders', 'Pohoda:orders');
$frontRoutes[] = new Route('/api/instagram/do', 'Instagram:do');

$adminRoutes[] = new Route('/admin/nastaveni/presmerovani-list', 'Nastaveni:redirectsList');
$adminRoutes[] = new Route('/admin/nastaveni', 'Nastaveni:web');
$adminRoutes[] = new Route('/admin/nastaveni/instagram-cleanup', 'Nastaveni:instagramCleanup');