import imageType from 'image-type';
import http from 'http';
import https from 'https';
import SimpleSchema from 'simpl-schema';
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { debug } from '/server/imports/debug';

export const checkImageUrl = Meteor.wrapAsync(checkImageUrlAsync);

function checkImageUrlAsync(url, callback) {
  debug.log('checkImageUrlAsync', url);
  check(url, String);
  if (! SimpleSchema.RegEx.Url.test(url)) {
    callback(new Meteor.Error(403, '「' + url + '」並非合法的網址！'));
  }
  const httpCallback = (res) => {
    let checkResult;
    res.once('data', (chunk) => {
      checkResult = imageType(chunk);
      res.destroy();
    });
    res.once('end', () => {
      if (checkResult) {
        callback(null, true);
      }
      else {
        callback(new Meteor.Error(403, '「' + url + '」並非合法的網址！'));
      }
    });
  };
  if (url.indexOf('https://') === 0) {
    https.get(url, httpCallback);
  }
  else {
    http.get(url, httpCallback);
  }
}

@@ -881,127 +881,526 @@
 ;%0A  
-%7D;%0A  if (url.indexOf('https://') === 0) %7B%0A    https.get(url, httpCallback);%0A  %7D%0A  else %7B%0A    http.get(url, httpCallback
+  res.on('error', () =%3E %7B%0A      callback(new Meteor.Error(403, '%E3%80%8C' + url + '%E3%80%8D%E4%B8%A6%E9%9D%9E%E5%90%88%E6%B3%95%E7%9A%84%E7%B6%B2%E5%9D%80%EF%BC%81'));%0A    %7D);%0A  %7D;%0A  const agent = false;%0A  const httpOptions = %7Burl, agent%7D;%0A  if (url.indexOf('https://') === 0) %7B%0A    const req = https.get(httpOptions, httpCallback);%0A    req.on('error', () =%3E %7B%0A      callback(new Meteor.Error(403, '%E3%80%8C' + url + '%E3%80%8D%E4%B8%A6%E9%9D%9E%E5%90%88%E6%B3%95%E7%9A%84%E7%B6%B2%E5%9D%80%EF%BC%81'));%0A    %7D);%0A  %7D%0A  else %7B%0A    const req = http.get(httpOptions, httpCallback);%0A    req.on('error', () =%3E %7B%0A      callback(new Meteor.Error(403, '%E3%80%8C' + url + '%E3%80%8D%E4%B8%A6%E9%9D%9E%E5%90%88%E6%B3%95%E7%9A%84%E7%B6%B2%E5%9D%80%EF%BC%81'));%0A    %7D
 );%0A 

修正上傳不合法的大小圖網址會造成server crash的bug。