新增临时素材

@since 0.0.1
@param {integer} $material_id 素材id
@return {integer}
@example \Yii::$app->wechat->addMedia($material_id);
978222
public function addMedia($material_id) {
		$material = WechatMaterial::findOne($material_id);
		if(!$material) {
			throw new ErrorException('数据查询失败');
		}

		$data = $this->getData('/cgi-bin/media/upload', [
			'access_token' => $this->getAccessToken(),
			'type' => $material->type,
		], ['media' => '@' . $material->localFile]);
		$material->cleanTmp();

		if($this->errcode == 0) {
			$materialMedia = new WechatMaterialMedia;
			$materialMedia->appid = $this->app->appid;
			$materialMedia->material_id = $material->id;
			$materialMedia->media_id = $data['media_id'];
			$materialMedia->expired_at = $data['created_at'] + $this->effectiveTimeOfTemporaryMaterial;
			if($materialMedia->save()) {
				return $materialMedia->id;
			}
		}

		return 0;
	}
271718
public function actionMessage($id)
    {
        $model = $this->findModel($id);
        $message = new Message($this->getWechat());

        if ($message->load(Yii::$app->request->post())) {
            $message->toUser = $model->open_id;
            if ($message->send()) {
                $this->flash('消息发送成功!', 'success');
                $message = new Message($this->getWechat());
            }
        }
        $message->toUser = $model->open_id;

        $searchModel = new MessageHistorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//        $dataProvider->sort = [
//            'defaultOrder' => ['created_at' => SORT_DESC]
//        ];
        $dataProvider->query
            ->wechat($this->getWechat()->id)
            ->wechatFans($model->open_id, $this->getWechat()->original);

        return $this->render('message', [
            'model' => $model,
            'message' => $message,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
1001570
function modUpdatePreparedState(id) {
        var updatingModules = {};
        update(id);

        function update(id) {
            modPrepare(id);
            if (!modIs(id, MODULE_ANALYZED)) {
                return false;
            }

            if (modIs(id, MODULE_PREPARED) || updatingModules[id]) {
                return true;
            }

            updatingModules[id] = 1;
            var mod = modModules[id];
            var prepared = true;

            each(
                mod.depMs,
                function (dep) {
                    // return (prepared = update(dep.absId));
                    prepared = update(dep.absId) && prepared;
                }
            );

            // 判断resource是否加载完成。如果resource未加载完成，则认为未准备好
            /* jshint ignore:start */
            prepared && each(
                mod.depRs,
                function (dep) {
                    prepared = !!dep.absId;
                    return prepared;
                }
            );
            /* jshint ignore:end */

            if (prepared && !modIs(id, MODULE_PREPARED)) {
                mod.state = MODULE_PREPARED;
            }
            updatingModules[id] = 0;
            return prepared;
        }
    }
718881
public function getForeverMedia($media_id,$is_video=false){
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array('media_id' => $media_id);
        //#TODO 暂不确定此接口是否需要让视频文件走http协议
        //如果要获取的素材是视频文件时，不能使用https协议，必须更换成http协议
        //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
        $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_GET_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            if (is_string($result)) {
                $json = json_decode($result,true);
                if ($json) {
                    if (isset($json['errcode'])) {
                        $this->errCode = $json['errcode'];
                        $this->errMsg = $json['errmsg'];
                        return false;
                    }
                    return $json;
                } else {
                    return $result;
                }
            }
            return $result;
        }
        return false;
    }
66105
public static function fullId()
    {
        $module_id = false;
        $modules = Yii::$app->loadedModules;
        foreach($modules as $module) {
            if ($module instanceof static) {
                $module_id = $module->getUniqueId();
                break;
            }
        }
        return $module_id;
    }
1042479
def info(self, media_id):
        
        dr = self.__app.native_api_call('media', 'i/' + media_id, {}, self.__options, False, None, False, http_path="/api/meta/v1/", http_method='GET')
        return json.loads(dr.text)
1342175
def get(self, media_id):
        
        def _processor(res):
            if isinstance(res, dict):
                if 'news_item' in res:
                    # 图文素材
                    return res['news_item']
            return res

        res = self._post(
            'material/get_material',
            data={
                'media_id': media_id
            },
            result_processor=_processor
        )
        return res
1317579
public function updateNews($news_media_id) {
		$newsMedia = WechatNewsMedia::findOne($news_media_id);
		if(!$newsMedia) {
			throw new ErrorException('数据查询失败');
		}

		if($newsMedia->news->count_item == count($newsMedia->thumbMaterialMediaIdList)) {
			$articles = $media->news->getArticles($this);
			$thumb_material_media_ids = [];
			$success = true;
			foreach($articles as $index => $article) {
				$thumb_material_media_ids[] = $article['thumb_material_media_id'];
				$data = $this->getData('/cgi-bin/material/update_news', [
					'access_token' => $this->getAccessToken(),
				], Json::encode([
					'media_id' => $media->media_id,
					'index' => $index,
					'articles' => $article,
				]));
				if($this->errcode != 0) {
					$success = false;
					break;
				}
			}
			if($success) {
				$media->thumb_material_media_ids = Json::encode($thumb_material_media_ids);
				if($details = $this->getNews($media->media_id)) {
					$media->urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'url'));
					$media->thumb_urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'thumb_url'));
				}
				if($media->save()) {
					return $media->id;
				}
			}
		} else {
			$newsid = $media->newsid;
			if($this->deleteNews($media->id)) {
				return $this->addNews($newsid);
			}
		}

		return 0;
	}
