index.vue 8.1 KB
Newer Older
d-u-a's avatar
d-u-a 已提交
1 2 3 4 5 6 7 8
<template>
  <uni-ad
    v-bind="attrs"
    v-on="$listeners"
  >
    <div
      ref="container"
      class="uni-ad-container"
d-u-a's avatar
d-u-a 已提交
9
      @click="_onhandle"
d-u-a's avatar
d-u-a 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    />
  </uni-ad>
</template>
<script>
import {
  subscriber
} from 'uni-mixins'

class AdConfig {
  static get instance () {
    if (this._instance == null) {
      this._instance = new AdConfig()
      this._instance._init()
    }
    return this._instance
  }

  constructor () {
    this._instance = null
    this._adConfig = null
    this._isLoading = false
    this._lastError = null
    this._callbacks = []
  }

d-u-a's avatar
d-u-a 已提交
35 36 37 38
  get adConfig () {
    return this._adConfig
  }

d-u-a's avatar
d-u-a 已提交
39 40 41 42 43 44 45
  get isExpired () {
    if (this._adConfig == null) {
      return true
    }
    return (Math.abs(Date.now() - this._adConfig.last) > this.CACHE_TIME)
  }

d-u-a's avatar
d-u-a 已提交
46 47 48 49 50 51
  _init () {
    var config = this._getConfig()
    if (config === null || !config.last) {
      return
    }

d-u-a's avatar
d-u-a 已提交
52
    if (!this.isExpired) {
d-u-a's avatar
d-u-a 已提交
53 54 55 56 57
      this._adConfig = config.data
    }
  }

  get (adpid, success, fail) {
d-u-a's avatar
d-u-a 已提交
58
    if (this._adConfig != null) {
d-u-a's avatar
d-u-a 已提交
59
      this._doCallback(adpid, success, fail)
d-u-a's avatar
d-u-a 已提交
60 61 62
      if (this.isExpired) {
        this._loadAdConfig(adpid)
      }
d-u-a's avatar
d-u-a 已提交
63 64 65
      return
    }

d-u-a's avatar
d-u-a 已提交
66 67 68 69 70 71 72
    this._callbacks.push({
      adpid: adpid,
      success: success,
      fail: fail
    })

    this._loadAdConfig(adpid)
d-u-a's avatar
d-u-a 已提交
73 74
  }

d-u-a's avatar
d-u-a 已提交
75 76
  _doCallback (adpid, success, fail) {
    var data = this._adConfig
d-u-a's avatar
d-u-a 已提交
77 78
    if (data[adpid]) {
      success(data[adpid])
d-u-a's avatar
d-u-a 已提交
79 80
    } else {
      fail(this.ERROR_INVALID_ADPID)
d-u-a's avatar
d-u-a 已提交
81 82 83
    }
  }

d-u-a's avatar
d-u-a 已提交
84
  _loadAdConfig (adpid) {
d-u-a's avatar
d-u-a 已提交
85 86 87 88 89 90 91 92
    if (this._isLoading === true) {
      return
    }
    this._isLoading = true

    uni.request({
      url: this.URL,
      method: 'GET',
d-u-a's avatar
d-u-a 已提交
93
      timeout: 5000,
d-u-a's avatar
d-u-a 已提交
94
      data: {
d-u-a's avatar
d-u-a 已提交
95 96
        d: location.hostname,
        a: adpid
d-u-a's avatar
d-u-a 已提交
97 98 99 100 101 102
      },
      dataType: 'json',
      success: (res) => {
        const rd = res.data
        if (rd.ret === 0) {
          const data = rd.data
d-u-a's avatar
d-u-a 已提交
103

d-u-a's avatar
d-u-a 已提交
104 105
          this._adConfig = data
          this._setConfig(data)
d-u-a's avatar
d-u-a 已提交
106 107 108 109 110

          this._callbacks.forEach(({ adpid, success, fail }) => {
            this._doCallback(adpid, success, fail)
          })
        } else {
d-u-a's avatar
d-u-a 已提交
111
          this._callbacks.forEach((i) => {
d-u-a's avatar
d-u-a 已提交
112
            i.fail({ errCode: rd.ret, errMsg: rd.msg })
d-u-a's avatar
d-u-a 已提交
113 114
          })
        }
d-u-a's avatar
d-u-a 已提交
115 116 117 118
        this._callbacks = []
      },
      fail: (err) => {
        this._callbacks.forEach((i) => {
d-u-a's avatar
d-u-a 已提交
119
          i.fail(err)
d-u-a's avatar
d-u-a 已提交
120 121
        })
        this._callbacks = []
d-u-a's avatar
d-u-a 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      },
      complete: (c) => {
        this._isLoading = false
      }
    })
  }

