<?php
namespace app\wechat\service;
use service\DataService;
use service\FileService;
use service\WechatService;
use think\Db;
class MediaService
{
public static function getNewsById($id, $where = [])
{
$data = Db::name('WechatNews')->where(['id' => $id])->where($where)->find();
$article_ids = explode(',', $data['article_id']);
$articles = Db::name('WechatNewsArticle')->whereIn('id', $article_ids)->select();
$data['articles'] = [];
foreach ($article_ids as $article_id) {
foreach ($articles as $article) {
if (intval($article['id']) === intval($article_id)) {
unset($article['create_by'], $article['create_at']);
$data['articles'][] = $article;
}
}
}
return $data;
}
public static function uploadImage($local_url)
{
$map = ['md5' => md5($local_url)];
if (($media_url = Db::name('WechatNewsImage')->where($map)->value('media_url'))) {
return $media_url;
}
$info = WechatService::WeChatMedia()->uploadImg(self::getServerPath($local_url));
if (strtolower(sysconf('wechat_type')) === 'thr') {
WechatService::wechat()->rmFile($local_url);
}
$data = ['local_url' => $local_url, 'media_url' => $info['url'], 'md5' => $map['md5']];
DataService::save('WechatNewsImage', $data, 'md5');
return $info['url'];
}
public static function uploadForeverMedia($local_url, $type = 'image', $video_info = [])
{
$map = ['md5' => md5($local_url), 'appid' => WechatService::getAppid()];
if (($media_id = Db::name('WechatNewsMedia')->where($map)->value('media_id'))) {
return $media_id;
}
$result = WechatService::WeChatMedia()->addMaterial(self::getServerPath($local_url), $type, $video_info);
if (strtolower(sysconf('wechat_type')) === 'thr') {
WechatService::wechat()->rmFile($local_url);
}
$data = ['md5' => $map['md5'], 'type' => $type, 'appid' => $map['appid'], 'media_id' => $result['media_id'], 'local_url' => $local_url];
isset($result['url']) && $data['media_url'] = $result['url'];
DataService::save('WechatNewsMedia', $data, 'md5', ['appid' => $map['appid'], 'type' => $type]);
return $data['media_id'];
}
protected static function getServerPath($local)
{
switch (strtolower(sysconf('wechat_type'))) {
case 'api':
if (file_exists($local)) {
return $local;
}
return FileService::download($local)['file'];
case 'thr':
return WechatService::wechat()->upFile(base64_encode(file_get_contents($local)), $local)['file'];
default:
return $local;
}
}
}