476140
public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (!empty($this->module->params['pageSizeAdmin'])) {
            $model->pageSize = intval($this->module->params['pageSizeAdmin']);
        }
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->save()) {
            return $this->redirect(['index', 'page' => $model->page, 'id' => $model->id]);
        } else {
            $rolesModels = [];
            if ($this->showRoles && !$model->isNewRecord) {
                $authItemModel = $this->module->model('AuthItem');
                $allRoles = $authItemModel::find()->where(['like', 'name', 'role'])->all();
                foreach ($allRoles as $role) {
                    $data = [
                        'item_name' => $role->name,
                        'user_id'   => $model->id,
                    ];
                    
                    $authAssignmentModel = $this->module->model('AuthAssignment');
                    $next = $authAssignmentModel::find()->where($data)->one();
                    if (empty($next)) {
                        $data['value'] = false;
                        $next = $this->module->model('AuthAssignment', [$data]);
                    } else {
                        $next->value = true;
                    }
                    $rolesModels[] = $next;
                }
            }
            return $this->render('update', [
                'model' => $model,
                'rolesModels' => $rolesModels,
            ]);
        }
    }
1262965
public static function media_get($access_token, $media_id)
    {
        $url = static::cgi_media_uri($access_token, $media_id);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));

        return $imageAll;

    }
606687
def media_update(self, id, description=None, focus=None):
        
        id = self.__unpack_id(id)

        if focus != None:
            focus = str(focus[0]) + "," + str(focus[1])
            
        params = self.__generate_params(locals(), ['id'])  
        return self.__api_request('PUT', '/api/v1/media/{0}'.format(str(id)), params)
327162
def download_permanent_media(self, media_id):
        
        return requests.post(
            url="https://api.weixin.qq.com/cgi-bin/material/get_material",
            params={"access_token": self.token},
            data=_json.dumps({
                "media_id": media_id
            }, ensure_ascii=False).encode("utf-8")
        )