  _getConfig () {
    if (!navigator.cookieEnabled || !window.localStorage) {
      return null
    }
    var data = localStorage.getItem(this.KEY)
    return data ? JSON.parse(data) : null
  }

  _setConfig (data) {
    if (!navigator.cookieEnabled || !window.localStorage) {
      return null
    }
    localStorage.setItem(this.KEY, JSON.stringify({
      last: Date.now(),
      data: data
    }))
  }
}
Object.assign(AdConfig.prototype, {
d-u-a's avatar
d-u-a 已提交
148
  URL: '//qy5y9ee9ch8r87pg72w5.dcloud.net.cn/hcs',
d-u-a's avatar
d-u-a 已提交
149 150 151 152 153
  KEY: 'uni_app_ad_config',
  CACHE_TIME: 1000 * 60 * 10,
  ERROR_INVALID_ADPID: {
    '-5002': '无效adpid'
  }
d-u-a's avatar
d-u-a 已提交
154 155
})

d-u-a's avatar
d-u-a 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
class AdReport {
  static get instance () {
    if (this._instance == null) {
      this._instance = new AdReport()
      this._instance._init()
    }
    return this._instance
  }

  constructor () {
    this._instance = null
    this._adConfig = null
    this._guid = null
  }

  _init () {
    var config = this._getConfig()
    if (config !== null && config.guid) {
      this._guid = config.guid
      return
    }

    this._guid = this._newGUID()
    this._setConfig(this._guid)
  }

  get (data) {
    this._process(Object.assign(data, {
      d: location.hostname,
      i: this._guid
    }))
  }

  _process (data) {
    uni.request({
      url: this.URL,
      method: 'GET',
      data: data,
      dataType: 'json',
      success: () => {
      }
    })
  }

  _newGUID () {
    let guid = ''
    const format = 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx'
    for (let i = 0; i < format.length; i++) {
      if (format[i] === 'x') {
        guid += (Math.random() * 16 | 0).toString(16)
      } else {
        guid += format[i]
      }
    }
    return guid.toUpperCase()
  }

  _getConfig () {
    if (!navigator.cookieEnabled || !window.localStorage) {
      return null
    }
    var data = localStorage.getItem(this.KEY)
    return data ? JSON.parse(data) : null
  }

  _setConfig (guid) {
    if (!navigator.cookieEnabled || !window.localStorage) {
      return null
    }
    localStorage.setItem(this.KEY, JSON.stringify({
      last: Date.now(),
      guid: guid
    }))
  }
}
Object.assign(AdReport.prototype, {
  URL: '//hp66hwpyev7yx2hfughh.dcloud.net.cn/ahl',
  KEY: 'uni_app_ad_guid'
})

d-u-a's avatar
d-u-a 已提交
236
const adProvider = {
d-u-a's avatar
d-u-a 已提交
237 238
  hx: 'zswx_hx',
  ky: 'zswx_ky'
d-u-a's avatar
d-u-a 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
}

const CHECK_RENDER_DELAY = 1000
const CHECK_RENDER_RETRY = 3

