Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 47 additions & 30 deletions app/Services/DesaService.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
namespace App\Services;

use App\Models\DataDesa;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
Expand Down Expand Up @@ -82,7 +81,7 @@ public function listDesaCacheKey(bool $all = false): string
}

/**
* Get Unique Desa
* Get Unique Desa.
*/
public function desa(array $filters = [])
{
Expand All @@ -106,7 +105,7 @@ public function desa(array $filters = [])
}

/**
* Get feeds for all desa
* Get feeds for all desa.
*/
public function getFeeds(): array
{
Expand All @@ -118,14 +117,17 @@ public function getFeeds(): array
})->filter(static fn($q) => !empty($q->website));
$feeds = [];
foreach ($allDesa as $desa) {
$feedReader = new SimplePie();
$feedReader->set_feed_url($desa->website_url_feed['website']);
//$feedReader->set_item_limit(5);
$feedReader->force_fsockopen(true);
$feedReader->set_cache_location(storage_path('framework/cache/simplepie'));
$feedReader->init();
$feedReader->handle_content_type();
$items = $feedReader->get_items();
// Kegagalan satu feed desa tidak boleh menggagalkan feed desa lain
try {
$items = $this->makeFeedReader($desa->website_url_feed['website'])->get_items();
} catch (\Throwable $feedError) {
Log::warning('Gagal mengambil feed desa', [
'desa_id' => $desa->desa_id,
'website' => $desa->website,
'message' => $feedError->getMessage(),
]);
continue;
}

// Handle case where no items returned
if (empty($items)) {
Expand All @@ -138,19 +140,7 @@ public function getFeeds(): array

foreach ($items as $item) {
try {
$feeds[] = [
'desa_id' => $desa->desa_id,
'nama_desa' => $desa->nama,
'feed_link' => $item->get_feed()->get_permalink(),
'feed_title' => $item->get_feed()->get_title(),
'link' => $item->get_link(),
'date' => \Carbon\Carbon::createFromTimestamp((int) $item->get_date('U')),
'author' => $item->get_author()->get_name() ?? 'Administrator',
'title' => $item->get_title(),
'image' => get_tag_image($item->get_description()),
'description' => strip_tags(substr(str_replace(['&', 'nbsp;', '[...]'], '', $item->get_description()), 0, 250) . '[...]'),
'content' => $item->get_content(),
];
$feeds[] = $this->mapFeedItem($item, $desa);
} catch (\Throwable $itemError) {
Log::error('Error processing feed item', [
'desa_id' => $desa->desa_id,
Expand All @@ -163,7 +153,7 @@ public function getFeeds(): array

Log::info('Total feeds collected', ['count' => count($feeds)]);
return $feeds;
} catch (Exception $e) {
} catch (\Throwable $e) {
Log::error('Error fetching desa feeds', ['message' => $e->getMessage()]);
return [];
}
Expand All @@ -180,7 +170,7 @@ public function listPathDesa()
}

/**
* Get Unique Desa
* Get Unique Desa.
*/
public function jumlahDesa(array $filters = [])
{
Expand All @@ -206,14 +196,41 @@ public function jumlahDesa(array $filters = [])
}

/**
* Dapatkan object desa berdasarkan kode_desa tertentu
*
* @param string $kodeDesa
* @return collection|DataDesa|\stdClass|null
* Dapatkan object desa berdasarkan kode_desa tertentu.
*/
public function getDesaByKode(string $kodeDesa): Collection|DataDesa|\stdClass|null
{
$listDesa = $this->listDesa();
return $listDesa->where('desa_id', $kodeDesa)->first();
}

protected function makeFeedReader(string $url): SimplePie
{
$feedReader = new SimplePie();
$feedReader->set_feed_url($url);
$feedReader->force_fsockopen(true);
$feedReader->set_cache_location(storage_path('framework/cache/simplepie'));
$feedReader->init();
$feedReader->handle_content_type();

return $feedReader;
}

protected function mapFeedItem($item, DataDesa $desa): array
{
return [
'desa_id' => $desa->desa_id,
'nama_desa' => $desa->nama,
'feed_link' => $item->get_feed()->get_permalink(),
'feed_title' => $item->get_feed()->get_title(),
'link' => $item->get_link(),
'date' => \Carbon\Carbon::createFromTimestamp((int) $item->get_date('U')),
// get_author() mengembalikan null bila item feed tidak memiliki author
'author' => $item->get_author()?->get_name() ?? 'Administrator',
'title' => $item->get_title(),
'image' => get_tag_image($item->get_description()),
'description' => strip_tags(substr(str_replace(['&', 'nbsp;', '[...]'], '', $item->get_description()), 0, 250) . '[...]'),
'content' => $item->get_content(),
];
}
}
2 changes: 2 additions & 0 deletions catatan_rilis.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Terimakasih [isi disini] yang telah berkontribusi langsung mengembangkan aplikas
11. [#1796](https://github.com/OpenSID/OpenDK/issues/1796) Menghapus Jabatan Camat/Sekretaris membuat seluruh aplikasi error 500.
12. [#1797](https://github.com/OpenSID/OpenDK/issues/1797) Persentase belanja barang/jasa salah dan division by zero di AnggaranRealisasiChartService.
13. [#1798](https://github.com/OpenSID/OpenDK/issues/1798) Perbaikan Cache listDesa terus diperpanjang dan tidak membedakan parameter $all.
14. [#1799](https://github.com/OpenSID/OpenDK/issues/1799) Perbaikan getFeeds() error jika item RSS tidak punya author dan gagal per feed.


#### TEKNIS

Expand Down
31 changes: 1 addition & 30 deletions helpers/general_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
*/

use App\Http\Controllers\Helpers\Parsedown;
use App\Models\DataDesa;
use App\Models\Menu;
use App\Models\Role;
use App\Models\Themes;
Expand All @@ -40,7 +39,6 @@
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use voku\helper\AntiXSS;
use willvincent\Feeds\Facades\FeedsFacade;

/*
* Parsing url image dari rss feed description
Expand Down Expand Up @@ -550,34 +548,7 @@ function theme_active()
if (! function_exists('getFeeds')) {
function getFeeds()
{
return cache()->remember('feeds_desa', 60 * 60, function () {
$all_desa = DataDesa::websiteUrl()->get()
->map(function ($desa) {
return $desa->website_url_feed;
})->all();

$feeds = [];
foreach ($all_desa as $desa) {
$getFeeds = FeedsFacade::make($desa['website'], 5, true);
foreach ($getFeeds->get_items() as $item) {
$feeds[] = [
'desa_id' => $desa['desa_id'],
'nama_desa' => $desa['nama'],
'feed_link' => $item->get_feed()->get_permalink(),
'feed_title' => $item->get_feed()->get_title(),
'link' => $item->get_link(),
'date' => \Carbon\Carbon::parse($item->get_date('U')),
'author' => $item->get_author()->get_name() ?? 'Administrator',
'title' => $item->get_title(),
'image' => get_tag_image($item->get_description()),
'description' => strip_tags(substr(str_replace(['&', 'nbsp;', '[...]'], '', $item->get_description()), 0, 250).'[...]'),
'content' => $item->get_content(),
];
}
}

return $feeds ?? null;
});
return app(\App\Services\DesaService::class)->getFeeds();
}
}

Expand Down
142 changes: 142 additions & 0 deletions tests/Unit/Services/DesaServiceFeedsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

/*
* File ini bagian dari:
*
* OpenDK
*
* Aplikasi dan source code ini dirilis berdasarkan lisensi GPL V3
*
* Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
*
* Dengan ini diberikan izin, secara gratis, kepada siapa pun yang mendapatkan salinan
* dari perangkat lunak ini dan file dokumentasi terkait ("Aplikasi Ini"), untuk diperlakukan
* tanpa batasan, termasuk hak untuk menggunakan, menyalin, mengubah dan/atau mendistribusikan,
* asal tunduk pada syarat berikut:
*
* Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam
* setiap salinan atau bagian penting Aplikasi Ini. Barang siapa yang menghapus atau menghilangkan
* pemberitahuan ini melanggar ketentuan lisensi Aplikasi Ini.
*
* PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT MAUPUN
* TERSIRAT. PENULIS ATAU PEMEGANG HAK CIPTA SAMA SEKALI TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN ATAU
* KEWAJIBAN APAPUN ATAS PENGGUNAAN ATAU LAINNYA TERKAIT APLIKASI INI.
*
* @package OpenDK
* @author Tim Pengembang OpenDesa
* @copyright Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
* @license http://www.gnu.org/licenses/gpl.html GPL V3
* @link https://github.com/OpenSID/opendk
*/

use App\Models\DataDesa;
use App\Services\DesaService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

function rssFeed(string $itemXml): string
{
return '<?xml version="1.0" encoding="UTF-8"?>'
.'<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel>'
.'<title>Feed Desa</title><link>https://desa.test/</link><description>Berita</description>'
.$itemXml
.'</channel></rss>';
}

/**
* DesaService tanpa akses jaringan: daftar desa dan isi feed ditentukan oleh test.
*
* @param array<string, string|Throwable> $feeds website desa => XML RSS atau exception
*/
function desaServiceDenganFeed(array $feeds): DesaService
{
return new class($feeds) extends DesaService
{
public function __construct(private array $feeds)
{
parent::__construct();
}

public function listDesa($all = false)
{
return collect(array_keys($this->feeds))->values()->map(fn ($website, $i) => new DataDesa([
'desa_id' => 'DESA'.$i,
'nama' => 'Desa '.$i,
'sebutan_desa' => 'Desa',
'website' => $website,
]));
}

protected function makeFeedReader(string $url): SimplePie
{
$website = str_replace('index.php/feed', '', $url);
$feed = $this->feeds[$website];

if ($feed instanceof Throwable) {
throw $feed;
}

$reader = new SimplePie();
$reader->enable_cache(false);
$reader->set_raw_data($feed);
$reader->init();

return $reader;
}
};
}

beforeEach(function () {
Cache::forget('desa_feeds');
});

afterEach(function () {
Cache::forget('desa_feeds');
});

it('memakai author Administrator bila item feed tidak punya author', function () {
$feeds = desaServiceDenganFeed([
'https://desa-a.test/' => rssFeed('<item><title>Berita Tanpa Author</title><link>https://desa-a.test/artikel/1</link><description>Isi</description></item>'),
])->getFeeds();

expect($feeds)->toHaveCount(1)
->and($feeds[0]['title'])->toBe('Berita Tanpa Author')
->and($feeds[0]['author'])->toBe('Administrator');
});

it('tetap memakai nama author dari feed bila tersedia', function () {
$feeds = desaServiceDenganFeed([
'https://desa-a.test/' => rssFeed('<item><title>Berita</title><link>https://desa-a.test/artikel/1</link><description>Isi</description><dc:creator>Operator Desa</dc:creator></item>'),
])->getFeeds();

expect($feeds)->toHaveCount(1)
->and($feeds[0]['author'])->toBe('Operator Desa');
});

it('melewati feed desa yang gagal dan tetap mengambil feed desa lain', function () {
Log::spy();

$feeds = desaServiceDenganFeed([
'https://desa-rusak.test/' => new RuntimeException('Koneksi gagal'),
'https://desa-b.test/' => rssFeed('<item><title>Berita Desa B</title><link>https://desa-b.test/artikel/1</link><description>Isi</description></item>'),
])->getFeeds();

expect($feeds)->toHaveCount(1)
->and($feeds[0]['title'])->toBe('Berita Desa B')
->and($feeds[0]['desa_id'])->toBe('DESA1');

Log::shouldHaveReceived('warning')
->withArgs(fn ($message, $context) => $message === 'Gagal mengambil feed desa' && $context['desa_id'] === 'DESA0')
->once();
});

it('helper getFeeds mendelegasikan ke DesaService', function () {
$hasil = [['title' => 'Berita', 'author' => 'Administrator']];

$this->mock(DesaService::class)
->shouldReceive('getFeeds')
->once()
->andReturn($hasil);

expect(getFeeds())->toBe($hasil);
});
1 change: 0 additions & 1 deletion tests/Unit/Services/DesaServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Config;
use willvincent\Feeds\Facades\FeedsFacade;

uses(DatabaseTransactions::class);

Expand Down
Loading