237079
public DownloadMaterialResponse downloadMaterial(String mediaId, MaterialType type){
        DownloadMaterialResponse response = new DownloadMaterialResponse();
        String url = BASE_API_URL + "cgi-bin/material/get_material?access_token=" + config.getAccessToken();
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(NetWorkCenter.CONNECT_TIMEOUT).setConnectTimeout(NetWorkCenter.CONNECT_TIMEOUT).setSocketTimeout(NetWorkCenter.CONNECT_TIMEOUT).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpPost request = new HttpPost(url);
        StringEntity mediaEntity = new StringEntity("{\"media_id\":\"" + mediaId + "\"}", ContentType.APPLICATION_JSON);
        request.setEntity(mediaEntity);

        CloseableHttpResponse httpResponse = null;
        try{
            httpResponse = client.execute(request);
            if(HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()){
                HttpEntity entity;
                String resultJson;
                switch (type){
                    case NEWS:
                        entity = httpResponse.getEntity();
                        resultJson = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                        response = JSONUtil.toBean(resultJson, DownloadMaterialResponse.class);
                        LOG.debug("-----------------请求成功-----------------");
                        LOG.debug("响应结果:");
                        LOG.debug(resultJson);
                        if (StrUtil.isBlank(response.getErrcode())) {
                            response.setErrcode("0");
                            response.setErrmsg(resultJson);
                        }
                        break;
                    case VIDEO:
                        entity = httpResponse.getEntity();
                        resultJson = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                        LOG.debug("-----------------请求成功-----------------");
                        LOG.debug("响应结果:");
                        LOG.debug(resultJson);
                        response = JSONUtil.toBean(resultJson, DownloadMaterialResponse.class);
                        if (StrUtil.isBlank(response.getErrcode())) {
                            response.setErrcode("0");
                            response.setErrmsg(resultJson);
                            // 通过down_url下载文件。文件放置在content中。通过writeTo方法获取
                            downloadVideo(response);
                        }
                        break;
                    default:
                        Header length = httpResponse.getHeaders("Content-Length")[0];
                        InputStream inputStream = httpResponse.getEntity().getContent();
                        response.setContent(inputStream, Integer.valueOf(length.getValue()));
                        break;
                }
            }else{
                response.setErrcode(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
                response.setErrmsg("请求失败");
            }
        } catch (IOException e) {
            LOG.error("IO流异常", e);
        } catch (Exception e) {
            LOG.error("其他异常", e);
        }

        return response;
    }
1173234
public function createMaterial()
    {
        $m = Material::factory( $this->materialsType, $this->materialsTable );
        $m->idcat = $this->id;
        return $m;
    }
983524
public function getMaterial($media_id, $outType = null)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";
        $this->registerApi($url, __FUNCTION__, func_get_args());
        $result = Tools::post($url, ['media_id' => $media_id]);
        if (json_decode($result)) {
            return Tools::json2arr($result);
        }
        return is_null($outType) ? $result : $outType($result);
    }
321094
public DownloadMaterialResponse getMaterial(String mediaId) {
		DownloadMaterialResponse materialresponse = null;
        String url = BASE_API_URL + "cgi-bin/material/get_material?access_token=#";
        Map<String, String> param = new HashMap<String, String>();
        param.put("media_id", mediaId);
        BaseResponse r = executePost(url, JSONUtil.toJson(param));
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        materialresponse = JSONUtil.toBean(resultJson, DownloadMaterialResponse.class);
        return materialresponse;
	}
392419
function modUpdatePreparedState( id ) {
        var visited = {};
        update( id );

        function update( id ) {
            if ( !modIs( id, MODULE_ANALYZED ) ) {
                return false;
            }
            if ( modIs( id, MODULE_PREPARED ) || visited[ id ] ) {
                return true;
            }

            visited[ id ] = 1;
            var module = modModules[ id ];
            var prepared = true;

            each(
                module.depMs,
                function ( dep ) {
                    return ( prepared = update( dep.absId ) );
                }
            );

            // 判断resource是否加载完成。如果resource未加载完成，则认为未准备好
            prepared && each(
                module.depRs,
                function ( dep ) {
                    prepared = !!(dep.absId && modIs( dep.absId, MODULE_DEFINED ));
                    return prepared;
                }
            );

            if ( prepared ) {
                module.state = MODULE_PREPARED;
            }

            return prepared;
        }
    }