export default {
  name: 'Ad',
  mixins: [subscriber],
  props: {
    adpid: {
      type: [Number, String],
      default: ''
    }
  },
  watch: {
    adpid (val) {
      if (val) {
        this._loadData(val)
      }
    }
  },
  mounted () {
    this._pl = []
    this._pd = {}
    this._pi = 0
    this._checkTimer = null
    this._checkTimerCount = 0
d-u-a's avatar
d-u-a 已提交
266
    this._loadData()
d-u-a's avatar
d-u-a 已提交
267 268 269 270 271
    AdReport.instance.get({
      h: __uniConfig.compilerVersion,
      a: this.adpid,
      at: 30
    })
d-u-a's avatar
d-u-a 已提交
272 273
  },
  beforeDestroy () {
d-u-a's avatar
d-u-a 已提交
274
    this._clearCheckTimer()
d-u-a's avatar
d-u-a 已提交
275 276 277
    this.$refs.container.innerHTML = ''
  },
  methods: {
d-u-a's avatar
d-u-a 已提交
278 279 280 281 282 283 284 285 286
    _onhandle (e) {
      this._report(41)
    },
    _reset () {
      this._pl = []
      this._pd = {}
      this._pi = 0
      this._clearCheckTimer()
      this.$refs.container.innerHTML = ''
d-u-a's avatar
d-u-a 已提交
287
    },
d-u-a's avatar
d-u-a 已提交
288
    _loadData (adpid) {
d-u-a's avatar
d-u-a 已提交
289
      this._reset()
d-u-a's avatar
d-u-a 已提交
290 291 292 293
      AdConfig.instance.get(adpid || this.adpid, (data) => {
        this._pd = data
        this._pl = data.psp.split(',')
        this._renderAd()
d-u-a's avatar
d-u-a 已提交
294
      }, (err) => {
d-u-a's avatar
d-u-a 已提交
295
        this.$trigger('error', {}, err)
d-u-a's avatar
d-u-a 已提交
296 297 298 299 300 301
      })
    },
    _renderAd () {
      if (this._pi > this._pl.length - 1) {
        return
      }
d-u-a's avatar
d-u-a 已提交
302

d-u-a's avatar
d-u-a 已提交
303 304 305 306 307 308 309 310 311 312 313
      var ap = this._pl[this._pi]
      var data = this._pd[ap]
      switch (ap) {
        case adProvider.hx:
          this._renderHX(data)
          break
        case adProvider.ky:
          this._renderKY(data)
          break
      }
    },
d-u-a's avatar
d-u-a 已提交
314 315 316 317 318 319 320 321
    _renderNext () {
      if (this._pi >= this._pl.length - 1) {
        return
      }

      this._pi++
      this._renderAd()
    },
d-u-a's avatar
d-u-a 已提交
322
    _renderHX (data) {
d-u-a's avatar
d-u-a 已提交
323 324 325 326 327
      if (document.querySelector('#' + adProvider.hx)) {
        this._renderNext()
        return
      }

d-u-a's avatar
d-u-a 已提交
328 329 330
      var ad = document.createElement('script')
      ad.src = data.src || data.url

d-u-a's avatar
d-u-a 已提交
331 332 333 334
      var adView = document.createElement('div')
      adView.setAttribute('id', adProvider.hx)
      adView.appendChild(ad)

d-u-a's avatar
d-u-a 已提交
335
      this.$refs.container.innerHTML = ''
d-u-a's avatar
d-u-a 已提交
336
      this.$refs.container.append(adView)
d-u-a's avatar
d-u-a 已提交
337

d-u-a's avatar
d-u-a 已提交
338
      this._startCheckTimer()
d-u-a's avatar
d-u-a 已提交
339 340 341 342 343 344 345 346
    },
    _renderKY (data) {
      var ad = document.createElement('script')
      ad.src = data.src || data.url

      this.$refs.container.innerHTML = ''
      this.$refs.container.append(ad)

d-u-a's avatar
d-u-a 已提交
347
      this._startCheckTimer()
d-u-a's avatar
d-u-a 已提交
348 349
    },
    _checkRender () {
d-u-a's avatar
d-u-a 已提交
350 351 352 353
      var hasContent = (this.$refs.container.children.length > 0 && this.$refs.container.clientHeight > 40)
      if (hasContent) {
        this._report(40)
      }
d-u-a's avatar
d-u-a 已提交
354 355 356 357 358
      return hasContent
    },
    _startCheckTimer () {
      this._clearCheckTimer()
      this._checkTimer = setInterval(() => {
d-u-a's avatar
d-u-a 已提交
359 360
        this._checkTimerCount++
        if (this._checkTimerCount >= CHECK_RENDER_RETRY) {
d-u-a's avatar
d-u-a 已提交
361
          this._clearCheckTimer()
d-u-a's avatar
d-u-a 已提交
362
          this._renderNext()
d-u-a's avatar
d-u-a 已提交
363 364
          return
        }
d-u-a's avatar
d-u-a 已提交
365

d-u-a's avatar
d-u-a 已提交
366
        if (this._checkRender()) {
d-u-a's avatar
d-u-a 已提交
367 368 369 370 371 372 373 374
          this._clearCheckTimer()
        }
      }, CHECK_RENDER_DELAY)
    },
    _clearCheckTimer () {
      this._checkTimerCount = 0
      if (this._checkTimer != null) {
        window.clearInterval(this._checkTimer)
d-u-a's avatar
d-u-a 已提交
375
        this._checkTimer = null
d-u-a's avatar
d-u-a 已提交
376
      }
d-u-a's avatar
d-u-a 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    },
    _report (type) {
      var taskId = ''
      if (this._pl.length > 0 && this._pi < this._pl.length) {
        var data = this._pd[this._pl[this._pi]]
        if (data) {
          taskId = data.task_id
        }
      }

      AdReport.instance.get({
        h: __uniConfig.compilerVersion,
        a: this.adpid,
        t: taskId,
        at: type
      })
d-u-a's avatar
d-u-a 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    }
  }
}
</script>

<style>
  uni-ad {
    display: block;
    overflow: hidden;
  }

  uni-ad[hidden] {
    display: none;
  }
</style>